基本上,我如何判断我的程序是否优于所有其他程序?
答案 0 :(得分:10)
一种相当简单的方法是P / Invoke 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.
}
答案 1 :(得分:1)
您可以使用:
if (GetForegroundWindow() == Process.GetCurrentProcess().MainWindowHandle)
{
//do stuff
}
WINAPI导入(在班级):
[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool GetForegroundWindow();
指定一个属性来保存该值,并通过IDE或者在InitializeComponent()之后将检查添加到表单的GotFocus事件中;
e.g:
//.....
InitalizeComponent();
this.GotFocus += (myFocusCheck);
//...
private bool onTop = false;
private void myFocusCheck(object s, EventArgs e)
{
if(GetFore......){ onTop = true; }
}
答案 2 :(得分:0)
如果您的窗口继承了表单,则可以检查Form.Topmost属性
答案 3 :(得分:0)
对这个问题的答案给出了一个很好的解决方案: 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停靠框架),则Euric当前接受的解决方案不起作用。