Application.Run 方法

定义

在当前线程上开始运行标准应用程序消息循环。

重载

Run()

在没有窗体的情况下,在当前线程上开始运行标准应用程序消息循环。

Run(ApplicationContext)

在特定的 ApplicationContext 中,在当前线程上开始运行标准应用程序消息循环。

Run(Form)

在当前线程上开始运行标准应用程序消息循环,并使指定窗体可见。

Run()

Source:
Application.cs
Source:
Application.cs
Source:
Application.cs

在没有窗体的情况下,在当前线程上开始运行标准应用程序消息循环。

C#
public static void Run();

例外

主消息循环已在此线程上运行。

注解

在基于 Win32 的应用程序或Windows 窗体应用程序中,消息循环是代码中的一个例程,用于处理用户事件,例如鼠标单击和键盘笔划。 每个正在运行的基于 Windows 的应用程序都需要一个活动消息循环,称为main消息循环。 关闭main消息循环时,应用程序将退出。 在 Windows 窗体 中,当调用 方法或在运行main消息循环的线程上调用 该方法时ExitThread,此循环将关闭Exit

大多数Windows 窗体开发人员不需要使用此版本的 方法。 应使用Run(Form)重载启动具有main窗体的应用程序,以便在关闭main窗体时终止应用程序。 对于所有其他情况,请使用 Run(ApplicationContext) 重载,它支持提供 ApplicationContext 对象以更好地控制应用程序的生存期。

另请参阅

适用于

.NET Framework 4.8.1 和其他版本
产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

Run(ApplicationContext)

Source:
Application.cs
Source:
Application.cs
Source:
Application.cs

在特定的 ApplicationContext 中,在当前线程上开始运行标准应用程序消息循环。

C#
public static void Run(System.Windows.Forms.ApplicationContext context);

参数

context
ApplicationContext

一个 ApplicationContext,应用程序将在其中运行。

例外

主消息循环已在此线程上运行。

示例

该示例显示两个窗体,并在两个窗体关闭时退出应用程序。 应用程序启动和退出时,会记住每个窗体的位置。 此示例演示如何使用 ApplicationContextApplication.Run(context) 方法在应用程序启动时显示多个窗体。

MyApplicationContext 继承自 ApplicationContext 并跟踪每个窗体何时关闭,并在它们都关闭时退出当前线程。 类存储用户每个窗体的位置。 表单位置数据存储在由 确定UserAppDataPath的位置中创建的标题Appdata.txt为 的文件中。 方法 Main 调用 Application.Run(context) 以在给定 的情况下 ApplicationContext启动应用程序。

为了简洁起见, AppForm1 不显示 和 AppForm2 窗体的代码。 有关整个代码列表, ApplicationContext 请参阅类概述。

C#
// 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);
    }
}

注解

消息循环将一直运行,直到Exit调用 或 ThreadExitExitThread 在上下文对象上引发事件。

另请参阅

适用于

.NET Framework 4.8.1 和其他版本
产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

Run(Form)

Source:
Application.cs
Source:
Application.cs
Source:
Application.cs

在当前线程上开始运行标准应用程序消息循环,并使指定窗体可见。

C#
public static void Run(System.Windows.Forms.Form mainForm);

参数

mainForm
Form

一个 Form,它代表要使之可见的窗体。

例外

主消息循环已在当前线程上运行。

示例

下面的代码示例列出窗体上的列表框中的数字。 每次单击 button1时,应用程序都会向列表中添加另一个数字。

方法 Main 调用 Run 以启动应用程序,该应用程序将创建窗体 、 listBox1button1。 当用户单击 button1时, 方法将 button1_Click 数字 1 到 3 添加到列表框,并显示 MessageBox。 如果用户在 上MessageBox单击“”,则 方法会将button1_Click另一个数字添加到列表中。 如果用户单击“ ”,应用程序会调用 Exit 处理队列中所有剩余的消息,然后退出。

该示例要求 listBox1 已创建 和 button1 并将其放置在窗体上。

C#
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();
 }

注解

通常,应用程序的 main 函数调用此方法,并将应用程序main窗口传递给它。

此方法将事件处理程序添加到 mainForm 事件的 参数 Closed 中。 事件处理程序调用 ExitThread 以清理应用程序。

备注

FormDispose返回此方法之前,将调用 类的 方法。

另请参阅

适用于

.NET Framework 4.8.1 和其他版本
产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10