Giter Site home page Giter Site logo

dart-windows / win32 Goto Github PK

View Code? Open in Web Editor NEW
744.0 15.0 120.0 46.4 MB

Access common Win32 APIs directly from Dart using FFI — no C required!

Home Page: https://win32.pub

License: BSD 3-Clause "New" or "Revised" License

Dart 88.17% C++ 0.59% Batchfile 0.02% JavaScript 0.72% MDX 1.35% TypeScript 8.38% CSS 0.76%
win32 dart ffi windows flutter

win32's Introduction

win32 README banner


Access Win32 APIs "directly" from Dart.

win32 is a Dart package that provides access to the most common Win32 APIs using FFI to make them accessible to Dart code without requiring a C compiler or the Windows SDK.

🎯 What is win32?

win32 allows Dart developers to tap into a broad range of Win32 API calls using FFI, simplifying access to Windows hardware and system services. By offering easy-to-use bindings for both traditional Win32 and COM (Component Object Model) APIs, it enables you to fully leverage Windows-specific functionalities directly in your Dart code.

💡 Why Use win32?

win32 is incredibly versatile and can be useful in a variety of scenarios, including:

  • Flutter Development on Windows: Need to access hardware accessories like gamepads or retrieve settings from the Windows registry in your app? win32 makes this possible with ease.

  • Cross-Platform Package Development: When writing a new cross-platform package, you can use win32 for the Windows-specific implementation, ensuring your package works seamlessly on Windows.

  • Enhanced Command-Line Utilities: If you're developing a command-line utility with Dart and require more advanced file APIs than what the dart:io library offers, win32 provides the necessary functionality.

  • Integration with Existing Windows Libraries: Smoothly integrate your apps with other Windows libraries that have published metadata using win32.

The main goal of win32 is to provide Dart developers with direct access to underlying Windows APIs, eliminating the need to manually map API conventions to Dart, simplifying development, and enhancing productivity.

📝 Documentation

Explore the full documentation at win32.pub/docs to dive deeper into the features and capabilities of the win32 package.

🚀 Getting Started

Add ffi and win32 packages to your project by running the appropriate command below:

For Flutter projects:

flutter pub add ffi win32

For Dart-only projects:

dart pub add ffi win32

Here's an example that demonstrates how to display a message box using the MessageBox function from the Windows API.

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

void main() {
  final lpCaption = 'Dart MessageBox Demo'.toNativeUtf16();
  final lpText = '''
This is not really an error, but we are pretending for the sake of this demo.

Resource error.
Do you want to try again?
'''
      .toNativeUtf16();

  final result = MessageBox(
    NULL,
    lpText,
    lpCaption,
    MESSAGEBOX_STYLE.MB_ICONWARNING | // Warning icon
        MESSAGEBOX_STYLE.MB_CANCELTRYCONTINUE | // Action button
        MESSAGEBOX_STYLE.MB_DEFBUTTON2, // Second button is the default
  );

  free(lpText);
  free(lpCaption);

  switch (result) {
    case MESSAGEBOX_RESULT.IDCANCEL:
      print('Cancel pressed');
    case MESSAGEBOX_RESULT.IDTRYAGAIN:
      print('Try Again pressed');
    case MESSAGEBOX_RESULT.IDCONTINUE:
      print('Continue pressed');
  }
}
MessageBox screenshot

🌟 Use Cases

Here are a few use cases showcasing the power of win32:

  • Building Windows Apps with Flutter: Create a Flutter-based Windows app that relies on Win32 APIs.
Task Manager App screenshot
  • Accessing System Information: Retrieve system information not directly accessible through Dart's core libraries.
System information screenshot
  • Enumerating Installed Fonts: Use EnumFontFamiliesEx to list all locally-installed fonts.
Fonts screenshot
  • Developing Traditional Win32 Apps in Dart: Build classic Windows applications purely in Dart.
DartNote App screenshot
  • Game Development: Create a fully-fledged game using GDI, like the example below.
Tetris Game screenshot
  • Advanced Console Applications: Build packages like dart_console that enable advanced console manipulation.

Dart console ANSI color demo screenshot

  • Modern File Pickers: Use filepicker_windows for a modern Windows file picker experience in your Dart/Flutter apps.
Windows file picker screenshot

This package provides minimal modifications to the Win32 API to support Dart idioms, aiming for high familiarity with existing Windows developers. Other Dart packages can build on these primitives to provide a more idiomatic API for Dart and Flutter developers.

A good example is win32_registry, which offers a set of APIs for accessing the Windows Registry without requiring knowledge of FFI.

📚 Examples

There are many examples included with this package that demonstrate calling various Win32 and COM APIs. These can be found in the examples subdirectory, and a short description of each example can be found here.

📦 Packages Built on win32

A growing number of Dart packages are built on the low-level APIs exposed by win32, providing more idiomatic class wrappers that are easy to integrate into your Flutter and Dart apps.

Here are some of the packages built on top of win32:

  • filepicker_windows: Provides access to Windows file open/save common dialog boxes.
  • win32_clipboard: Access the Windows Clipboard from Dart.
  • win32_gamepad: A friendly Dart API for accessing gamepads on Windows.
  • win32_gui: Provides object-oriented API for Win32 GUI development.
  • win32_registry: Easy access to the Windows Registry from Dart.
  • win32_runner: An experimental shell (runner) for hosting Flutter apps without a C++ compiler.

Find more packages on pub.dev.

🐞 Features and Bugs

win32 package offers a subset of the Win32 API, with more APIs being added regularly based on user demand. If you require additional functionality or encounter any bugs, please file an issue on our issue tracker.

🔄 Backwards Compatibility

While win32 follows semantic versioning (semver), some breaking changes may occur in minor versions due to improvements in the win32metadata scraper or the addition of new APIs.

To avoid potential issues, consider pinning to a specific version of win32 or regularly testing with the latest version.

🙏 Contributors

A heartfelt thank you to all our contributors who help improve win32 by creating packages, assisting with issues and pull requests, and participating in discussions.


win32 contributors graph

🎉 Acknowledgements

The Tetris example was adapted from a C version by Chang-Hung Liang.

The C implementation of Snake by David Jones was ported with his permission.

The original C version of the Notepad example was authored by Charles Petzold, licensed by him without restriction.

The original C version of the custom titlebar example is by Dmitriy Kubyshkin and is licensed under the MIT License.

Win32 API documentation comments are licensed by Microsoft under the Creative Commons Attribution 4.0 International Public License.

win32's People

Contributors

arcticfox1919 avatar au250073 avatar bonukai avatar bryancusatis avatar cbenhagen avatar dependabot[bot] avatar devoncarew avatar dkrutskikh avatar domesticmouse avatar elmoribond avatar gaddlord avatar halildurmus avatar hexer10 avatar hpoul avatar hpstuff avatar ilopx avatar krjw-eyev avatar lcarrasco avatar loic-sharma avatar mit-mit avatar sirusdoma avatar smotto avatar solbirn avatar stuartmorgan avatar sunbreak avatar timsneath avatar untp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

win32's Issues

Getting the real background-color

hi can you help me

this is method fails, return value 0

void showBg() {
   var hr = CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
  if (FAILED(hr)) {
    throw WindowsException(hr);
  }

  final bgColor = DesktopWallpaper.createInstance();
  final nlmBackgroundColor = allocate<Uint32>();
  hr = bgColor.GetBackgroundColor(nlmBackgroundColor);
  
  if (FAILED(hr)) {
    throw WindowsException(hr);
  }

  final connectivity = nlmBackgroundColor.value;

  print(connectivity);
  free(nlmBackgroundColor);
  free(bgColor.ptr);


}

Memory manipulation API in Dart

Hi,
I was wondering if the aim of this library was to provide ffi only for ui api or also low end memory manipulation functions such as ReadProcessMemory, WriteProcessMemory, EnumProcesses, EnumProcessModules, ...
If so could they be implemented anytime in the future, for some I could also make a PR, but I couldn't find anyway to port EnumProcessModules , since it requires an array as parameter and I couldn't find any documentation about that.

Add WinRT support

Now that COM is checked in and relatively stable, let's add support for WinRT. Working on this in the winrt branch.

High-level Flutter API surface

Figure out what APIs are relevant to Flutter, and add an idiomatic surface that does not require knowledge of FFI, null-terminated strings etc.

Convert to null safety

Core is migrated. Still broken:

[ ] Notepad doesn't quit properly
[ ] WinMD example doesn't work
[X] WinMD generator still contains lots of unnecessary ? (hasn't been properly migrated)
[X] Tetris needs testing

Simple input dialog

I've searched around, tried some of the examples. Very cool stuff!

Is there a way to show a simple input dialog? I am looking for a small window that a user can type into and return the value for use. Something like:

int timerDuration = getInput();

and the user could type 5 so a 5 minute timer could be set.

The function 'CreateCompatibleDC' isn't defined

Hi,
I am using the latest ^1.7.4 version of the library and the screenshot example has compile errors like
The function 'CreateCompatibleDC' isn't defined.
The function 'SetStretchBltMode' isn't defined.
Undefined name 'BITMAP'.
The function 'StretchBlt' isn't defined.
etc.

FindWindowEx

Hello,

I like your API,

I wish I could use this function to find the first windows

var hWnd = FindWindowEx(textFormat: TextFormat.ansi, lpszWindow:Utf8.toUtf8( "MyWindowsName"));
I found the code in another API (dart_winapi) and it works fine,

what this allows to do is for example to maximize the first window when launching the application

Sample :

var hWnd  = FindWindowEx(textFormat: TextFormat.ansi, lpszWindow:Utf8.toUtf8(  "MyWindowsName"));
ShowWindow(hWnd: hWnd, nCmdShow:  3 );

here are the constants if you want to integrate them :

static const int swForceMinimize = 11; //Minimizes a window, even if the thread that owns the window is not responding.
      //This flag should only be used when minimizing windows from a different thread.
  static const int sw_Hide = 0; //Hides the window and activates another window.
  static const int sw_Maximize = 3; //Maximizes the specified window.
  static const int sw_Minimize =
      6; //Minimizes the specified window and activates the next top-level window in the Z order.
  static const int sw_Restore =
      9; //Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.
  static const int sw_Show =
      5; //Activates the window and displays it in its current size and position.
  static const int sw_ShowDefault =
      10; //Sets the show state based on the SW_ value specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application.
  static const int sw_ShowMaximized =
      3; // Activates the window and displays it as a maximized window.
  static const int sw_ShowMinimized =
      2; //Activates the window and displays it as a minimized window.
  static const int sw_ShowMinNoActive =
      7; //Displays the window as a minimized window. This value is similar to SW_SHOWMINIMIZED, except the window is not activated.
  static const int sw_ShowNa =
      8; //Displays the window in its current size and position. This value is similar to SW_SHOW, except that the window is not activated.
  static const int sw_ShowNoactivate =
      4; //Displays a window in its most recent size and position. This value is similar to SW_SHOWNORMAL, except that the window is not activated.
  static const int sw_ShowNormal =
      1; // Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.

Figure out async calls to WinRT

Compilation fails with 'InvalidType doesn't have nullability'

/root/.pub-cache/hosted/pub.dartlang.org/win32-1.7.1/lib/src/generated/IWbemServices.dart:495:15:
Error: 'NativeFunction' isn't a type.
Pointer<NativeFunction<_ExecMethod_Native>>.fromAddress(
^^^^^^^^^^^^^^
/root/.pub-cache/hosted/pub.dartlang.org/win32-1.7.1/lib/src/generated/IWbemServices.dart:495:7:
Error: Method not found: 'Pointer.fromAddress'.
Pointer<NativeFunction<_ExecMethod_Native>>.fromAddress(
^^^^^^^^^^^

Documenting kernel32.dart and friends

Hey Tim,

To make it easier to explore win32, I'd like to add documentation to kernel32.dart (and the other APIs), but I'm guessing this file is autogenerated from somewhere. Can you give guidance on a viable path forward that I could start contributing to?

brett

Autogenerate Win32 APIs

  1. Create a function to extract the comments, methods, parameters from the existing Dart files and export into a CSV file
  2. Create a function to generate the core files from the CSV file

Advantages:

  • Resilience to changes in the FFI format (easy to update the latter function rather than editing code
  • Some better error checking (can inspect the CSV file with standardized tools like Google Sheets for consistency, e.g. is a DWORD always converted into an Uint32?)
  • May be able to autogenerate documentation if there are public sources for API descriptions (can we scrape something)?
  • Allows switch to a more documentable format (see FillConsoleOutputCharacter in the integrated-ffi branch) -- it doesn't matter so much if the code is less readable if it's autogenerated anyway.
  • Opportunity to read metadata in the future if Win32 APIs are documented in this way

Disadvantages

  • Initial cost

Clean up HRESULT error handling

We handle errors inconsistently here.

Win32 defines an HRESULT as a signed value:

typedef LONG HRESULT;
typedef long LONG;

Typically it is shown as a const value (e.g. 0x800401F0), but when assigned to a Dart int, that is of course a positive value. To minimize confusion and retain consistency with COM:

  • An HRESULT is treated as a signed int in Dart, rather than a positive 0x80000000 value.
  • COM error constants will be converted to signed 32-bit values

The primary change to the code is that a line like:

const CO_E_NOTINITIALIZED = 0x800401F0;

will become

final CO_E_NOTINITIALIZED = 0x800401F0.toSigned(32);

While this adds some pain to the constants.dart file, this will remove some .toUnsigned(32) calls in the code and therefore avoid the risk of a returned HRESULT failing an equality test with a constant.

We'll need to make some updates to the code to test this consistently; I suspect there's a bug farm lurking here already that this work will root out. Good opportunity for more tests.

Console window stays open when running a compiled Win32 GUI EXE

When you execute a compiled Win32 (non-console) application such as the Notepad example, the console application that launches it remains visible.

In #126, @ilopX suggests a clever workaround technique to patch the console executable with the same header that you'd get from the /SUBSYSTEM:WINDOWS linker command in Visual Studio. This solution makes me slightly nervous due to the brute force nature of hot-patching binaries.

For completeness, another approach that doesn't require patching executables is to add this to the first line of your main() function:

  ShowWindow(GetConsoleWindow(), SW_HIDE);

although I concede that this generates a very quick flash as it loads and immediately closes the console window.

This also feels like a good feature request for the Dart compiler, to solve this without the downsides of either of our proposals.

Opening this issue to explore solutions to this problem.

More defensive coding against missing APIs on Windows 7 and ARM64

See https://github.com/timsneath/win32/runs/1645786081?check_suite_focus=true:

00:00 +6 -1: test\api_test.dart: Test kernel32 functions Can instantiate ClosePseudoConsole [E]
  Invalid argument(s): Failed to lookup symbol (127)
  dart:ffi            DynamicLibrary.lookup
  test\api_test.dart  main.<fn>.<fn>
  
00:00 +10 -2: test\api_test.dart: Test kernel32 functions Can instantiate CreatePseudoConsole [E]
  Invalid argument(s): Failed to lookup symbol (127)
  dart:ffi            DynamicLibrary.lookup
  test\api_test.dart  main.<fn>.<fn>
  
00:00 +56 -3: test\api_test.dart: Test kernel32 functions Can instantiate IsWow64Process2 [E]
  Invalid argument(s): Failed to lookup symbol (127)
  dart:ffi            DynamicLibrary.lookup
  test\api_test.dart  main.<fn>.<fn>
  
00:00 +66 -4: test\api_test.dart: Test kernel32 functions Can instantiate ResizePseudoConsole [E]
  Invalid argument(s): Failed to lookup symbol (127)
  dart:ffi            DynamicLibrary.lookup
  test\api_test.dart  main.<fn>.<fn>
  
00:00 +201 -5: test\api_test.dart: Test user32 functions Can instantiate GetSystemDpiForProcess [E]
  Invalid argument(s): Failed to lookup symbol (127)
  dart:ffi            DynamicLibrary.lookup
  test\api_test.dart  main.<fn>.<fn>
 
00:19 +503 -6: test\winmd_test.dart: Find a specific WinMD token [E]
  Expected: <33554435>
    Actual: <33554490>
  
  package:test_api           expect
  test\winmd_test.dart 25:7  main.<fn>

UNRELATED TO THIS PROJECT | Help needed

hi, I've posted this question almost everywhere I could, you seem the person that could most likely help me

it's just a few lines of code that I couldn't get my head around

if you find the time, I'd be glad if you could help me

thanks

[Proposal] Add support for WinRT Windows.Devices.Geolocation APIs

Description

Hey Tim, currently as a part of GSoC'20 we are trying to land new samples in the samples repo to help developers understand how to develop a federated plugin and use platform channels. For the federated plugin sample, we have decided to expose Geolocations APIs on different platforms, and currently, we are looking at the possibilities to add the support for windows too.

It would be great if we can provide the support for GeoLocator API to fetch the current location in win32.

cc:/ @domesticmouse

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.