【问题标题】:How to cancel the WPF form minimize event如何取消 WPF 表单最小化事件
【发布时间】:2012-10-23 02:58:01
【问题描述】:

我想取消自然最小化行为并改为更改 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

【问题讨论】:

    标签: c# wpf winforms


    【解决方案1】:

    您需要在表单触发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

    【讨论】:

    • 以上代码取消了窗口系统菜单中的最小化命令,但Win-Down热键仍然有效。
    【解决方案2】:

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

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 2016-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多