首先创建一个新控制台程序。接着,访问Project->AddReference菜单项打开AddReference对话框,并添加对WindowsBase.dll、PresentationCore.dll、System.xaml.dll和PresentationFramework.dll的引用。最后黏贴下面的代码即可。
方法一:
using System;
using System.Windows;
using System.Windows.Controls;
namespace ConsoleHelloWorld
{
class Program : Application
{
[STAThread]
static void Main(string[] args)
{
Program app = new Program();
app.Startup += AppStartUp;
app.Exit += AppExit;
app.Run();
}
static void AppExit(object sender, ExitEventArgs e)
{
MessageBox.Show("App has exited");
}
static void AppStartUp(object sender,StartupEventArgs e)
{
Window mainWindow = new Window();
mainWindow.Title = "My First WPF App!";
mainWindow.Height = 200;
mainWindow.Width = 300;
mainWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
mainWindow.Show();
}
}
}
方法二:创建强类型的windows类
using System;
using System.Windows;
using System.Windows.Controls;
namespace ConsoleHelloWorld
{
class Program : Application
{
[STAThread]
static void Main(string[] args)
{
Program app = new Program();
app.Startup += AppStartUp;
app.Exit += AppExit;
app.Run();
}
static void AppExit(object sender, ExitEventArgs e)
{
MessageBox.Show("App has exited");
}
static void AppStartUp(object sender,StartupEventArgs e)
{
MainWindow mainWindow = new MainWindow("My better WPF App!",200,300);
mainWindow.Show();
}
}
class MainWindow : Window
{
public MainWindow(string windowTitle, int height, int width)
{
this.Title = windowTitle;
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
this.Height = height;
this.Width = width;
}
}
}