Home > Back-end >  C Windows API: GetOpenFileName and GetSaveFileName making GetAsyncKeyState stop working
C Windows API: GetOpenFileName and GetSaveFileName making GetAsyncKeyState stop working

Time:01-28

GetOpenFileName and GetSaveFileName making GetAsyncKeyState stop working. (Note: i am also using getch() from conio.h in some places if that is any useful)

A little example (UNTESTED):

#include <commdlg.h>
#include <windows.h>
#include <iostream>

using std::cout;

#define keyPressed(x) GetAsyncKeyState(x) & 0x8000

int main () {
  while (true) {
    if (keyPressed('w')) {
      cout << "W pressed\n";
      break;
    }
  }

  OPENFILENAME ofn = {0};
  char Buffer[300];
  std::fill(Buffer, Buffer   300, '\0');
  ofn.lStructSize = sizeof(OPENFILENAME);
  ofn.hwndOwner = GetForegroundWindow();
  ofn.lpstrFile = Buffer;
  ofn.nMaxFile = 300;
  ofn.Flags = OFN_EXPLORER;
  ofn.lpstrFilter = NULL;
  ofn.lpstrCustomFilter = NULL;
  ofn.nFilterIndex = 0;
  ofn.lpstrFileTitle = NULL;
  ofn.lpstrInitialDir = NULL;
  ofn.lpstrTitle = NULL;
  if (!GetOpenFileName(&ofn)) {
    cout << "Error\n";
  }

  while (true) {
    if (keyPressed('w')) {
      cout << "W pressed\n";
      break;
    }
  }
}

Thanks!

CodePudding user response:

I'm sure GetAsyncKeyState is working as normal but you are not actually calling it while the open/save dialog is open because these modal dialogs run their own message loop and the function does not return back to your code until you close the dialog.

You could run the GetAsyncKeyState loop in another thread and then it would work but you should not do that because polling in a loop is bad. Use RegisterHotKey or a low-level keyboard hook.

And finally, GetAsyncKeyState checks a virtual key code, not arbitrary ASCII characters.

CodePudding user response:

Alright, thanks to @Anders, setting ofn.hwndOwner to NULL worked. Thanks!

I didn't need to poll in another thread or use Virtual Key Codes but thanks for trying to help me!

  •  Tags:  
  • Related