C# 获取系统消息监听

 public HomeWindowNew()
        {
            InitializeComponent();

            SourceInitialized += HandleInitialized;
           
        }

        private void HandleInitialized(object sender, EventArgs e)
        {
            IntPtr wptr = new WindowInteropHelper(this).Handle;
            HwndSource hs = HwndSource.FromHwnd(wptr);
            hs.AddHook(new HwndSourceHook(WpfHandleWinowMsg));
        }

        private IntPtr WpfHandleWinowMsg(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            Console.WriteLine("00000" + msg);
            switch (msg)
            {
                case 1:
                    break;
                case 2:
                    break;
                default:

                    break;
            }
            return IntPtr.Zero;
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 C#监听当前操作系统活动窗口发生改变,你可以使用 System.Windows.Forms 命名空间中的 SystemEvents 类的ForegroundWindowChanged 事件。以下是一个示例代码: ```csharp using System; using System.Windows.Forms; class Program { static void Main() { // 注册 ForegroundWindowChanged 事件 SystemEvents.ForegroundWindowChanged += OnForegroundWindowChanged; // 等待退出程序 Console.WriteLine("按任意键退出程序..."); Console.ReadKey(); } static void OnForegroundWindowChanged(object sender, EventArgs e) { // 获取当前活动窗口的标题 string foregroundWindowTitle = GetForegroundWindowTitle(); // 输出当前活动窗口的标题 Console.WriteLine("当前活动窗口改变: " + foregroundWindowTitle); } static string GetForegroundWindowTitle() { IntPtr foregroundWindowHandle = NativeMethods.GetForegroundWindow(); const int MaxLength = 256; var buffer = new char[MaxLength]; NativeMethods.GetWindowText(foregroundWindowHandle, buffer, MaxLength); return new string(buffer); } } // 使用 Windows API 获取窗口标题 class NativeMethods { [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern int GetWindowText(IntPtr hWnd, char[] lpString, int nMaxCount); } ``` 上述代码中,我们通过注册 `SystemEvents.ForegroundWindowChanged` 事件来监听当前活动窗口发生改变的情况。每当活动窗口发生改变时,`OnForegroundWindowChanged` 方法会被调用,并获取当前活动窗口的标题,并输出到控制台。 请注意,此代码使用了 Windows API 来获取窗口标题。`GetForegroundWindow` 函数用于获取当前活动窗口的句柄,然后使用 `GetWindowText` 函数获取窗口的标题。你可以根据需要修改和扩展代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值