c#利用ApplicationContext類 同時啓動雙窗體的實現

Application類(位於System.Windows.Forms命名空間)公開了Run方法,能夠調用該方法來調度應用程序進入消息循環。Run方法有三個重載html

一、第一個重載版本不帶任何參數,比較少使用app

二、static void Run(System.Windows.Forms.Form mainForm)  調用這個重載,只須要吧但願做爲主窗口的Form實例(包括從Form類派生的類)傳遞給mianForm參數便可。一旦mainForm關閉,整個消息循環就會退出,Run方法返回,應用程序就會退出。函數

三、static void Run(System.Windows.Forms.ApplicationContext context) 這是Run方法中重載最靈活的。一般的作法是從ApplicationContext類派生,並寫入實現代碼。ApplicationContext類也容許設置一個Form實例製做爲主窗口,也能夠不設置主窗口。這個Run方法會在ApplicationContext對象進行消息循環。調用ApplicationContext類的ExitThread方法會致使ApplicationContext上的消息循環終止。post

  

手動建立一個類:產生三個窗口,只有把三個窗口所有關閉程序才終止運行(基於第三種Run方法)this

複製代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;


//從ApplicationContext派生一個類出來,
public class MyApplication : ApplicationContext
{

    static int WindowsCount;//用於記錄窗口個數
    private Form Windows1, Windows2, Windows3;//申請三個Form窗口  private只限於本類成員訪問

    //構造函數,分別實例化三個窗口
    public MyApplication()
    {
        WindowsCount = 0;
        /*實例化Windows1*/
        Windows1 = new Form();
        Windows1.Text = "窗口1";
        Windows1.Size = new System.Drawing.Size(300, 300);
        Windows1.Location = new System.Drawing.Point(50, 100);
        Windows1.Name = "Form1";
        Windows1.FormClosed += OnMainFormClosed;//處理事件(窗口關閉的處理事件)
        WindowsCount += 1;//窗口總數加一

        Windows2 = new Form();
        Windows2.Text = "窗口2";
        Windows2.Size = new System.Drawing.Size(300, 300);
        Windows2.Location = new System.Drawing.Point(50, 100);
        Windows2.Name = "Form2";
        Windows2.FormClosed += OnMainFormClosed;//處理事件(窗口關閉的處理事件)
        WindowsCount += 1;//窗口總數加一

        Windows3 = new Form();
        Windows3.Text = "窗口3";
        Windows3.Size = new System.Drawing.Size(300, 300);
        Windows3.Location = new System.Drawing.Point(50, 100);
        Windows3.Name = "Form3";
        Windows3.FormClosed += OnMainFormClosed;//處理事件(窗口關閉的處理事件)
        WindowsCount += 1;//窗口總數加一

        //顯示3個窗口
        Windows1.Show();
        Windows2.Show();
        Windows3.Show();      

    }
    private void OnMainFormClosed(object sender,FormClosedEventArgs e)
    {
        WindowsCount -= 1;
        if (WindowsCount == 0)
            ExitThread();//調用ExitThead終止消息循環

    }

}
namespace application1
{
    static class Program
    {
        /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MyApplication());
        }
    }
}
複製代碼

 

 

 

 

 

 

出處:https://www.cnblogs.com/hjxzjp/p/7674300.htmlspa

===============================================================.net

下面的代碼示例顯示兩個窗體,並在兩個窗體都關閉時退出應用程序。在應用程序啓動和退出時,它會記住每一個窗體的位置。此示例演示如何使用 ApplicationContextApplication.Run(context) 方法在啓動應用程序時顯示多個窗體。線程

MyApplicationContextApplicationContext 繼承,並跟蹤每一個窗體關閉的時間,而後在這兩個窗體均關閉時退出當前線程。該類爲用戶存儲每一個窗體的位置。窗體位置數據存儲在標題爲 Appdata.txt 的文件中,該文件在 UserAppDataPath 肯定的位置中建立。code

給定 ApplicationContext 的狀況下,Main 方法調用 Application.Run(context) 啓動應用程序。orm

using System;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Text;
using System.IO;

namespace ScreenSplit
{
    static class Program
    {
        // 初始化窗體1大小及標題文本
        public class AppForm1 : System.Windows.Forms.Form
        {
            public AppForm1()
            {
                Screen screen = Screen.FromRectangle(new Rectangle(0, 0, 0, 0));
                this.Size = new System.Drawing.Size(screen.WorkingArea.Width / 2, screen.WorkingArea.Height);
                this.Text = "AppForm1";
            }
        }

        // 初始化窗體2大小及標題文本
        public class AppForm2 : System.Windows.Forms.Form
        {
            public AppForm2()
            {
                Screen screen = Screen.FromRectangle(new Rectangle(0, 0, 0, 0));
                this.Size = new System.Drawing.Size(screen.WorkingArea.Width / 2, screen.WorkingArea.Height);
                this.Text = "AppForm2";
            }
        }

        // 利用ApplicationContext類處理程序的啓動、關閉
        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;

                // 應用程序退出
                Application.ApplicationExit += new EventHandler(this.OnApplicationExit);

                try
                {
                    // 在用戶目錄使用appdata.txt文件保存窗體退出時的位置與大小
                    userData = new FileStream(Application.UserAppDataPath + "//appdata.txt", FileMode.OpenOrCreate);

                }
                catch (IOException e)
                {
                    // 程序退出時異常處理.
                    MessageBox.Show("An error occurred while attempting to show the application." +
                                    "The error is:" + e.ToString());

                    // 退出當前主線程
                    ExitThread();
                }

                //窗體關閉
                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++;

                // 從文件中讀取保存窗體位置與大小的參數
                if (ReadFormDataFromFile())
                {
                    Screen screen = Screen.FromRectangle(new Rectangle(0, 0, 0, 0));
                    form1.Top = 0; form1.Left = 0;
                    form2.Top = 0; form2.Left = screen.WorkingArea.Width / 2;
                    form1.StartPosition = FormStartPosition.Manual;
                    form2.StartPosition = FormStartPosition.Manual;

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

                // 顯示雙窗體
                form1.Show();
                form2.Show();
            }

            private void OnApplicationExit(object sender, EventArgs e)
            {
                // 保存窗體位置與大小
                WriteFormDataToFile();

                try
                {
                    // 忽略窗體關閉時可能出現的錯誤
                    userData.Close();
                }
                catch { }
            }

            private void OnFormClosing(object sender, CancelEventArgs e)
            {
                // 保存窗體位置與大小
                if (sender is AppForm1)
                    form1Position = ((Form)sender).Bounds;
                else if (sender is AppForm2)
                    form2Position = ((Form)sender).Bounds;
            }

            private void OnFormClosed(object sender, EventArgs e)
            {
                // 關閉全部窗體,退出主線程
                formCount--;
                if (formCount == 0)
                {
                    ExitThread();
                }
            }

            private bool WriteFormDataToFile()
            {
                // 保存窗體位置與大小到用戶文件
                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
                {
                    userData.Seek(0, SeekOrigin.Begin);
                    userData.Write(dataToWrite, 0, dataToWrite.Length);
                    userData.Flush();

                    userData.SetLength(dataToWrite.Length);
                    return true;

                }
                catch
                {
                    return false;
                }

            }

            private bool ReadFormDataFromFile()
            {
                // 從文件中讀取窗體大小與位置
                UTF8Encoding encoding = new UTF8Encoding();
                String data;

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

                    try
                    {
                        userData.Seek(0, SeekOrigin.Begin);
                        userData.Read(dataToRead, 0, dataToRead.Length);

                    }
                    catch (IOException e)
                    {
                        String errorInfo = e.ToString();
                        return false;
                    }
                   
                    data = encoding.GetString(dataToRead);

                    try
                    {
                        // 轉換數據文件爲 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
                    {
                        return false;
                    }

                }
                else
                {
                    // 無數據文件時,缺省窗體位置與大小
                    return false;
                }
            }

            [STAThread]
            static void Main(string[] args)
            {
                MyApplicationContext context = new MyApplicationContext();
                Application.Run(context);
            }
        }

    }
}

//以上代碼保存成Program.cs,修改form名稱後能夠直接使用。源自MSDN,稍做修改

 

出處:https://blog.csdn.net/guohu99/article/details/5115757

相關文章
相關標籤/搜索