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



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

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

此代码的工作方式类似于一个超级按钮。当我单击最小化按钮时,出现消息"最小化",当我重新打开应用程序时,出现消息"最大化">

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

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

想法?谢谢!

编辑:我已经尝试过做这篇文章中推荐的事情,但没有工作:

如何检测窗口窗体何时最小化?

这可能对你有用

//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();
}

最新更新