如何检查表格是否不可见(最小化)

时间:2018-09-28 14:33:49

标签: c# winforms minimize

我正在使用此代码检查表单是否最小化:

[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
    switch (m.Msg)
    {
        case WM_SYSCOMMAND:
            int command = m.WParam.ToInt32() & 0xfff0;
            if (command == SC_MINIMIZE)
                MessageBox.Show("Minimized");
                Variaveis.telaMinimizada = true;
            else
                Variaveis.telaMinimizada = false;
                MessageBox.Show("Maximized");
            break;
    }
    base.WndProc(ref m);
}

此代码的作用就像一个超级魅力。当我单击最小化按钮时,出现消息“最小化”,而当我重新打开该应用程序时,出现消息“最大化”

但是有一个问题。 并非总是人们通过单击“最小化”按钮来最小化表单。我的意思是,如果我在屏幕上单击OUT ,表单也将最小化,当这种情况发生时,我没有检测到代码没有最小化表单。

单击 OUT 表单后最小化表单时,如何检查表单是否最小化(或在屏幕上不可见)?

想法?谢谢!

编辑:我已经尝试做这篇文章推荐的事情,但是不起作用:

How to detect when a windows form is being minimized?

1 个答案:

答案 0 :(得分:4)

这可能对您有用

//we create a variable to store our window's last state
FormWindowState lastState;
public Form2()
{
    InitializeComponent();

    //then we create an event for form size changed
    //i did use lambda for creating event but you can use ordinary way.
    this.SizeChanged += (s, e) =>
    {

        //when window size changed we check if current state
        //is not the same with the previous
        if (WindowState != lastState)
        {

            //i did use switch to show all 
            //but you can use if to get only minimized status
            switch (WindowState)
            {
                case FormWindowState.Normal:
                    MessageBox.Show("normal");
                    break;
                case FormWindowState.Minimized:
                    MessageBox.Show("min");
                    break;
                case FormWindowState.Maximized:
                    MessageBox.Show("max");
                    break;
                default:
                    break;
            }
            //and at the and of the event we store last window state in our
            //variable so we get single message when state changed.
            lastState = WindowState;
        }
    };
}

编辑: 并检查表单是否不再位于顶部,您可以像这样覆盖OnLostFocus

protected override void OnLostFocus(EventArgs e)
{
MessageBox.Show("form not on top anymore");
base.OnLostFocus(e);
this.Focus();
}