gpt4 book ai didi

c# - 如何检查哪个程序处于焦点状态?

转载 作者:行者123 更新时间:2023-12-05 01:46:38 25 4
gpt4 key购买 nike

我正在尝试让计时器每 250 毫秒检查一次特定程序是否处于焦点状态,但我就是不知道如何...

当前代码:

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

错误在第 11 行:

Operator '==' cannot be applied to operands of type 'Process[]' and 'IntPtr'

我做错了什么?

最佳答案

这对我有用,在返回事件窗口名称时略有不同:

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

以下将为您提供实际的窗口标题文本:

string processName = clsProcess.MainWindowTitle;

关于c# - 如何检查哪个程序处于焦点状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34866994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com