基本上,我怎么知道我的计划是上述所有其他的分层?
Answer 1:
一个相当简单的方法是P /调用GetForegroundWindow()和比较HWND返回给应用程序的form.Handle财产。
using System;
using System.Runtime.InteropServices;
namespace MyNamespace
{
class GFW
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
public bool IsActive(IntPtr handle)
{
IntPtr activeHandle = GetForegroundWindow();
return (activeHandle == handle);
}
}
}
然后,从表格:
if (MyNamespace.GFW.IsActive(this.Handle))
{
// Do whatever.
}
Answer 2:
您可以使用:
if (GetForegroundWindow() == Process.GetCurrentProcess().MainWindowHandle)
{
//do stuff
}
WINAPI进口(在类级别):
[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool GetForegroundWindow();
分配属性来保存的价值,并检查通过IDE添加到窗体的GotFocus事件,或在InitializeComponent()之后;
例如:
//.....
InitalizeComponent();
this.GotFocus += (myFocusCheck);
//...
private bool onTop = false;
private void myFocusCheck(object s, EventArgs e)
{
if(GetFore......){ onTop = true; }
}
Answer 3:
如果你的窗口继承的形式,你可以检查Form.Topmost财产
Answer 4:
一个好的解决办法是通过这个答案给一个相同的问题: https://stackoverflow.com/a/7162873/386091
/// <summary>Returns true if the current application has focus, false otherwise</summary>
public static bool ApplicationIsActivated()
{
var activatedHandle = GetForegroundWindow();
if (activatedHandle == IntPtr.Zero) {
return false; // No window is currently activated
}
var procId = Process.GetCurrentProcess().Id;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
return activeProcId == procId;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
通过芥酸目前公认的解决方案,如果你的程序显示一个对话框,或具有可拆卸窗口(例如,如果你使用Windows对接框架)不起作用。
文章来源: How do I see if my form is currently on top of the other ones?