WINFORM学习手册——SDI应用

一、新建一个解决方案,将menustrip和toolstrip拖入主窗体:

image

二、在SdiForm.cs里面写入如下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Sdi
{
    public partial class SdiForm : Form
    {
        public SdiForm()
        {
            InitializeComponent();
        }
        public static int Count = 0;//记录窗体数量
        /// <summary>
        /// 创建窗体
        /// </summary>
        public static SdiForm CreateForm()
        {
            SdiForm form = new SdiForm();
            form.Text = "窗体" + (++Count);
            //当前窗体设置为主窗体,及活动窗体
            SdiApplication.Instance.ApplicationContext.MainForm = form;
            form.Show();
            return form;
        }
    }
}

注:暂时会出现错误提示,不要管它

三、添加引用Microsoft.VisualBasic

image

四、添加类SdiApplication.cs,并在里面写入如下代码:

using Microsoft.VisualBasic.ApplicationServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sdi
{
    public class SdiApplication : WindowsFormsApplicationBase
    {
        private static SdiApplication _instance = null;

        public static SdiApplication Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new SdiApplication();
                }
                return _instance;
            }
        }
        public SdiApplication()
        {
            this.IsSingleInstance = true;//单一进程,及无论开多少窗体,都只有一个进程
            this.ShutdownStyle = ShutdownMode.AfterAllFormsClose;//关闭所有窗体后,关闭进程
        }
        protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
        {
            SdiForm.CreateForm();
        }
        protected override void OnCreateMainForm()
        {
            SdiForm.CreateForm();
        }
    }
}

五、更改Program.cs文件:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Sdi
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            SdiApplication.Instance.Run(args);
        }
    }
}

执行,我们会发现无论我们打开多少个窗体,都只有一个进程

image

我们和Mdi程序做一个比较:

image

posted @ 2014-01-07 22:06  争世不悔  阅读(581)  评论(0编辑  收藏  举报