在WPF中,可以通过重写窗体类的方法来自定义窗体消息。以下是一个示例:
创建一个自定义窗体类,继承自Window类:public class CustomWindow : Window{ // 重写WndProc方法处理窗体消息 protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource; if (hwndSource != null) { hwndSource.AddHook(new HwndSourceHook(WndProc)); } } private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { // 自定义处理窗体消息的逻辑 switch (msg) { case WM_CLOSE: // 自定义处理窗体关闭的逻辑 MessageBox.Show("窗体关闭消息被拦截!"); handled = true; break; } return IntPtr.Zero; } // 定义窗体消息常量 private const int WM_CLOSE = 0x0010;}在XAML中使用自定义窗体类:<local:CustomWindow x:Class="MyApp.MainWindow" xmlns:local="clr-namespace:MyApp" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="450" Width="800"> <!-- 窗体内容 --></local:CustomWindow>通过重写WndProc方法和处理窗体消息常量,可以自定义窗体的消息处理逻辑,实现更灵活的窗体行为。


