如何取消WPF表单最小化事件 [英] How to cancel the WPF form minimize event

查看:44
本文介绍了如何取消WPF表单最小化事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想取消自然的最小化行为,而是改为更改WPF表单大小.

I want to cancel the natural minimizing behavior and change a WPF form size instead.

我有一个使用Window_StateChanged的解决方案,但是看起来并不好-首先将窗口最小化,然后跳回并进行尺寸更改.有没有办法做到这一点?我用Google搜索了Window_StateChanging,但无法弄清楚,是我不喜欢使用的某种外部库.

I have a solution with the Window_StateChanged but it doesn't look so nice - the window first minimized then jumps back and does the size alteration. Is there a way to accomplish this? I Googled for Window_StateChanging but couldn't figure it out, some sort of external lib that I prefer not to use.

这就是我所拥有的:

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

推荐答案

在表单触发 Window_StateChanged 之前,您需要截取minimal命令,以避免您看到的最小化/还原舞蹈..我相信最简单的方法是让您的表单侦听Windows消息,并在收到最小化命令时取消它并调整表单大小.

You'll need to intercept the minimize command before your form fires Window_StateChanged, to avoid the minimize/restore dance you're seeing. I believe the easiest way to do this is to have your form listen for Windows messages and when the minimize command is received, cancel it and resize your form.

在表单构造函数中注册 SourceInitialized 事件:

Register the SourceInitialized event, in your form constructor:

this.SourceInitialized += new EventHandler(OnSourceInitialized); 

将这两个处理程序添加到您的表单中:

Add these two handlers to your form:

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

我怀疑这是您希望避免的方法,但归根结底是我展示的实现起来不太困难的代码.

I suspect this is the approach you were hoping to avoid but boiled down to the code I show it's not too difficult to implement.

基于此SO问题的代码.

这篇关于如何取消WPF表单最小化事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆