C# 如何检测窗口窗体何时被最小化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1052913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to detect when a windows form is being minimized?
提问by Jorge Branco
I know that I can get the current state by WindowState, but I want to know if there's any event that will fire up when the user tries to minimize the form.
我知道我可以通过 WindowState 获取当前状态,但是我想知道当用户尝试最小化表单时是否会触发任何事件。
回答by ChrisF
To get in beforethe form has been minimised you'll have to hook into the WndProc procedure:
要在表单最小化之前进入,您必须挂钩 WndProc 过程:
private const int WM_SYSCOMMAND = 0x0112;
private const int SC_MINIMIZE = 0xF020;
[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)
{
// Do your action
}
// If you don't want to do the default action then break
break;
}
base.WndProc(ref m);
}
To react afterthe form has been minimised hook into the Resize
event as the other answers point out (included here for completeness):
如其他答案所指出的那样,在表单最小化后做出反应挂钩到Resize
事件中(为了完整起见,包括在此处):
private void Form1_Resize (object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
// Do your action
}
}
回答by Dan F
I don't know of a specificevent, but the Resize
event fires when the form is minimized, you can check for FormWindowState.Minimized
in that event
我不知道特定的事件,但是Resize
当表单最小化时会触发该事件,您可以FormWindowState.Minimized
在该事件中检查
回答by Steve Dignan
You can use the Resize event and check the Forms.WindowState Property in the event.
您可以使用 Resize 事件并检查事件中的 Forms.WindowState 属性。
private void Form1_Resize ( object sender , EventArgs e )
{
if ( WindowState == FormWindowState.Minimized )
{
// Do some stuff
}
}
回答by Chaos
For people who search for WPF windows minimizing event :
对于搜索 WPF windows 最小化事件的人:
It's a bit different. For the callback use WindowState :
它有点不同。对于回调使用 WindowState :
private void Form1_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
// Do some stuff
}
}
The event to use is StateChanged (instead Resize):
要使用的事件是 StateChanged(而不是 Resize):
public Main()
{
InitializeComponent();
this.StateChanged += Form1_Resize;
}