Skip to content

Instantly share code, notes, and snippets.

@ochilab
Last active August 25, 2019 21:52
Show Gist options
  • Save ochilab/7594f70daa232404ba2e50dbaa6b0064 to your computer and use it in GitHub Desktop.
Save ochilab/7594f70daa232404ba2e50dbaa6b0064 to your computer and use it in GitHub Desktop.
C#:Activeになっているウィンドウのアプリケーション名を取得する
[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("何もしない");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment