VS2008创建一个Windows窗体程序并深入分析

用VS2008创建一个有关Windows窗体应用程序。仔细观察可以发现,对于该程序,VS2008中有三个常用文件。这就是Form1.cs、Form1.Designer.cs、Program.cs三个文件。

Main方法在program.cs中,它是程序的入口点。

Form1.cs是Form1类的代码文件(默认)并且只包含这个类的一部分。另一部分默认在Form1.Designer.cs文件中。

下面我们做下面的简单实例:
我们在Form1窗体中,放两个按钮,分别命名为button1和button2。

在Form1.cs中,我们写入
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("你单击了左边的button1按钮。");      //弹出消息框
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MessageBox.Show("你单击了右边的button2按钮。");       //弹出消息框
        }
    }
}

该程序运行结果为:



从上面的代码可以发现,代码被写在了Form1类里边;而前面的控制台应用程序都是写在Program.cs的Program类里,并且主要是写在了Main函数里。其实在Windows窗体应用程序中,也有Main函数。它和控制台应用程序中的Main一样,也在Program.cs文件的Program类中,其代码内容如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

posted on 2012-07-02 10:19  流星落  阅读(1422)  评论(0编辑  收藏  举报

导航