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

152 Views Asked by At
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.

2

There are 2 best solutions below

0
On BEST ANSWER

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);
}
1
On

Platform-precise code and having access to local APIs. In the case of Windows, you could use the Win32 API to get statistics about the active window and its process ID. To do this, you may use Dart's FFI (Foreign Function Interface) to name capabilities from dynamic hyperlink libraries (DLLs) like user32.Dll and psapi.Dll.

Here is an example

import 'dart:ffi' as ffi;

class Psapi {
  static final ffi.DynamicLibrary psapi = ffi.DynamicLibrary.open('psapi.dll');

  static int GetWindowThreadProcessId(
      ffi.IntPtr hwnd, ffi.Pointer<ffi.Uint32> lpdwProcessId) {
    return psapi
        .lookupFunction<
            ffi.Uint32 Function(
                ffi.IntPtr hwnd, ffi.Pointer<ffi.Uint32> lpdwProcessId),
            int Function(ffi.IntPtr hwnd,
                ffi.Pointer<ffi.Uint32> lpdwProcessId)>('GetWindowThreadProcessId')(
      hwnd,
      lpdwProcessId,
    );
  }
}

class User32 {
  static final ffi.DynamicLibrary user32 = ffi.DynamicLibrary.open('user32.dll');

  static ffi.IntPtr GetForegroundWindow() {
    return user32
        .lookupFunction<ffi.IntPtr Function(), ffi.IntPtr Function()>(
            'GetForegroundWindow')();
  }
}

void main() {
  ffi.Pointer<ffi.Uint32> pidPointer = ffi.allocate<ffi.Uint32>();
  ffi.IntPtr hwnd = User32.GetForegroundWindow();

  Psapi.GetWindowThreadProcessId(hwnd, pidPointer);

  int pid = pidPointer.value;

  print('Process ID of the active window: $pid');

  ffi.free(pidPointer);
}