dartuser32dart-ffi

FindWindowA function does not yield the expected output in dart foreign function interface


The following dart code's expected output is the handle to the file explorer window but the output always comes out to be 0 even though the file explorer window does exist!

import 'package:ffi/ffi.dart';
import 'dart:ffi';

void main() {
  DynamicLibrary dl = DynamicLibrary.open('user32.dll');
  final func = dl.lookupFunction<
      IntPtr Function(Pointer<Utf16>?, Pointer<Utf16>?),
      int Function(Pointer<Utf16>?, Pointer<Utf16>?)
    >('FindWindowA');

  print(func(nullptr, 'File Explorer'.toNativeUtf16()));
}

I have ran the function FindWindowA in a c++ program and it has returned the exptected output with the same input values that are NULL and 'File Explorer'.

In dart using null throws the error Invalid argument(s): argument value for ':ffi_param1' is null; hence the use of nullptr


Solution

  • FindWindowA does not take pointers to UTF-16 strings. The A in FindWindowA stands for "ANSI", which is Microsoft's way of indicating that it uses strings with single-byte code units encoded in the system's local encoding. (This is also indicated by its signature, which takes LPCSTR arguments.)

    If you want to pass UTF-16 strings (which in Microsoft Windows are considered "wide strings"), then use FindWindowW.