Skip to content

Commit

Permalink
Speed up AppWindow.ProcessTitle
Browse files Browse the repository at this point in the history
  • Loading branch information
daanzu authored and elig0n committed May 17, 2020
1 parent 7e1bb79 commit 8e2173f
Showing 1 changed file with 40 additions and 1 deletion.
41 changes: 40 additions & 1 deletion Core/AppWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
using System.Runtime.Caching;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using ManagedWinapi.Windows;

namespace Switcheroo.Core
Expand Down Expand Up @@ -58,14 +59,52 @@ public string ProcessTitle
}
else
{
processTitle = Process.ProcessName;
processTitle = getWindowProcessName(HWnd);

}
MemoryCache.Default.Add(key, processTitle, DateTimeOffset.Now.AddHours(1));
}
return processTitle;
}
}

[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

private enum ProcessRights
{
PROCESS_TERMINATE = 0x1,
PROCESS_CREATE_THREAD = 0x2,
PROCESS_SET_SESSIONID = 0x4,
PROCESS_VM_OPERATION = 0x8,
PROCESS_VM_READ = 0x10,
PROCESS_VM_WRITE = 0x20,
PROCESS_DUP_HANDLE = 0x40,
PROCESS_CREATE_PROCESS = 0x80,
PROCESS_SET_QUOTA = 0x100,
PROCESS_SET_INFORMATION = 0x200,
PROCESS_QUERY_INFORMATION = 0x400,
}

[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(ProcessRights dwDesiredAccess, bool bInheritHandle, int dwProcessId);

[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool QueryFullProcessImageName(IntPtr hProcess, int dwFlags, StringBuilder lpExeName, out int lpdwSize);

private static Regex processNameRegex = new Regex("([^\\\\]+?)(?=(\\.exe)?$)");

private static string getWindowProcessName(IntPtr hwnd)
{
int pid;
GetWindowThreadProcessId(hwnd, out pid);
IntPtr handle = OpenProcess(ProcessRights.PROCESS_QUERY_INFORMATION | ProcessRights.PROCESS_VM_READ, false, pid);
int exeBufferSize = 512;
StringBuilder exeBuffer = new StringBuilder(exeBufferSize);
QueryFullProcessImageName(handle, 0, exeBuffer, out exeBufferSize);
return processNameRegex.Match(exeBuffer.ToString()).Value;
}

public Icon LargeWindowIcon
{
get { return new WindowIconFinder().Find(this, WindowIconSize.Large); }
Expand Down

0 comments on commit 8e2173f

Please sign in to comment.