-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCurrentApplicationHelper.cs
More file actions
54 lines (50 loc) · 1.6 KB
/
CurrentApplicationHelper.cs
File metadata and controls
54 lines (50 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace NaturalCommands
{
public static class CurrentApplicationHelper
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
public static string? GetCurrentProcessName()
{
IntPtr hwnd = GetForegroundWindow();
if (hwnd == IntPtr.Zero)
return null;
int pid;
GetWindowThreadProcessId(hwnd, out pid);
try
{
Process proc = Process.GetProcessById(pid);
return proc.ProcessName.ToLower();
}
catch
{
return null;
}
}
/// <summary>
/// Returns the title of the current foreground window, or null when none.
/// </summary>
public static string? GetCurrentWindowTitle()
{
IntPtr hwnd = GetForegroundWindow();
if (hwnd == IntPtr.Zero) return null;
var sb = new System.Text.StringBuilder(1024);
try
{
// Use centralized Win32 helper when available
NaturalCommands.Helpers.Win32ApiHelper.GetWindowText(hwnd, sb, sb.Capacity);
var title = sb.ToString();
return string.IsNullOrWhiteSpace(title) ? null : title;
}
catch
{
return null;
}
}
}
}