在WPF中,要想利用WndProc来处理所有的事件,需要利用到SourceInitialized Event,首先需要创建一个HwndSource对象,然后利用其AddHook方法来将所有的windows消息附加到一个现有的事件中,这个就是WndProc。
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource hs = PresentationSource.FromVisual(this) as HwndSource;
hs.AddHook(new HwndSourceHook(WndProc));
}
这样,我们就成功地添加了一个可以接收所有windows消息的函数,那么有了它,就让我们用它来做一些有意义的事情吧。
在WPF设计过程中,我是利用一个无边框窗体进行了重绘。所以当我设置其最大化时,肯定是要遮蔽任务栏的:
this.WindowState = (this.WindowState == WindowState.Normal ? WindowState.Maximized : WindowState.Normal);
下面就让我们来实现不遮蔽任务栏(参考文章:Maximizing window (with WindowStyle=None) considering Taskbar)。
#region 这一部分用于最大化时不遮蔽任务栏
private static void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
{
MINMAXINFO mmi = (MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(MINMAXINFO));
// Adjust the maximized size and position to fit the work area of the correct monitor
int MONITOR_DEFAULTTONEAREST = 0x00000002;
System.IntPtr monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
if (monitor != System.IntPtr.Zero)
{
MONITORINFO monitorInfo = new MONITORINFO();
GetMonitorInfo(monitor, monitorInfo);
RECT rcWorkArea = monit