创建不使用XAML的WPF程序

本文介绍两种创建WPF应用程序的方法,包括直接创建窗口和使用强类型窗口类的方式。通过具体的代码示例,读者可以了解如何设置窗口属性并显示窗口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先创建一个新控制台程序。接着,访问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;
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值