获取活动窗口c#

获取活动窗口c#,c#,timer,active-window,C#,Timer,Active Window,我正在尝试获取我单击的每个窗口的名称。我有工作代码,但它使用的是系统计时器,而不是窗体上的计时器。我会发布代码,让它的服务器看看我做错了什么。它也不允许我引用我的文本框,我想我需要把它带到函数中 这里是Dll导入和变量 private static string LastActiveWindow = ""; private static string ActiveWindowName = ""; [DllImport("user32.dll")] private

我正在尝试获取我单击的每个窗口的名称。我有工作代码,但它使用的是系统计时器,而不是窗体上的计时器。我会发布代码,让它的服务器看看我做错了什么。它也不允许我引用我的文本框,我想我需要把它带到函数中

这里是Dll导入和变量

    private static string LastActiveWindow = "";
    private static string ActiveWindowName = "";
    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    static extern int GetWindowText(IntPtr hWind, StringBuilder lpString, int nMaxCount);
然后我的计时器每秒运行10次,这将运行活动窗口功能:

    private void TimerActiveWindow_Tick(object sender, EventArgs e)
    {
        ActiveWindow();
    }

    private static void ActiveWindow(object Obj, EventArgs e)
    {
        IntPtr hwnd = GetForegroundWindow();
        const int Capacity = 512;
        var text = new StringBuilder(Capacity);

        try
        {
            if (GetWindowText(hwnd, text, Capacity) > 0)
            {
                if (ActiveWindowName != text.ToString())
                {
                    if (!LastActiveWindow.Equals(text.ToString()))
                    {
                    //    TxtBody.text += "<br><font color = purple> Current Window - [" + text.ToString() + "]</font><br>";
                        LastActiveWindow = text.ToString();
                        MessageBox.Show(text.ToString());
                    }
                }
            }

        }
        catch { }
    }

我不确定你面临的问题是什么,但你可能对它很感兴趣。当我调用activewindow函数时,括号中没有任何错误,我不确定应该放在那里,我也不能引用该函数中的文本框。你无法访问
TxtBody
,因为该函数是静态的,而
TxtBody
可能是一个实例级字段。你应该把
ActiveWindow
也变成一个实例级的方法。好吧,我改变了它,但是我在系统计时器中使用的事件处理程序呢,我如何使用TimerWindow表单来获得它。timer与timer有点不同。timer,但是我很确定你能用它做基本相同的事情。我不确定你面临的问题是什么,但你可能对它很感兴趣。当我调用activewindow函数时,我不知道括号中有什么错误,我不确定该放在那里,此外,我无法引用该函数中的文本框。您无法访问
TxtBody
,因为该函数是静态的,而
TxtBody
可能是一个实例级字段。你应该把
ActiveWindow
也变成一个实例级的方法。好吧,我改变了它,但是我在系统计时器中使用的事件处理程序呢,我如何使用TimerWindow表单获得它。timer与timer.timer有点不同,但我很确定你可以用它做基本相同的事情。
        System.Timers.Timer TimerActiveWindow = new System.Timers.Timer();
        TimerActiveWindow.Elapsed += new ElapsedEventHandler(Program.ActiveWindow);
        TimerActiveWindow.AutoReset = true;
        TimerActiveWindow.Interval = 100;