Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês
Esta documentação foi arquivada e não está sendo atualizada.

Método Application.Run (ApplicationContext)

Começa a executar um loop de mensagem padrão do aplicativo no thread corrente, com um ApplicationContext.

Namespace:  System.Windows.Forms
Assembly:  System.Windows.Forms (em System.Windows.Forms.dll)

public static void Run(
	ApplicationContext context
)

Parâmetros

context
Tipo: System.Windows.Forms.ApplicationContext
An ApplicationContext em que o aplicativo é executado.

ExceçãoCondição
InvalidOperationException

Um loop de mensagem principal já está sendo executada neste thread.

O loop de mensagens é executado até Exit ou ExitThread é chamado ou a ThreadExit evento é gerado no objeto de contexto.

O exemplo exibe dois formulários e sai do aplicativo quando ambos os formulários forem fechados.Quando o aplicativo começa e termina, a posição de cada formulário será lembrada.Este exemplo demonstra como usar um ApplicationContext, juntamente com o Application.Run(context) método, para exibir vários formulários quando o aplicativo é iniciado.

A classe MyApplicationContext herda do ApplicationContext e mantém controle quando cada formulário é fechado e sai do segmento corrente quando os dois estão. A classe armazena as posições de cada formulário do usuário.Os dados de posição do formulário são armazenados em um arquivo chamado Appdata.txt que é criada no local determinado pelo UserAppDataPath. The Main chamadas de método Application.Run(context) Para iniciar o aplicativo recebe o ApplicationContext.

O código para o AppForm1 e AppForm2 formulários não é mostrada para fins de brevidade. Consulte o ApplicationContext Visão geral de classe para a listagem de código inteiro.

// The class that handles the creation of the application windowsclass MyApplicationContext : ApplicationContext {

    privateint formCount;
    private AppForm1 form1;
    private AppForm2 form2;

    private Rectangle form1Position;
    private Rectangle form2Position;

    private FileStream userData;

    private MyApplicationContext() {
        formCount = 0;

        // Handle the ApplicationExit event to know when the application is exiting.
        Application.ApplicationExit += new EventHandler(this.OnApplicationExit);

        try {
            // Create a file that the application will store user specific data in.
            userData = new FileStream(Application.UserAppDataPath + "\\appdata.txt", FileMode.OpenOrCreate);

        } catch(IOException e) {
            // Inform the user that an error occurred.
            MessageBox.Show("An error occurred while attempting to show the application." + 
                            "The error is:" + e.ToString());

            // Exit the current thread instead of showing the windows.
            ExitThread();
        }

        // Create both application forms and handle the Closed event// to know when both forms are closed.
        form1 = new AppForm1();
        form1.Closed += new EventHandler(OnFormClosed);            
        form1.Closing += new CancelEventHandler(OnFormClosing);            
        formCount++;

        form2 = new AppForm2();
        form2.Closed += new EventHandler(OnFormClosed);            
        form2.Closing += new CancelEventHandler(OnFormClosing);            
        formCount++;

        // Get the form positions based upon the user specific data.if (ReadFormDataFromFile()) {
            // If the data was read from the file, set the form// positions manually.
            form1.StartPosition = FormStartPosition.Manual;
            form2.StartPosition = FormStartPosition.Manual;

            form1.Bounds = form1Position;
            form2.Bounds = form2Position;
        }

        // Show both forms.
        form1.Show();
        form2.Show();
    }

    privatevoid OnApplicationExit(object sender, EventArgs e) {
        // When the application is exiting, write the application data to the// user file and close it.
        WriteFormDataToFile();

        try {
            // Ignore any errors that might occur while closing the file handle.
            userData.Close();
        } catch {}
    }

    privatevoid OnFormClosing(object sender, CancelEventArgs e) {
        // When a form is closing, remember the form position so it// can be saved in the user data file.if (sender is AppForm1) 
            form1Position = ((Form)sender).Bounds;
        elseif (sender is AppForm2)
            form2Position = ((Form)sender).Bounds;
    }

    privatevoid OnFormClosed(object sender, EventArgs e) {
        // When a form is closed, decrement the count of open forms.// When the count gets to 0, exit the app by calling// ExitThread().
        formCount--;
        if (formCount == 0) {
            ExitThread();
        }
    }

    privatebool WriteFormDataToFile(){
        // Write the form positions to the file.
        UTF8Encoding encoding = new UTF8Encoding();

        RectangleConverter rectConv = new RectangleConverter();
        String form1pos = rectConv.ConvertToString(form1Position);
        String form2pos = rectConv.ConvertToString(form2Position);

        byte[] dataToWrite = encoding.GetBytes("~" + form1pos + "~" + form2pos);

        try {
            // Set the write position to the start of the file and write
            userData.Seek(0,SeekOrigin.Begin);
            userData.Write(dataToWrite, 0, dataToWrite.Length);
            userData.Flush();

            userData.SetLength(dataToWrite.Length);
            returntrue;

        } catch {
            // An error occurred while attempting to write, return false.returnfalse;
        }

    }

    privatebool ReadFormDataFromFile(){
        // Read the form positions from the file.
        UTF8Encoding encoding = new UTF8Encoding();
        String data;

        if (userData.Length != 0) {
            byte[] dataToRead = new Byte[userData.Length];

            try {
                // Set the read position to the start of the file and read.
                userData.Seek(0, SeekOrigin.Begin);
                userData.Read(dataToRead, 0, dataToRead.Length);

            } catch (IOException e) {
                String errorInfo = e.ToString();
                // An error occurred while attempt to read, return false.returnfalse;
            }

            // Parse out the data to get the window rectangles
            data = encoding.GetString(dataToRead);

            try {
                // Convert the string data to rectangles
                RectangleConverter rectConv = new RectangleConverter();
                String form1pos = data.Substring(1,data.IndexOf("~",1)-1);

                form1Position = (Rectangle)rectConv.ConvertFromString(form1pos);

                String form2pos = data.Substring(data.IndexOf("~",1)+1);
                form2Position = (Rectangle)rectConv.ConvertFromString(form2pos);

                returntrue;

            } catch {
                // Error occurred while attempting to convert the rectangle data.// Return false to use default values.returnfalse;
            }

        } else {
            // No data in the file, return false to use default values.returnfalse;
        }
    }        

    [STAThread]
    staticvoid Main(string[] args) {

        // Create the MyApplicationContext, that derives from ApplicationContext,// that manages when the application should exit.

        MyApplicationContext context = new MyApplicationContext();

        // Run the application with the specific context. It will exit when// all forms are closed.
        Application.Run(context);

    }
}


// The class that handles the creation of the application windows
class MyApplicationContext extends ApplicationContext
{
    private int formCount;
    private AppForm1 form1;
    private AppForm2 form2;
    private Rectangle form1Position;
    private Rectangle form2Position;
    private FileStream userData;

    private MyApplicationContext()
    {
        formCount = 0;

        // Handle the ApplicationExit event to know 
        // when the application is exiting.
        Application.add_ApplicationExit(new EventHandler(
            this.OnApplicationExit));
        try {
            // Create a file that the application will store 
            // user specific data in.
            userData = new FileStream(Application.get_UserAppDataPath() 
                + "\\appdata.txt", FileMode.OpenOrCreate);
        }
        catch (IOException e) {
            // Inform the user that an error occurred.
            MessageBox.Show("An error occurred while attempting to show the "
                + " application. The error is:" + e.ToString());

            // Exit the current thread instead of showing the windows.
            ExitThread();
        }

        // Create both application forms and handle the Closed event
        // to know when both forms are closed.
        form1 = new AppForm1();
        form1.add_Closed(new EventHandler(OnFormClosed));
        form1.add_Closing(new CancelEventHandler(OnFormClosing));
        formCount++;
        form2 = new AppForm2();
        form2.add_Closed(new EventHandler(OnFormClosed));
        form2.add_Closing(new CancelEventHandler(OnFormClosing));
        formCount++;

        // Get the form positions based upon the user specific data.
        if (ReadFormDataFromFile()) {
            // If the data was read from the file, set the form
            // positions manually.
            form1.set_StartPosition(FormStartPosition.Manual);
            form2.set_StartPosition(FormStartPosition.Manual);
            form1.set_Bounds(form1Position);
            form2.set_Bounds(form2Position);
        }

        // Show both forms.
        form1.Show();
        form2.Show();
    } //MyApplicationContext

    private void OnApplicationExit(Object sender, EventArgs e)
    {
        // When the application is exiting, write the application data to the
        // user file and close it.
        WriteFormDataToFile();
        try {
            // Ignore any errors that might occur while closing the file handle.
            userData.Close();
        }
        catch (System.Exception exp) {
        }
    } //OnApplicationExit

    private void OnFormClosing(Object sender, CancelEventArgs e)
    {
        // When a form is closing, remember the form position so it
        // can be saved in the user data file.
        if (sender instanceof AppForm1) {
            form1Position = ((Form)sender).get_Bounds();
        }
        else {
            if (sender instanceof AppForm2) {
                form2Position = ((Form)sender).get_Bounds();
            }
        }
    } //OnFormClosing

    private void OnFormClosed(Object sender, EventArgs e)
    {
        // When a form is closed, decrement the count of open forms.
        // When the count gets to 0, exit the app by calling
        // ExitThread().
        formCount--;
        if (formCount == 0) {
            ExitThread();
        }
    } //OnFormClosed

    private boolean WriteFormDataToFile()
    {
        // Write the form positions to the file.
        UTF8Encoding encoding = new UTF8Encoding();
        RectangleConverter rectConv = new RectangleConverter();
        String form1Pos = rectConv.ConvertToString(form1Position);
        String form2Pos = rectConv.ConvertToString(form2Position);
        ubyte dataToWrite[] = encoding.GetBytes("~" + form1Pos + "~" 
            + form2Pos);

        try {
            // Set the write position to the start of the file and write
            userData.Seek(0, SeekOrigin.Begin);
            userData.Write(dataToWrite, 0, dataToWrite.length);
            userData.Flush();
            userData.SetLength(dataToWrite.length);
            return true;
        }
        catch (System.Exception exp) {
            // An error occurred while attempting to write, return false.
            return false;
        }
    } //WriteFormDataToFile

    private boolean ReadFormDataFromFile()
    {
        // Read the form positions from the file.
        UTF8Encoding encoding = new UTF8Encoding();
        String data;

        if (userData.get_Length() != 0) {
            ubyte dataToRead[] = new ubyte[(int)userData.get_Length()];

            try {
                // Set the read position to the start of the file and read.
                userData.Seek(0, SeekOrigin.Begin);
                userData.Read(dataToRead, 0, dataToRead.length);
            }
            catch (IOException e) {
                String errorInfo = e.ToString();

                // An error occurred while attempt to read, return false.
                return false;
            }

            // Parse out the data to get the window rectangles
            data = encoding.GetString(dataToRead);
            try {
                // Convert the string data to rectangles
                RectangleConverter rectConv = new RectangleConverter();
                String form1Pos = data.Substring(1, data.IndexOf("~", 1) - 1);
                form1Position = 
                    (Rectangle)(rectConv.ConvertFromString(form1Pos));

                String form2Pos = data.Substring(data.IndexOf("~", 1) + 1);
                form2Position = 
                    (Rectangle)(rectConv.ConvertFromString(form2Pos));
                return true;
            }
            catch (System.Exception exp) {
                // Error occurred while attempting to convert the rectangle data.
                // Return false to use default values.
                return false;
            }
        }
        else {
            // No data in the file, return false to use default values.
            return false;
        }
    } //ReadFormDataFromFile

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        // Create the MyApplicationContext, that derives from
        // ApplicationContext, that manages when the application should exit.
        MyApplicationContext context = new MyApplicationContext();

        // Run the application with the specific context. It will exit when
        // all forms are closed.
        Application.Run(context);
    } //main 
} //MyApplicationContext


Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

o.NET Framework e.NET Compact Framework não oferecem suporte a todas as versões de cada plataforma. Para obter uma lista de versões suportadas, consulte Requisitos de sistema do .NET framework.

.NET Framework

Compatível com: 3.5, 3.0, 2.0, 1.1, 1.0
Mostrar: