74 lines
2.5 KiB
C#
74 lines
2.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Superlocal.Agile.WinApp.Records
|
|
{
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="Handle"></param>
|
|
/// <param name="Title"></param>
|
|
/// <param name="ProcessInfo"></param>
|
|
/// <example>
|
|
/// {
|
|
/// "Handle": {
|
|
/// "value": 331358
|
|
/// },
|
|
/// "WindowsTitle": "Superlocal.Agile (Running) - Microsoft Visual Studio (Administrator)",
|
|
/// "ProcessId": 31408,
|
|
/// "ProcessName": "devenv",
|
|
/// "ProcessPath": "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community\\Common7\\IDE\\devenv.exe"
|
|
/// },
|
|
/// {
|
|
/// "Handle": {
|
|
/// "value": 132342
|
|
/// },
|
|
/// "WindowsTitle": "Webcams Besse - Super Besse : 15 webcams actives - Sports-Hiver.com - Mozilla Firefox",
|
|
/// "ProcessId": 13456,
|
|
/// "ProcessName": "firefox",
|
|
/// "ProcessPath": "C:\\Program Files\\Mozilla Firefox\\firefox.exe"
|
|
/// },
|
|
/// {
|
|
/// "Handle": {
|
|
/// "value": 133772
|
|
/// },
|
|
/// "WindowsTitle": "Settings.settings - FolderName - Visual Studio Code",
|
|
/// "ProcessId": 5688,
|
|
/// "ProcessName": "Code",
|
|
/// "ProcessPath": "C:\\Users\\fch\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe"
|
|
/// },
|
|
/// </example>
|
|
internal record WindowInfo(IntPtr Handle, string Title, ProcessInfo? ProcessInfo);
|
|
|
|
internal static class WindowInfoHelper
|
|
{
|
|
public static WindowInfo? GetActiveWindowInfo() => GetWindowInfo(PInvoke.User32.GetForegroundWindow());
|
|
public static WindowInfo? GetWindowInfo(IntPtr handle)
|
|
{
|
|
if (handle == IntPtr.Zero)
|
|
return null;
|
|
|
|
int processId;
|
|
PInvoke.User32.GetWindowThreadProcessId(handle, out processId);
|
|
var process = ProcessInfoHelper.GetProcessInfo(processId);
|
|
var windowTitle = string.Empty;
|
|
try
|
|
{
|
|
windowTitle = PInvoke.User32.GetWindowText(handle);
|
|
}
|
|
catch (Exception)
|
|
{
|
|
// TODO add logger
|
|
}
|
|
|
|
windowTitle = !string.IsNullOrWhiteSpace(windowTitle) ? windowTitle.ToString() : process != null && !string.IsNullOrEmpty(process.ProcessName) ? process.ProcessName : "Untitled";
|
|
|
|
return new WindowInfo(handle, windowTitle, process);
|
|
}
|
|
}
|
|
}
|