2012-10-23 19 views
2

我想取消自然最小化行为并改为改变WPF表单大小。如何取消WPF表单最小化事件

我有一个与Window_StateChanged的解决方案,但它看起来并不那么好 - 窗口第一次最小化然后跳回并做大小改变。有没有办法做到这一点?我谷歌搜索Window_StateChanging,但无法弄清楚,我不喜欢使用某种外部库。

这就是我:

private void Window_StateChanged(object sender, EventArgs e) 
{ 
    switch (this.WindowState) 
    { 
     case WindowState.Minimized: 
      { 
       WindowState = System.Windows.WindowState.Normal; 
       this.Width = 500; 
       this.Height = 800; 
       break; 
      } 
    } 
} 

感谢,

EP

回答

6

你需要表单火灾Window_StateChanged,前拦截化命令,以避免最小化/恢复舞你看到了。我相信最简单的方法是让窗体侦听Windows消息,并在收到最小化命令时取消它并调整窗体大小。

注册SourceInitialized事件,在窗体的构造函数:

this.SourceInitialized += new EventHandler(OnSourceInitialized); 

这两个处理程序添加到您的窗体:

private void OnSourceInitialized(object sender, EventArgs e) { 
    HwndSource source = (HwndSource)PresentationSource.FromVisual(this); 
    source.AddHook(new HwndSourceHook(HandleMessages)); 
} 

private IntPtr HandleMessages(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { 
    // 0x0112 == WM_SYSCOMMAND, 'Window' command message. 
    // 0xF020 == SC_MINIMIZE, command to minimize the window. 
    if (msg == 0x0112 && ((int)wParam & 0xFFF0) == 0xF020) { 
     // Cancel the minimize. 
     handled = true; 

     // Resize the form. 
     this.Width = 500; 
     this.Height = 500; 
    } 

    return IntPtr.Zero; 
} 

我怀疑这是你希望避免的做法,但归结到代码我显示它并不太难实现。

基于this SO question的代码。

+0

真棒!非常感谢,这是完美的! – Salty

0

试试这个简单的解决方案:

public partial class MainWindow : Window 
{ 
    private int SC_MINIMIZE = 0xf020; 
    private int SYSCOMMAND = 0x0112; 

    public MainWindow() 
    { 
     InitializeComponent(); 
     SourceInitialized += (sender, e) => 
           { 
            HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle); 
            source.AddHook(WndProc); 
           }; 
    } 

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) 
    { 
     // process minimize button 
     if (msg == SYSCOMMAND && SC_MINIMIZE == wParam.ToInt32()) 
     { 
      //Minimize clicked 
      handled = true; 
     } 
     return IntPtr.Zero; 
    } 
}