- 1 year ago
How get process PID in Dart (Windows) with EnumProcesses
To obtain the process IDs (PIDs) of running processes in Dart on Windows, you can use the dart:ffi
library to interface with the Windows API. Here's an example of how you can retrieve process IDs using the EnumProcesses
function:
- Create a new Dart file (e.g.,
process_pid.dart
) and add the following code:
dartimport 'dart:ffi';
import 'package:ffi/ffi.dart';
final kernel32 = DynamicLibrary.open('kernel32.dll');
typedef EnumProcessesC = Int32 Function(Pointer<Uint32> lpidProcess, Uint32 cb, Pointer<Uint32> lpcbNeeded);
typedef EnumProcessesDart = int Function(Pointer<Uint32> lpidProcess, int cb, Pointer<Uint32> lpcbNeeded);
void main() {
final enumProcesses = kernel32
.lookupFunction<EnumProcessesC, EnumProcessesDart>('EnumProcesses');
const maxProcesses = 1024;
final pids = allocate<Uint32>(count: maxProcesses);
final pBytesReturned = allocate<Uint32>();
enumProcesses(pids, maxProcesses * sizeOf<Uint32>(), pBytesReturned);
final numberOfPids = pBytesReturned.value ~/ sizeOf<Uint32>();
for (var i = 0; i < numberOfPids; i++) {
final pid = pids.elementAt(i).value;
print('Process ID: $pid');
}
free(pids);
free(pBytesReturned);
}
- Run the Dart script using the
dart
command:
dart process_pid.dart
The code above uses the dart:ffi
library to define the necessary types and functions to interface with the EnumProcesses
function from the Windows API. It loads the kernel32.dll
library using DynamicLibrary.open
and looks up the EnumProcesses
function using lookupFunction
.
The EnumProcesses
function retrieves the process IDs of all running processes. The code allocates memory to store the process IDs using allocate
and retrieves the number of bytes returned using pBytesReturned
. It then loops over the allocated memory to extract and print each process ID.
Remember to run the Dart script with appropriate permissions to access the necessary system functions.