Application.Run Método
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Começa a executar um ciclo padrão de mensagens de aplicação na thread atual.
Sobrecargas
| Name | Description |
|---|---|
| Run() |
Começa a executar um ciclo padrão de mensagens de aplicação no thread atual, sem formulário. |
| Run(ApplicationContext) |
Começa a executar um ciclo padrão de mensagens de aplicação na thread atual, com um ApplicationContext. |
| Run(Form) |
Começa a executar um ciclo padrão de mensagens de aplicação no thread atual e torna o formulário especificado visível. |
Run()
Começa a executar um ciclo padrão de mensagens de aplicação no thread atual, sem formulário.
public:
static void Run();
public static void Run();
static member Run : unit -> unit
Public Shared Sub Run ()
Exceções
Um ciclo principal de mensagens já está a correr neste tópico.
Observações
Numa aplicação baseada em Win32 ou no Windows Forms, um ciclo de mensagens é uma rotina no código que processa eventos do utilizador, como cliques de rato e pressionamentos de teclado. Toda aplicação baseada em Windows em execução requer um ciclo de mensagens ativo, chamado ciclo principal de mensagens. Quando o ciclo principal de mensagens é fechado, a aplicação encerra-se. Em Windows Forms, este ciclo é fechado quando o método Exit é chamado, ou quando o método ExitThread é chamado no thread que executa o loop principal da mensagem.
A maioria dos programadores de Windows Forms não precisará de usar esta versão do método. Deve usar a Run(Form) sobrecarga para iniciar uma candidatura com um formulário principal, de modo a que a candidatura termine quando o formulário principal estiver fechado. Para todas as outras situações, use a Run(ApplicationContext) sobrecarga, que suporta fornecer um ApplicationContext objeto para melhor controlo ao longo da vida útil da aplicação.
Ver também
Aplica-se a
Run(ApplicationContext)
Começa a executar um ciclo padrão de mensagens de aplicação na thread atual, com um ApplicationContext.
public:
static void Run(System::Windows::Forms::ApplicationContext ^ context);
public static void Run(System.Windows.Forms.ApplicationContext context);
static member Run : System.Windows.Forms.ApplicationContext -> unit
Public Shared Sub Run (context As ApplicationContext)
Parâmetros
- context
- ApplicationContext
Um ApplicationContext em que a aplicação é executada.
Exceções
Um ciclo principal de mensagens já está a correr neste tópico.
Exemplos
O exemplo apresenta dois formulários e sai da candidatura quando ambos estão encerrados. Quando a candidatura começa e termina, a posição de cada formulário é memorizada. Este exemplo demonstra como usar um ApplicationContext, juntamente com o Application.Run(context) método, para mostrar múltiplos formulários quando a aplicação começa.
A classe MyApplicationContext herda e ApplicationContext acompanha quando cada formulário está fechado, e sai do thread atual quando ambos estão. A classe armazena as posições de cada formulário para o utilizador. Os dados de posição do formulário são armazenados num ficheiro Appdata.txt intitulado que é criado na localização determinada por UserAppDataPath. O Main método chama Application.Run(context) para iniciar a aplicação dado o ApplicationContext.
O código para os AppForm1 formulários e AppForm2 não é apresentado para fins de brevidade. Consulte o resumo ApplicationContext da classe para a lista completa de códigos.
// The class that handles the creation of the application windows
ref class MyApplicationContext: public ApplicationContext
{
private:
int _formCount;
AppForm1^ _form1;
AppForm2^ _form2;
System::Drawing::Rectangle _form1Position;
System::Drawing::Rectangle _form2Position;
FileStream^ _userData;
public:
MyApplicationContext()
{
_formCount = 0;
// Handle the ApplicationExit event to know when the application is exiting.
Application::ApplicationExit += gcnew EventHandler( this, &MyApplicationContext::OnApplicationExit );
try
{
// Create a file that the application will store user specific data in.
_userData = gcnew FileStream( String::Concat( 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: {0}", dynamic_cast<String^>(e) );
// 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 = gcnew AppForm1;
_form1->Closed += gcnew EventHandler( this, &MyApplicationContext::OnFormClosed );
_form1->Closing += gcnew CancelEventHandler( this, &MyApplicationContext::OnFormClosing );
_formCount++;
_form2 = gcnew AppForm2;
_form2->Closed += gcnew EventHandler( this, &MyApplicationContext::OnFormClosed );
_form2->Closing += gcnew CancelEventHandler( this, &MyApplicationContext::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();
}
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 ( Exception^ )
{
}
}
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 ( dynamic_cast<AppForm1^>(sender) != nullptr )
_form1Position = (dynamic_cast<Form^>(sender))->Bounds;
else
if ( dynamic_cast<AppForm1^>(sender) != nullptr )
_form2Position = (dynamic_cast<Form^>(sender))->Bounds;
}
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();
}
}
bool WriteFormDataToFile()
{
// Write the form positions to the file.
UTF8Encoding^ encoding = gcnew UTF8Encoding;
RectangleConverter^ rectConv = gcnew RectangleConverter;
String^ form1pos = rectConv->ConvertToString( _form1Position );
String^ form2pos = rectConv->ConvertToString( _form2Position );
array<Byte>^dataToWrite = encoding->GetBytes( String::Concat( "~", 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 ( Exception^ )
{
// An error occurred while attempting to write, return false.
return false;
}
}
bool ReadFormDataFromFile()
{
// Read the form positions from the file.
UTF8Encoding^ encoding = gcnew UTF8Encoding;
String^ data;
if ( _userData->Length != 0 )
{
array<Byte>^dataToRead = gcnew array<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 = dynamic_cast<String^>(e);
// 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 = gcnew RectangleConverter;
String^ form1pos = data->Substring( 1, data->IndexOf( "~", 1 ) - 1 );
_form1Position = *safe_cast<Rectangle^>(rectConv->ConvertFromString( form1pos ));
String^ form2pos = data->Substring( data->IndexOf( "~", 1 ) + 1 );
_form2Position = *safe_cast<Rectangle^>(rectConv->ConvertFromString( form2pos ));
return true;
}
catch ( Exception^ )
{
// 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;
}
}
};
// The class that handles the creation of the application windows
class MyApplicationContext : 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.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();
}
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 { }
}
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 is AppForm1)
_form1Position = ((Form)sender).Bounds;
else if (sender is AppForm2)
_form2Position = ((Form)sender).Bounds;
}
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();
}
}
private bool 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);
return true;
}
catch
{
// An error occurred while attempting to write, return false.
return false;
}
}
private bool 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.
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
{
// 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;
}
}
[STAThread]
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);
}
}
' The class that handles the creation of the application windows
Public Class MyApplicationContext
Inherits ApplicationContext
Private _formCount As Integer
Private _form1 As AppForm1
Private _form2 As AppForm2
Private _form1Position As Rectangle
Private _form2Position As Rectangle
Private _userData As FileStream
Public Sub New()
MyBase.New()
_formCount = 0
' Handle the ApplicationExit event to know when the application is exiting.
AddHandler Application.ApplicationExit, AddressOf OnApplicationExit
Try
' Create a file that the application will store user specific data in.
_userData = New FileStream(Application.UserAppDataPath + "\appdata.txt", FileMode.OpenOrCreate)
Catch e As IOException
' 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()
End Try
' Create both application forms and handle the Closed event
' to know when both forms are closed.
_form1 = New AppForm1()
AddHandler _form1.Closed, AddressOf OnFormClosed
AddHandler _form1.Closing, AddressOf OnFormClosing
_formCount = _formCount + 1
_form2 = New AppForm2()
AddHandler _form2.Closed, AddressOf OnFormClosed
AddHandler _form2.Closing, AddressOf OnFormClosing
_formCount = _formCount + 1
' Get the form positions based upon the user specific data.
If (ReadFormDataFromFile()) Then
' 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
End If
' Show both forms.
_form1.Show()
_form2.Show()
End Sub
Private Sub OnApplicationExit(ByVal sender As Object, ByVal e As EventArgs)
' 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
End Try
End Sub
Private Sub OnFormClosing(ByVal sender As Object, ByVal e As CancelEventArgs)
' When a form is closing, remember the form position so it
' can be saved in the user data file.
If TypeOf sender Is AppForm1 Then
_form1Position = CType(sender, Form).Bounds
ElseIf TypeOf sender Is AppForm2 Then
_form2Position = CType(sender, Form).Bounds
End If
End Sub
Private Sub OnFormClosed(ByVal sender As Object, ByVal e As EventArgs)
' When a form is closed, decrement the count of open forms.
' When the count gets to 0, exit the app by calling
' ExitThread().
_formCount = _formCount - 1
If (_formCount = 0) Then
ExitThread()
End If
End Sub
Private Function WriteFormDataToFile() As Boolean
' Write the form positions to the file.
Dim encoding As UTF8Encoding = New UTF8Encoding()
Dim rectConv As RectangleConverter = New RectangleConverter()
Dim form1pos As String = rectConv.ConvertToString(_form1Position)
Dim form2pos As String = rectConv.ConvertToString(_form2Position)
Dim dataToWrite As Byte() = 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
' An error occurred while attempting to write, return false.
Return False
End Try
End Function
Private Function ReadFormDataFromFile() As Boolean
' Read the form positions from the file.
Dim encoding As UTF8Encoding = New UTF8Encoding()
Dim data As String
If (_userData.Length <> 0) Then
Dim dataToRead(_userData.Length) As Byte
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 e As IOException
Dim errorInfo As String = e.ToString()
' An error occurred while attempt to read, return false.
Return False
End Try
' Parse out the data to get the window rectangles
data = encoding.GetString(dataToRead)
Try
' Convert the string data to rectangles
Dim rectConv As RectangleConverter = New RectangleConverter()
Dim form1pos As String = data.Substring(1, data.IndexOf("~", 1) - 1)
_form1Position = CType(rectConv.ConvertFromString(form1pos), Rectangle)
Dim form2pos As String = data.Substring(data.IndexOf("~", 1) + 1)
_form2Position = CType(rectConv.ConvertFromString(form2pos), Rectangle)
Return True
Catch
' Error occurred while attempting to convert the rectangle data.
' Return false to use default values.
Return False
End Try
Else
' No data in the file, return false to use default values.
Return False
End If
End Function
End Class
Public Module MyApplication
Public Sub Main()
' Create the MyApplicationContext, that derives from ApplicationContext,
' that manages when the application should exit.
Dim context As MyApplicationContext = New MyApplicationContext()
' Run the application with the specific context. It will exit when
' all forms are closed.
Application.Run(context)
End Sub
End Module
Observações
O loop de mensagens corre até Exit ou ExitThread ser chamado ou o ThreadExit evento ser gerado no objeto de contexto.
Ver também
Aplica-se a
Run(Form)
Começa a executar um ciclo padrão de mensagens de aplicação no thread atual e torna o formulário especificado visível.
public:
static void Run(System::Windows::Forms::Form ^ mainForm);
public static void Run(System.Windows.Forms.Form mainForm);
static member Run : System.Windows.Forms.Form -> unit
Public Shared Sub Run (mainForm As Form)
Parâmetros
Exceções
Um loop principal de mensagens já está a correr na thread atual.
Exemplos
O seguinte exemplo de código lista números numa caixa de lista num formulário. Cada vez que clica button1, a aplicação adiciona mais um número à lista.
O Main método chama Run para iniciar a aplicação, que cria o formulário, listBox1, e button1. Quando o utilizador clica button1em , o button1_Click método soma números de um a três à caixa da lista e mostra um MessageBox. Se o utilizador clicar em Não no MessageBox, o button1_Click método adiciona outro número à lista. Se o utilizador clicar em Sim, a aplicação chama Exit para processar todas as mensagens restantes na fila e depois para sair.
O exemplo requer que listBox1 e button1 tenham sido criados e colocados num formulário.
public:
static void main()
{
// Starts the application.
Application::Run( gcnew Form1 );
}
private:
void button1_Click( Object^ sender, System::EventArgs^ e )
{
// Populates a list box with three numbers.
int i = 3;
for ( int j = 1; j <= i; j++ )
{
listBox1->Items->Add( j );
}
/* Determines whether the user wants to exit the application.
* If not, adds another number to the list box. */
while ( MessageBox::Show( "Exit application?", "",
MessageBoxButtons::YesNo ) == ::DialogResult::No )
{
// Increments the counter ands add the number to the list box.
i++;
listBox1->Items->Add( i );
}
// The user wants to exit the application. Close everything down.
Application::Exit();
}
public static void Main(string[] args) {
// Starts the application.
Application.Run(new Form1());
}
private void button1_Click(object sender, System.EventArgs e) {
// Populates a list box with three numbers.
int i = 3;
for(int j=1; j<=i; j++) {
listBox1.Items.Add(j);
}
/* Determines whether the user wants to exit the application.
* If not, adds another number to the list box. */
while (MessageBox.Show("Exit application?", "", MessageBoxButtons.YesNo) ==
DialogResult.No) {
// Increments the counter ands add the number to the list box.
i++;
listBox1.Items.Add(i);
}
// The user wants to exit the application. Close everything down.
Application.Exit();
}
<STAThread()> _
Shared Sub Main()
' Starts the application.
Application.Run(New Form1())
End Sub
Private Sub button1_Click(sender As object, e As System.EventArgs)
' Populates a list box with three numbers.
Dim i As Integer = 3
Dim j As Integer
For j = 1 To i - 1
listBox1.Items.Add(j)
Next
' Checks to see whether the user wants to exit the application.
' If not, adds another number to the list box.
While (MessageBox.Show("Exit application?", "", MessageBoxButtons.YesNo) = _
DialogResult.No)
' Increments the counter and adds the number to the list box.
i = i + 1
listBox1.Items.Add(i)
End While
' The user wants to exit the application. Close everything down.
Application.Exit()
End Sub
Observações
Normalmente, a função principal de uma aplicação chama este método e passa-lhe a janela principal da aplicação.
Este método adiciona um gestor de eventos ao mainForm parâmetro do Closed evento. O gestor de eventos chama ExitThread para limpar a aplicação.