[英]How can I check which program is in focus?
I'm trying to have a timer check if a specific program is in focus every 250ms, but I just can't figure out how... 我正在尝试让计时器每250毫秒检查一次特定程序是否在焦点上,但我只是不知道如何...
Current code: 当前代码:
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Hearthstone_Test
{
public partial class Main : Form
{
private void timer1_Tick(object sender, EventArgs e)
{
var activatedHandle = GetForegroundWindow();
if (GetForegroundWindow() == Process.GetProcessesByName("Hearthstone"));
{
Console.WriteLine("Not Focused"); // No window is currently activated
}
else
{
Console.WriteLine("Focused");
}
var procId = Process.GetCurrentProcess().Id;
int activeProcId;
GetWindowThreadProcessId(activatedHandle, out activeProcId);
}
[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);
}
}
Error is at line 11: 错误在第11行:
Operator '==' cannot be applied to operands of type 'Process[]' and 'IntPtr'
What I'm doing wrong? 我做错了什么?
This worked for me, slightly different as it returns the active window name: 这对我有用,因为它返回活动窗口名称,所以略有不同:
public string getActiveWindowName()
{
try
{
var activatedHandle = GetForegroundWindow();
Process[] processes = Process.GetProcesses();
foreach (Process clsProcess in processes)
{
if(activatedHandle == clsProcess.MainWindowHandle)
{
string processName = clsProcess.ProcessName;
return processName;
}
}
}
catch { }
return null;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern IntPtr GetForegroundWindow();
the following will give you the actual window header text: 以下将为您提供实际的窗口标题文本:
string processName = clsProcess.MainWindowTitle;
You're comparing an IntPtr
returned by GetForegroundWindow()
to an Process[]
. 您正在将
GetForegroundWindow()
返回的IntPtr
与Process[]
。 As the name suggests, Process.GetProcessesByName
can return multiple processes and as such you'll need to treat it as an array. 顾名思义,
Process.GetProcessesByName
可以返回多个进程,因此您需要将其视为数组。
Save Process.GetProcessesByName("Hearthstone")
into a variable, and iterate over each entry to see if it is the one that's focused. 将
Process.GetProcessesByName("Hearthstone")
保存到一个变量中,并遍历每个条目以查看它是否是重点突出的条目。 Also, you assume that the handle is the process ID; 另外,您假定该句柄是进程ID。 which probably isn't the case.
情况可能并非如此。 The following code is untested.
以下代码未经测试。
...
var processes = Process.GetProcessesByName("Hearthstone");
foreach(Process p in processes) {
if(activedHandle == p.Handle) {
//A instance of the process Hearthstone is currently focused.
...
} else {
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.