Loading [MathJax]/extensions/tex2jax.js

2016-06-17

C#:Activeになっているウィンドウのアプリケーション名を取得する

ちょっと自分の行動ログを取りたくなったので、利用しているアプリケーション名を取得するコードを書いてみました。これをタイマーで逐次チェックしていけばいいでしょう。いちおう、Win32APIを利用してます。

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", EntryPoint = "GetWindowText", CharSet = CharSet.Auto)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
int processid;
try{
GetWindowThreadProcessId(GetForegroundWindow(), out processid);
if (0 != processid){
Process p = Process.GetProcessById(processid);
System.Diagnostics.Debug.Write(processid + ":");
System.Diagnostics.Debug.WriteLine(p.MainModule.FileVersionInfo.ProductName);//アプリケーションの名前が出てきます
}
else{
System.Diagnostics.Debug.Write(processid + ":Sleep");
}
}
catch (System.ComponentModel.Win32Exception e){
System.Diagnostics.Debug.Writeln("何もしない");
}


0 件のコメント:

コメントを投稿