c# - 使用 C# 和控制台应用程序检测事件窗口的更改

标签 c# console-application active-window

这个问题与这个问题 ( Detect active window changed using C# without polling ) 非常相似,并且该接受答案上的代码在 Windows 窗体应用程序中工作得很好,但在控制台应用程序中却不行。

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

提前致谢。

最佳答案

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

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

关于c# - 使用 C# 和控制台应用程序检测事件窗口的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32015004/

相关文章:

java - 在Java中获取当前 Activity 窗口的标题

c++ - 如何确定 OpenGL 窗口是否为事件窗口?

c# - .NET exe/dll 混淆

c++ - 跨平台、基于交互式文本的界面,具有命令完成功能

linux - 无法从 Linux 控制台运行 C++ 应用程序 - "not found"错误

c# - 超时关闭在控制台中无法关闭启动画面

c# - 确定程序是否为 .NET 中的事件窗口

c# - Unity TCP 服务器/客户端

c# - linq Expression<TDelegate> 赋值如何在语言语法级别上工作

C# 事件订阅