0

I want my program to trigger an action only when certain other programs are currently being used. I get the current foreground HWND with GetForegroundWindow(). But HWNDs change over time, so that's not a way to identify those programs. The same goes for Process IDs and handles. What is a way to identify the foreground program over reboots?

I first thought GetModuleFileNameExA should work, but my code crashes because it is not found:

Handle handle = GetProcessHandleFromHwnd(hWID);

String Name = null;

GetModuleFileNameExA(
  handle,
  null,
  Name,
  2147483647
);

[DllImport("Kernel32.dll", CharSet = CharSet.Ansi)]
private static extern IntPtr GetModuleFileNameExA(
  Handle hProcess,
  Object hModule,
  String lpFilename,
  Int32 nSize
);
GiffordPG
  • 33
  • 4
  • It crashes because your signature is wrong. Look [on pinvoke.net](http://pinvoke.net/default.aspx/psapi/GetModuleFileNameEx.html). – dymanoid Nov 23 '18 at 15:02
  • @dymanoid I fixed the signature and used Null as the hModule. The result were random signs instead of a path. Is my assumtion correct that Null can be used if I just want the path? It's what the docs say – GiffordPG Nov 23 '18 at 16:06
  • `GetModuleFileNameExA` method introduced into [api-ms-win-core-url-l1-1-0.dll](https://learn.microsoft.com/en-us/uwp/win32-and-com/win32-apis#apis-from-api-ms-win-core-psapi-ansi-l1-1-0dll) in UWP. – Bite Nov 26 '18 at 06:30

1 Answers1

0

You need to use GetWindowThreadProcessId. This is explained better in the answers to this question: Find process id by window's handle.

You should then be able to use System.Diagnostics.Process.GetProcesses() to match the pid to a process and its modules. You may find that you cannot access the details of 64 bit processes from a 32 bit process, or that security blocks access to some information.

open-collar
  • 1,404
  • 1
  • 16
  • 22