如何获取我当前在 Flutter Windows 应用程序中活动的窗口/选项卡的 PID(进程 ID)?

问题描述 投票:0回答:1
import 'dart:io'
...
print(pid);

此代码打印我的 Flutter 应用程序的 pid。但我想在打开该应用程序时获取其他应用程序的 pid。 假设,我现在使用 Skype 应用程序。所以这个

print(pid)
将打印 Skype 的 pid。当我打开记事本时,它会打印记事本 pid。 有什么办法可以做到这一点吗? 预先感谢。

我已经找到了使用

dart:ffi
访问 psapi.dll 的方法。但什么也没得到。

flutter dart pid flutter-windows
1个回答
0
投票

平台精确的代码并可以访问本地 API。对于 Windows,您可以使用 Win32 API 来获取有关活动窗口及其进程 ID 的统计信息。为此,您可以使用 Dart 的 FFI(外部函数接口)来命名动态超链接库 (DLL) 中的功能,例如 user32.Dll 和 psapi.Dll。

这是一个例子

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.