首先,创建一个控制台应用程序SimpleWinFormsApp。接下来,打开Project->Add Reference菜单选项,在弹出对话框的.NET选项卡中添加System.Windows.Forms.dll和System.Drawing.dll程序集的引用。然后更新Program.cs文件的代码:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;//必须的Windows窗体命名空间
namespace HelloWorld
{
//这是我们的应用程序对象
class Program
{
static void Main(string[] args)
{
Application.Run(new MainWindow("My Window",200,300));
}
}
//这是我们的主窗口
class MainWindow:Form
{
public MainWindow() { }
public MainWindow(string title, int height, int width)
{
Text = title;
Width = width;
Height = height;
CenterToParent();
CenterToScreen();
}
}
}
运行该程序时,你会发现置顶窗口的背后有一个命令窗口。这是因为我们创建的控制台应用程序,传递给C#编译器的/target标识默认为/target:exe。双击Solution Explorer中的Properties图标,在Application选项卡中将Output Type修改为Windows Application,这样就可以将标识改为/target:winexe(不会再出现命令窗口)。