【问题标题】:Detect active window changed using C# with a console application使用控制台应用程序检测使用 C# 更改的活动窗口
【发布时间】:2015-08-14 16:47:29
【问题描述】:

这个问题与这个问题 (Detect active window changed using C# without polling) 非常相似,并且接受的答案中的代码适用于 Windows 窗体应用程序,但不适用于控制台应用程序。

¿如何在不使用控制台应用程序进行无限迭代(或任何类型的轮询)的情况下检测活动窗口已更改?

提前致谢。

【问题讨论】:

  • 该代码根本不需要 Form,只需要 Application.Run()。在单独线程上的 SetWinEventHook 之后调用它。

标签: c# console-application active-window


【解决方案1】:

只需进行一些更改,即可将其更改为作为控制台应用程序运行。这是一个工作代码。

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            dele = new WinEventDelegate(WinEventProc);
            IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
            Application.Run(); //<----
        }

        static WinEventDelegate dele = null; //STATIC

        delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);

        [DllImport("user32.dll")]
        static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);

        private const uint WINEVENT_OUTOFCONTEXT = 0;
        private const uint EVENT_SYSTEM_FOREGROUND = 3;

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

        private static string GetActiveWindowTitle() //STATIC
        {
            const int nChars = 256;
            IntPtr handle = IntPtr.Zero;
            StringBuilder Buff = new StringBuilder(nChars);
            handle = GetForegroundWindow();

            if (GetWindowText(handle, Buff, nChars) > 0)
            {
                return Buff.ToString();
            }
            return null;
        }

        public static void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) //STATIC
        {
            Console.WriteLine(GetActiveWindowTitle());
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-01-18
    • 2011-05-21
    • 1970-01-01
    • 2011-04-20
    • 2014-02-17
    • 2011-04-04
    • 2022-01-14
    • 1970-01-01
    • 2019-03-18
    相关资源
    最近更新 更多