この質問はこれと非常によく似ています ( Detect active window changed using C# without polling )。その受け入れられた回答のコードは、Windows フォーム アプリケーションでは正常に機能しますが、コンソール アプリケーションでは機能しません。
コンソール アプリケーションで無限の繰り返し (または任意の種類のポーリング) を実行せずに、アクティブ ウィンドウが変更されたことを検出するにはどうすればよいですか?
前もって感謝します。
この質問はこれと非常によく似ています ( 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());
}
}
}