2015-08-14 57 views
0

这个问题是非常相似,这一个(Detect active window changed using C# without polling)改变,对接受的答案代码正常工作与Windows窗体应用程序,但没办法用一个控制台应用程序。检测活动窗口中使用C#有一个控制台应用程序

¿我如何可以检测到活动窗口已没有与控制台应用程序做无限次迭代(或任何类型的轮询)改变了吗?

在此先感谢。

+0

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

回答

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()); 
     } 
    } 
} 
相关问题