dart 我如何获得PID(进程ID)的窗口/选项卡我目前活跃在Flutter窗口应用程序?

eqzww0vc  于 2024-01-04  发布在  Flutter
关注(0)|答案(2)|浏览(191)
import 'dart:io'
...
print(pid);

字符串
这段代码打印我的Flutter应用程序的PID.但我想得到其他应用程序的PID,当我打开该应用程序.假设,我现在在Skype应用程序.所以这个print(pid)将打印Skype的PID.当我打开记事本它会打印记事本PID.有什么办法做到这一点吗?提前感谢.
我已经搜索了使用dart:ffi访问psapi.dll的方法。但一无所获。

kt06eoxx

kt06eoxx1#

平台精确的代码和访问本地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);
}

字符串

anhgbhbe

anhgbhbe2#

我终于找到了解决办法。

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

字符串

相关问题