如何查看哪个节目是焦点?

时间:2016-01-19 01:20:38

标签: c# window focus

我试图让计时器检查特定程序是否每250毫秒都有一个焦点,但我无法弄清楚如何......

当前代码:

<div style="padding: 50px; width: 90px; line-height: 2em;" contenteditable="true">
  line height line height line height
  <span style="line-height: 1em; color: Red;">line height</span>
  <span style="line-height: 10px; color: Orange;">line height</span>
  <span style="line-height: normal; color: Green;">line height</span>
  <span style="line-height: .5em; font-size: .5em; height: 5px; color: Blue;">line height</span>
</div>

错误在第11行:

~/Downloads/Android/sdk/tools/

我做错了什么?

2 个答案:

答案 0 :(得分:3)

这对我有用,稍微不同,因为它返回活动窗口名称:

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;

答案 1 :(得分:0)

您要将IntPtr返回的GetForegroundWindow()Process[]进行比较。 顾名思义,Process.GetProcessesByName可以返回多个进程,因此您需要将其视为数组。

Process.GetProcessesByName("Hearthstone")保存到变量中,并迭代每个条目以查看它是否是焦点。 另外,假设句柄是进程ID;可能并非如此。以下代码未经测试。

...
var processes = Process.GetProcessesByName("Hearthstone");
foreach(Process p in processes) {
    if(activedHandle == p.Handle) {
        //A instance of the process Hearthstone is currently focused.
        ...
    } else {
        ...
    }
}