Tags down


Implementing winapi(SendInput) with dart:ffi

By : Fanny Woestyn
Date : September 22 2020, 12:00 PM
help you fix your problem Your approach will not work since your struct is just too big. What you really want is the allocated memory have the same size as in regular C version (which is 28 bytes), so something like this:
code :
class KeyboardInput extends Struct {
  @Uint32() int type;
  @Uint16() int virtualCode;
  @Uint16() int scanCode;
  @Uint32() int flags;
  @Uint32() int time;
  Pointer dwExtraInfo;
  @Uint32() int _padding;
import 'dart:ffi';
DynamicLibrary _user32 = DynamicLibrary.open("user32.dll");

typedef _keybd_event_C = Void Function(Uint8 bVk, Uint8 bScan, Uint32 dwFlags, Pointer dwExtraInfo);
typedef _keybd_event_Dart = void Function(int bVk, int bScan, int dwFlags, Pointer dwExtraInfo);
var keybd_event = _user32.lookupFunction<_keybd_event_C, _keybd_event_Dart>("keybd_event");

const MAPVK_VK_TO_VSC = 0;
typedef _MapVirtualKeyW_C = Uint32 Function(Uint32 uCode, Uint32 uMapType);
typedef _MapVirtualKeyW_Dart = int Function(int uCode, int uMapType);
var MapVirtualKeyW = _user32.lookupFunction<_MapVirtualKeyW_C, _MapVirtualKeyW_Dart>("MapVirtualKeyW");

void main() {
    MapVirtualKeyW(0x5a, MAPVK_VK_TO_VSC), 

Share : facebook icon twitter icon

Issue with WinAPI SendInput code

By : Csempe
Date : March 29 2020, 07:55 AM
Does that help I suppose it is because you are sending only KEYDOWN messages. You might want to try sending first KEYDOWN, then KEYEVENTF_KEYUP for the same character.
[edit for NEW CODE]

Implementing Pattern with RegExp in Dart

By : LinChengYi
Date : March 29 2020, 07:55 AM
this one helps. I think it is fine how you did it (RegExp as member).
The abstract class with the factory constructor is a construct to prevent deriving from RegExp.

winapi: Can SetFocus() return NULL without an error? because that's what I'm seeing when implementing focus restore a la

By : ahmed wael
Date : March 29 2020, 07:55 AM
this one helps. I decided to take Harry Johnston's advice to take Raymond Chen's advice not to worry about the error return because we can't handle the return somehow. All my error returns panic and abort the program anyway; I just wanted to cover all possible bases when it comes to error returns. (On GTK+ you can't override the error logging; on Mac OS X/Cocoa there are exceptions but some people yelled at me for asking about them, so I guess everyone's in agreement about all this...)
Here's a program that confirms that yes, SetFocus() returns NULL for an out-of-thread previous window:
code :
// 6 june 2014
// based on winfocuspanictest 5 june 2014
// scratch Windows program by pietro gagliardi 17 april 2014
// fixed typos and added toWideString() 1 may 2014
// borrows code from the scratch GTK+ program (16-17 april 2014) and from code written 31 march 2014 and 11-12 april 2014
#define _UNICODE
#define UNICODE
#define STRICT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <windows.h>

HMODULE hInstance;
HICON hDefaultIcon;
HCURSOR hDefaultCursor;
HFONT controlfont;

void panic(char *fmt, ...);
TCHAR *toWideString(char *what);

HWND label;
HWND reportwin;

void onActivate(HWND hwnd, WPARAM wParam)
    UINT state = (UINT) LOWORD(wParam);
    int minimized = HIWORD(wParam) != 0;

    if (hwnd != reportwin)
    if (minimized)
    if (state == WA_INACTIVE) {
        HWND old;

        old = GetFocus();
        if (old != NULL && IsChild(hwnd, old))
            SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) old);
    } else {
        HWND lastfocus, result;
        DWORD err;
        static WCHAR lastpos[200] = L"";

        lastfocus = (HWND) GetWindowLongPtr(hwnd, GWLP_USERDATA);
        if (lastfocus == NULL)
        SetLastError(0);        // just in case
        result = SetFocus(lastfocus);
        err = GetLastError();
        snwprintf(lastpos, 199, L"last: %p err: %d cur: %p", result, err, GetFocus());
        SendMessage(label, WM_SETTEXT, 0, (LPARAM) lastpos);

LRESULT CALLBACK wndproc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
    switch (msg) {
    case WM_ACTIVATE:
        onActivate(hwnd, wParam);
        return 0;
    case WM_CLOSE:
        return 0;
        return DefWindowProc(hwnd, msg, wParam, lParam);
    panic("oops: message %ud does not return anything; bug in wndproc()", msg);

void makeMainWindowClass(void)
    WNDCLASS cls;

    ZeroMemory(&cls, sizeof (WNDCLASS));
    cls.lpszClassName = L"mainwin";
    cls.lpfnWndProc = wndproc;
    cls.hInstance = hInstance;
    cls.hIcon = hDefaultIcon;
    cls.hCursor = hDefaultCursor;
    cls.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
    if (RegisterClass(&cls) == 0)
        panic("error registering window class");

HWND makeMainWindow(int isreportwin)
    HWND hwnd;
    RECT r;

    r.left = 0;
    r.top = 0;
    r.right = 320;
    r.bottom = 70;
    if (AdjustWindowRectEx(&r, WS_OVERLAPPEDWINDOW, FALSE, 0) == 0)
        panic("AdjustWindowRectEx() failed");
    hwnd = CreateWindowEx(0,
        L"mainwin", L"Main Window",
        r.right - r.left, r.bottom - r.top,
        NULL, NULL, hInstance, NULL);
    if (hwnd == NULL)
        panic("opening main window failed");

#define CXSTYLE (0)
#define SETFONT(hwnd) SendMessage(hwnd, WM_SETFONT, (WPARAM) controlfont, (LPARAM) TRUE);

    HWND entry;
    HWND xlabel;

    entry = CreateWindowEx(WS_EX_CLIENTEDGE | CXSTYLE,
        L"edit", L"Click here to focus",
        10, 10, 300, 20,
        hwnd, (HMENU) 100, hInstance, NULL);
    if (entry == NULL)
        panic("error creating entry");

    xlabel = CreateWindowEx(CXSTYLE,
        L"static", L"",
        10, 40, 300, 20,
        hwnd, (HMENU) 101, hInstance, NULL);
    if (xlabel == NULL)
        panic("error creating label");

    if (isreportwin) {
        reportwin = hwnd;
        label = xlabel;
    return hwnd;

void initwin(void);
void firstShowWindow(HWND hwnd);

    MSG msg;

    firstShowWindow(makeMainWindow(data != NULL));
    for (;;) {
        BOOL gmret;

        gmret = GetMessage(&msg, NULL, 0, 0);
        if (gmret == -1)
            panic("error getting message");
        if (gmret == 0)
            exit(0);        // kill the program if either window is closed
    return 0;

int main(int argc, char *argv[])
    if (CreateThread(NULL, 0, thread, NULL, 0, NULL) == NULL)       // null for the other thread's window
        panic("error creating thread");
    thread((void *) thread);        // non-null for the main window
    return 0;

void initwin(void)

    hInstance = GetModuleHandle(NULL);
    if (hInstance == NULL)
        panic("error getting hInstance");
    if (hDefaultIcon == NULL)
        panic("error getting default window class icon");
    hDefaultCursor = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
    if (hDefaultCursor == NULL)
        panic("error getting default window cursor");
    ncm.cbSize = sizeof (NONCLIENTMETRICS);
    if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS,
        sizeof (NONCLIENTMETRICS), &ncm, 0) == 0)
        panic("error getting non-client metrics for getting control font");
    controlfont = CreateFontIndirect(&ncm.lfMessageFont);
    if (controlfont == NULL)
        panic("error getting control font");

void panic(char *fmt, ...)
    char *msg;
    TCHAR *lerrmsg;
    char *fullmsg;
    va_list arg;
    DWORD lasterr;
    DWORD lerrsuccess;

    lasterr = GetLastError();
    va_start(arg, fmt);
    vfprintf(stderr, fmt, arg);
    // according to http://msdn.microsoft.com/en-us/library/windows/desktop/ms680582%28v=vs.85%29.aspx
        NULL, lasterr,
        (LPTSTR) &lerrmsg, 0, NULL);
    if (lerrsuccess == 0) {
        fprintf(stderr, "critical error: FormatMessage() failed in panic(): last error in panic(): %ld, last error from FormatMessage(): %ld\n", lasterr, GetLastError());
    fwprintf(stderr, L"\nlast error: %s\n", lerrmsg);

void firstShowWindow(HWND hwnd)
    // we need to get nCmdShow
    int nCmdShow;

    nCmdShow = SW_SHOWDEFAULT;
    if ((si.dwFlags & STARTF_USESHOWWINDOW) != 0)
        nCmdShow = si.wShowWindow;
    ShowWindow(hwnd, nCmdShow);
    if (UpdateWindow(hwnd) == 0)
        panic("UpdateWindow(hwnd) failed in first show");

How to send a key using winapi's SendInput?

By : Anna3anana
Date : March 29 2020, 07:55 AM
I hope this helps . The definition of winapi::INPUT in the version of winapi-rs you use is incorrect. It appears to have been fixed today (or yesterday, depending on where you are).

c++ winapi SendInput unexpected behavior

By : Hiruine
Date : March 29 2020, 07:55 AM
With these it helps Use MOUSEEVENTF_ABSOLUTE flag and convert the points to mouse coordinates (0 to 0xFFFF) to set the mouse coordinates. Otherwise the x/y coordinates are regarded as relative positions.
code :
int main() 

    POINT p;
    cout << p.x << " " << p.y << endl;

    int screenWidth = GetSystemMetrics(SM_CXSCREEN);
    int screenHeight = GetSystemMetrics(SM_CYSCREEN);
    cout << screenWidth << " " << screenHeight << endl;

    p.x = screenWidth / 2;
    p.y = screenHeight / 2;

    INPUT in[1] = { 0 };
    in[0].type = INPUT_MOUSE;
    in[0].mi.dx = (p.x * 0xFFFF) / (GetSystemMetrics(SM_CXSCREEN) - 1);
    in[0].mi.dy = (p.y * 0xFFFF) / (GetSystemMetrics(SM_CYSCREEN) - 1);

    SendInput(1, in, sizeof(INPUT));

    cout << p.x << " " << p.y << endl;

    return 0;
Related Posts Related Posts :
  • Access captured variables outside the lambda
  • Storing 4 values from each line from a txt file, into an object - C++
  • What is the most efficient way to test for duplicates in a user inputted array?
  • How to find a string in a binary file?
  • Passing variable into lambda
  • decltype(auto) function return type does not deduce && types
  • Find the unique elements of a vector C++
  • Why doesn't str != "hello" && "goodbye" work?
  • Array rotate and delete
  • Is the concept of release-sequence useful in practice?
  • Multiple spotlights in opengl doesn't work
  • The for loop isn't entered even if the initial requirement is true
  • Function is called twice from the same thread for the same object with the same call stack
  • Filling char pointer correctly
  • How Base class members gets copied in inheritance when we copy/assign derived class objects?
  • call method from a function pointer
  • Is it common to declare const pointers in C++?
  • How to check whether new threads created inside third party DLL in visual c++ application
  • I cannot convert a '2D array whit bool' to a 'void 2D array bool'(for game of life)
  • How to send variables between classes in Qt
  • What are the similarities and differences between C++'s concepts and Rust's traits?
  • Variadic templates in C++ 11 and class constructors
  • getting segmentation fault when copying arrays using std::copy
  • std::cout is decreasing CPU Usage?
  • Trying to use find_if function to locate value in vector of pairs by first element
  • Lottery simulator is returning garbage values and not the users lotto numbers and the winning numbers
  • error: expression must have integral or unscoped enum type when incrementally filling in vectors
  • auto fail to deduce correct return type
  • Pass string or wstring in a function
  • Is there a way to get some function called on every thread that gets created?
  • How can I enforce two function parameters have the same template type?
  • Using strcpy_s() and strcat_s() with dynamically allocated strings
  • Tensorflow Lite arm64 error: cannot convert ‘const int8x8_t?
  • How to pass `this` pointer from outer class to a member structure?
  • Storing integers values from file into a vectors of vector
  • Why `static` functions in different TUs do not break the ODR?
  • Base class and templates
  • boost::asio allow non-blocking accept of new connections while handler for connection is blocking
  • How to write custom comparator for std::minmax function for datatype vector<glm::vec3> (opengl datatype)
  • Confused about * and & with pointers
  • What's the value in memory?
  • Qt - How to handle memory management for dialogs?
  • Why am I having trouble compiling a templated class?
  • Understanding which method will be invoked
  • Why does bool casting is called?
  • Insert string at linking time
  • How to use a C++ lambda to convert a member function pointer to a normal function pointer for use as a callback
  • Is the Intel C++ Compiler (19.0) now only using the Clang front-end (i.e. already abandoned EDG)?
  • Why does deleting the move constructor cause a compile error?
  • How can I make sure my random number between 0 and 1 generated by rand is not 0?
  • How will I pass ranges instead of iterator-pairs in C++20?
  • Use std::optional as a regular pointer vs use has_value() and value
  • How to interlace string with one character?
  • Derived class from Template argument doesn't have protected member access
  • Parallel For Loops: Find if a sorted array contains duplicate elements
  • Casting a reference to a base class: standard behaviour?
  • How to check dllmain function is returning false
  • How to update the attributes of an object?
  • How do I extract an integer in a string?
  • Why code give segmentation fault on inputs greater than 10?
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk