wpf怎么自定义窗体消息

avatar
作者
筋斗云
阅读量:0

在WPF中,可以通过重写窗体类的方法来自定义窗体消息。以下是一个示例:

  1. 创建一个自定义窗体类,继承自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; } 
  1. 在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方法和处理窗体消息常量,可以自定义窗体的消息处理逻辑,实现更灵活的窗体行为。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!