Search code examples
flutterdartpidflutter-windows

How can I get PID(process id) of window/tab I'm currently active in Flutter windows application?


import 'dart:io'
...
print(pid);

This code print the pid of my Flutter application. But I want to get the other apps' pid when I switch on that app. Suppose, I am now on skype app. So this print(pid) will print pid of skype. When I switch on notepad it will print notepads pid. Is there any way to do that? Thanks in advance.

I've searched way to access psapi.dll using dart:ffi. But got nothing.


Solution

  • Finally I was able to find the solution.

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