How to get application name by using pid in dart-win32

99 views Asked by At

I'm trying to get currently active application's name on windows flutter app using pid. Is there any way to get the app's name by process id? Here is my code:

import 'dart:ffi' as ffi;
import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart' as win;

void main(){
    ffi.Pointer<ffi.Uint32> pidPointer = calloc();
    int hwnd = win.GetForegroundWindow();
    win.GetWindowThreadProcessId(hwnd, pidPointer);
    int pid = pidPointer.value;
    print('Process ID of the active window: $pid');
    win.free(pidPointer);
}
1

There are 1 answers

0
Sharif Ahamed On BEST ANSWER

Here is the solution:

import 'dart:ffi' as ffi;
import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';

void getActiveAppName() {
    ffi.Pointer<ffi.Uint32> pidPointer = calloc();
    int hwnd = GetForegroundWindow();
    GetWindowThreadProcessId(hwnd, pidPointer);
    int pid = pidPointer.value;
    free(pidPointer);
    printModules(pid);
}
int printModules(int processID) {
    // Print the process identifier.
    //print('\nProcess ID: $processID');

    // Get a handle to the process.
    final hProcess = OpenProcess(
        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);

    if (hProcess == 0) {
        return 1;
    }

    // Get a list of all the modules in this process.
    final hMods = calloc<HMODULE>(1024);
    final cbNeeded = calloc<DWORD>();

    if (EnumProcessModules(hProcess, hMods, ffi.sizeOf<HMODULE>() * 1024, cbNeeded) ==
        1) {
            final szModName = wsalloc(MAX_PATH);
            final hModule = hMods.elementAt(0).value;
            if (GetModuleFileNameEx(hProcess, hModule, szModName, MAX_PATH) != 0) {
                final hexModuleValue = hModule
                    .toRadixString(16)
                    .padLeft(ffi.sizeOf<HMODULE>(), '0')
                    .toUpperCase();
                // Print the module name and handle value.
                print('\t${szModName.toDartString().split('\\').last.split('.exe').first.split('.EXE').first}'); // (0x$hexModuleValue)
            }
            free(szModName);
    }
    free(hMods);
    free(cbNeeded);

    // Release the handle to the process.
    CloseHandle(hProcess);

    return 0;
}