Last active
March 27, 2018 01:28
-
-
Save skysan87/1bdfeab203873664710efd12e3ecce40 to your computer and use it in GitHub Desktop.
[C#]特定のプロセスのコントロールのフォーカス変更を監視する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using System.Threading; | |
using System.Windows.Automation; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static AutomationFocusChangedEventHandler focusHandler = null; | |
private static int processId; | |
static void Main(string[] args) | |
{ | |
// 監視するプロセス | |
string processPath = @"WindowsFormsApplication1"; | |
Process process = Process.Start(processPath); | |
Thread.Sleep(1000); | |
processId = process.Id; | |
try | |
{ | |
SubscribeToFocusChange(); | |
Console.WriteLine("App Start"); | |
Console.ReadKey(); | |
} | |
finally | |
{ | |
UnsubscribeFocusChange(); | |
Console.WriteLine("App Close"); | |
} | |
} | |
/// <summary> | |
/// Create an event handler and register it. | |
/// </summary> | |
public static void SubscribeToFocusChange() | |
{ | |
focusHandler = new AutomationFocusChangedEventHandler(OnFocusChange); | |
Automation.AddAutomationFocusChangedEventHandler(focusHandler); | |
} | |
/// <summary> | |
/// Handle the event. | |
/// </summary> | |
private static void OnFocusChange(object src, AutomationFocusChangedEventArgs e) | |
{ | |
if (src is AutomationElement) | |
{ | |
var target = src as AutomationElement; | |
if (target.Current.ProcessId == processId) | |
{ | |
if (string.IsNullOrEmpty(AutomationElement.FocusedElement.Current.Name)) | |
Console.WriteLine("OnFocusChange?:{0}", AutomationElement.FocusedElement.Current.ClassName); | |
else | |
Console.WriteLine("OnFocusChange:{0}({1})", AutomationElement.FocusedElement.Current.Name, AutomationElement.FocusedElement.Current.ClassName); | |
} | |
} | |
} | |
/// <summary> | |
/// Cancel subscription to the event. | |
/// </summary> | |
public static void UnsubscribeFocusChange() | |
{ | |
if (focusHandler != null) | |
{ | |
Automation.RemoveAutomationFocusChangedEventHandler(focusHandler); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment