I am trying to change the keys my keyboard sends to applications. I've already created a global hook and can prevent the keys I want, but I want to now send a new key in place. Here's my hook proc:
LRESULT __declspec (dllexport) HookProc(int nCode, WPARAM wParam, LPARAM lParam)
{
int ret;
if(nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
kbStruct = (KBDLLHOOKSTRUCT*)lParam;
printf("\nCaught [%x]", kbStruct->vkCode);
if(kbStruct->vkCode == VK_OEM_MINUS)
{
printf(" - oem minus!");
keybd_event(VK_DOWN, 72, KEYEVENTF_KEYUP, NULL);
return -1;
}
else if(kbStruct->vkCode == VK_OEM_PLUS)
{
printf(" - oem plus!");
keybd_event(VK_UP, 75, KEYEVENTF_KEYUP, NULL);
return -1;
}
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
I've tried using SendMessage and PostMessage with GetFocus() and GetForegroudWindow(), but can't figure out how to create the LPARAM for WM_KEYUP or WM_KEYDOWN. I also tried keybd_event(), which does simulate the keys (I know because this hook proc catches the simulated key presses), including 5 or 6 different scan codes, but nothing affects my foreground window.
I am basically trying to turn the zoom bar on my ms3200 into a scroll control, so I may even be sending the wrong keys (UP and DOWN).
Calling keybd_event is correct. If all you're doing is a key up, maybe the window processes the key down message instead. You really need to send a key down followed by a key up:
keybd_event(VK_UP, 75, 0, NULL);
keybd_event(VK_UP, 75, KEYEVENTF_KEYUP, NULL);
Or, better yet, send the key down when the OEM key goes down and a key up when the OEM key goes up. You can tell the down/up state by kbStruct->flags & LLKHF_UP.
You may wish to use SendInput, as keybd_event as has been superseded. The MSDN Magazine article C++ Q&A: Sending Keystrokes to Any App has a useful example.
You might want to try Control-UpArrow and Control-DownArrow instead of Up and Down. However this doesn't seem to work for all applications, and even on application where it does work, it may depend on where the focus is.
Related
I want a multiline EDIT control, which is a child of a dialog, to take tabs as regular text input (instead of switching to the next control).
According to multiple resources, the correct way of doing this is to handle WM_GETDLGCODE and returning DLGC_WANTTAB (or checking + DLGC_WANTMESSAGE).
See:
https://stackoverflow.com/a/16668256/653473
https://stackoverflow.com/a/42352363/653473
Raymond Chen's first comment here: https://stackoverflow.com/a/18444839/653473
Raymond's article suggests that what I want is in fact the default behavior, which is not what I'm observing.
Reproduction:
This is based on Visual Studio's default Windows Desktop Application C++ template. If you don't have that for some reason, the contents aren't that important; what's important is that there is an "About" dialog box being shown with the DialogBox function.
Create an EDIT control in the dialog, and subclass that:
WNDPROC OriginalEditWndProc;
// Message handler for about box.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
{
HWND hEdit = CreateWindowExW(0, L"EDIT", NULL, WS_VISIBLE | WS_CHILD | ES_MULTILINE, 0, 0, 100, 100, hDlg, NULL, NULL, NULL);
OriginalEditWndProc = (WNDPROC)GetWindowLongPtrW(hEdit, GWLP_WNDPROC);
SetWindowLongPtrW(hEdit, GWLP_WNDPROC, (LONG_PTR)EditSubclassProc);
return (INT_PTR)TRUE;
}
}
return (INT_PTR)FALSE;
}
Using this subclass WNDPROC:
static LRESULT CALLBACK EditSubclassProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == WM_GETDLGCODE)
{
OutputDebugStringA("WM_GETDLGCODE\r\n");
return OriginalEditWndProc(hWnd, message, wParam, lParam) | DLGC_WANTTAB /* this should make it work */;
}
else if (message == WM_KEYDOWN)
{
if (wParam == VK_TAB)
{
OutputDebugStringA("got VK_TAB\r\n");
return OriginalEditWndProc(hWnd, message, wParam, lParam);
}
}
return OriginalEditWndProc(hWnd, message, wParam, lParam);
}
(Note that it makes no difference to use comctl32's SetWindowSubclass. Note also that this dialog is not functional because it does not handle a WM_COMMAND to be able close it, but that's irrelevant.)
Observations:
We do get "got VK_TAB" every time tab is pressed.
If ES_MULTILINE is present, then the keyboard focus goes to the OK button of the About dialog.
If ES_MULTILINE is removed, then nothing happens upon pressing tab.
Returning DLGC_WANTMESSAGE instead of merely DLGC_WANTTAB doesn't change anything.
Furthermore: If the About dialog is not displayed as a dialog (in other words, IsDialogMessage is not called), but as a regular window, then the behavior is different.
Change the way the dialog box is shown by modifying IDM_ABOUT handler:
case IDM_ABOUT:
{
//DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
HWND hDlg = CreateDialogParamW(NULL, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About, 0);
ShowWindow(hDlg, SW_SHOW);
break;
}
Observations:
There is one WM_GETDLGCODE when the dialog is first displayed (for reasons unknown), and then no more of these messages (as expected).
We do get "got VK_TAB" every time tab is pressed.
If ES_MULTILINE is present, a tab is inserted into the text (desired behavior).
If ES_MULTILINE is removed, then nothing happens upon pressing tab (same as before).
Returning DLGC_WANTMESSAGE instead of merely DLGC_WANTTAB doesn't change anything.
Firstly, these observations clash with Raymond's article. As written before, that article suggests that I should get tab characters inserted into the text by default, without doing anything. That's not what happens.
Secondly, WM_GETDLGCODE does in fact work as advertised, we do get WM_KEYDOWN with VK_TAB. I painfully debugged through the disassembly, and found out that:
There are 2 different WNDPROC in the EDIT control, one for single line and one for multiline.
Upon receiving the WM_KEYDOWN with VK_TAB, the multiline version (MLWndProc iirc) eventually calls MLKeyDown. That function then sends a WM_NEXTDLGCTL message. This is the culprit:
...
765D6DEA push ebx
765D6DEB push 0Dh
765D6DED push 100h
765D6DF2 push esi
765D6DF3 jmp MLKeyDown+1B6h (765D6D4Bh)
765D6DF8 cmp edx,1
765D6DFB jne MLKeyDown+270h (765D6E05h)
765D6DFD push ecx
765D6DFE push 9
765D6E00 jmp MLKeyDown+3C0h (765D6F55h)
765D6E05 test dword ptr [edi+68h],40000h
765D6E0C je MLKeyDown+648h (765D71DDh)
765D6E12 xor eax,eax
765D6E14 cmp edx,2
765D6E17 push 0
765D6E19 sete al
765D6E1C push eax
765D6E1D push 28h ; WM_NEXTDLGCTL
765D6E1F push dword ptr [edi+58h]
765D6E22 call SendMessageW (7658BB20h)
So it seems that the EDIT control insists on this behavior.
Something is not right here though. I cannot possibly be the first person to have that problem, and, again, Raymond's article suggests that this should not be happening in the first place.
Lastly:
Using v6 of the Common Controls library (which is used to get a "modern" visual style [for very modest definitions of "modern"]) doesn't change anything:
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
Here is a repository with the entire project
if you want that multi-line edit control process VK_TAB as if it is not inside a dialog - need not pass WM_GETDLGCODE to edit control, but process it by self. so solution can be next -
on WM_INITDIALOG call
SetWindowSubclass(GetDlgItem(hwndDlg, IDC_EDIT1), sSubclassProc, 0, 0);
(of course in place IDC_EDIT1 your actual edit id)
and sSubclassProc can be very simply:
static LRESULT CALLBACK sSubclassProc(HWND hWnd, UINT uMsg, WPARAM wParam,
LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR /*dwRefData*/)
{
switch (uMsg)
{
case WM_GETDLGCODE:
return DLGC_WANTCHARS|DLGC_HASSETSEL|DLGC_WANTALLKEYS|DLGC_WANTARROWS;
case WM_NCDESTROY:
RemoveWindowSubclass(hWnd, sSubclassProc, uIdSubclass);
break;
}
return DefSubclassProc(hWnd, uMsg, wParam, lParam);
}
after this edit process VK_TAB key.
really it got VK_TAB (inside WM_KEYDOWN and WM_CHAR) in any case. but how process this - depend from some internal flag. it can insert tab-stop positions xor send WM_NEXTDLGCTL message to parent. this flag (you view it in assembly code - this is test dword ptr [edi+68h],40000h line is set during handle WM_GETDLGCODE message (dialog send this message to controls when process WM_ACTIVATE)
so your error was in line
return OriginalEditWndProc(hWnd, message, wParam, lParam) | DLGC_WANTTAB ;
you call OriginalEditWndProc and it set flag (40000 in [this+68h])
I'm learning Win32 programming
I used LoadImage(...) to set the small icon for the window but it doesn't seem to be working and I cannot pinpoint the problem
void AddIcons(HWND hw)
{
HICON hi = LoadImage(NULL, "ICON.bmp", IMAGE_BITMAP, 16, 16, LR_LOADFROMFILE);
printf("Icon initialized\n");
if(hi)
{
printf("%x\n", hi);
SendMessage(hw, WM_SETICON, ICON_SMALL, (LPARAM)hi);
}
}
And the windows procedure:
LRESULT CALLBACK WndProc(HWND handle, UINT message, WPARAM wParam, LPARAM lParam)
{
switch(message)
{
case WM_SETICON: printf("REQUEST RECEIVED\n");
}
.
. // AddIcons() is called here
. // DefWindowProc() handles the message at the end
}
I get all three print statements including REQUEST RECEIVED.
However, the icon is still the default. Where is the problem occuring?
I am aware that I can use keep a resource file and use LoadIcon(..) but I am more comfortable doing everything programatically. Which begs a second question:
Can everything that can be done using resource(.rc) files be done programmatically?
If so, is one method inherently better than the other?
As the title says, I would like to move the window only when the user will drag it from a portion of the client area. This will be an imitation of the normal caption bar movement and it's because my form is custom and it doesn't have any title or caption bars. At the moment, I use the code as follows:
...
case WM_NCHITTEST:
return HTCAPTION;
and that works fine for making the user able to move the window no matter where he drags from. I would like to limit this possibility (only the top of the window will allow movement). I haven't tried checking the position of the mouse pressed because I don't know how to do it in the WM_NCHITTEST message.
I use plain Win32 (winapi) C code (no MFC or anything else at the moment) in Visual Studio 2015.
You will run into trouble if you just return HTCAPTION in response to all WM_NCHITTEST messages. You will break things like scrollbars, close buttons, resizing borders, etc. that are all implemented via different HT* values.
You have the right idea, though. You want to make the client area of your window draggable, so you need to trick Windows into thinking that your client area is actually the caption area (which, as you know, is draggable). That code looks like this:
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// ...
case WM_NCHITTEST:
{
// Call the default window procedure for default handling.
const LRESULT result = ::DefWindowProc(hWnd, uMsg, wParam, lParam);
// You want to change HTCLIENT into HTCAPTION.
// Everything else should be left alone.
return (result == HTCLIENT) ? HTCAPTION : result;
}
// ...
}
However, based on the image in your question, you appear to want to restrict this to only a certain region of your window. You will need to define exactly what that area is, and then hit-test to see if the user has clicked in that area. Assuming that rcDraggable is a RECT structure that contains the bounds of the red box shown in your image (in screen coordinates), you can use the following code:
static RECT rcDraggable = ...
LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
// ...
case WM_NCHITTEST:
{
// Call the default window procedure for default handling.
const LRESULT result = ::DefWindowProc(hWnd, uMsg, wParam, lParam);
// Get the location of the mouse click, which is packed into lParam.
POINT pt;
pt.x = GET_X_LPARAM(lParam);
pt.y = GET_Y_LPARAM(lParam);
// You want to change HTCLIENT into HTCAPTION for a certain rectangle, rcDraggable.
// Everything else should be left alone.
if ((result == HTCLIENT) && (PtInRect(&rcDraggable, pt))
{
return HTCAPTION;
}
return result;
}
// ...
}
If you define rcDraggable in terms of client coordinates, you will need to convert it to screen coordinates before doing the hit-testing in response to WM_NCHITTEST. To do that, call the MapWindowPoints function, like so:
RECT rc = rcDraggable;
MapWindowPoints(hWnd, /* a handle to your window */
NULL, /* convert to screen coordinates */
reinterpret_cast<POINT*>(&rc),
(sizeof(RECT) / sizeof(POINT)));
You can call some magic code in WM_LBUTTONDOWN handler, AFAIR this:
ReleaseCapture();
SendMessage(yourWindowHandle, WM_SYSCOMMAND, 0xf012, 0) ;
I used this method a few years ago in Delphi and Windows XP. I think it must be similar for c++. Of course, you can check x and y before doing this.
First of all, sorry for my ignorance of the window creation process. Today is actually the first day of my experimenting with it.
I started to code a text based game a few days ago and I have the main menu, and 3 or 4 different functions that control various things with text. I was then advised to look into Windows API and create a window for the program. I have created the window which can be seen here:
#include <Windows.h>
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PWSTR nCmdLine, int nCmdShow)
{
const wchar_t CLASS_NAME[] = L"WindowClass";
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.lpszClassName = CLASS_NAME;
wc.hInstance = hInstance;
RegisterClass(&wc);
HWND hwnd = CreateWindowEx( //This creats a new instance of a window
0,
CLASS_NAME,
L"MyFirstWindow",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
500,
500,
NULL,
NULL,
hInstance,
NULL);
if(hwnd == 0)
return 0;
ShowWindow(hwnd,nCmdShow);
nCmdShow = 1;
MSG msg = { };
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_DESTROY:PostQuitMessage(0); return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd,&ps);
FillRect(hdc,&ps.rcPaint,(HBRUSH)(COLOR_WINDOW+5));
EndPaint(hwnd, &ps);
}return 0;
case WM_CLOSE:
{
if(MessageBox(hwnd,L"Do you want to exit?",L"Exit",MB_OKCANCEL)==IDOK)
DestroyWindow(hwnd);
} return 0;
}
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
This looks a bit messy, but you probably will not need it anyway.
So at this point I have my original program and this program that creates a window. My question is how, or even where, do I put my original program's code so that it can be incorporated into the window.
If you are reading this and thinking I'm a total moron for doing it this way, I'm open to ideas that are a lot simpler than what I'm doing right now.
Your code is the standard boilerplate for creating a window using c and win32 API functions. I recommend that you modify the message pump (it's the while loop in middle calling GetMessage). Instead do this:
Run an infinite loop
Peek a message
If the message is not there, execute your code
Else process messages including the quit message
Here's what the code should look like:
while (1)
{
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
//Your game code
}
}
I also want to point, that while learning game programming using C and calling Win32 API is a worthy goal, you might want to look at XNA game studio.
The reason I am recommending it is because it is easier to learn and you can make much more interesting games faster. Here are a few links to get you started if you are interested.
http://joshua-w-wise78.livejournal.com/
http://www.krissteele.net/blogdetails.aspx?id=72
http://www.codeproject.com/KB/game/xna1.aspx
http://msdn.microsoft.com/en-us/library/bb203894.aspx
If your original program was a console app, that read input and printed output, then you will probably want to get input from your window to implement your game.
Instead of looking at it from the perspective of read user input from stdin then generate output to stdout, you have to think of it from the view of window messaging. So you need to process the WM_KEYDOWN messages, you can then use DrawText() to show the user input in your client area, or you could use a c++ RichEdit control. Once you process the WM_KEYDOWN messages you know what the user has pressed and then your program can do it's thing (maybe being triggered to process an accumalated buffer of characters whenever the WM_KEYDOWN key is equal to the enter key?) and write the output to your client area using DrawText() or send WM_KEYDOWN messages to your richedit window using SendMessage().
I think this is what you meant by a text based game, anyway, you just have to start thinking of doing everything by monitoring windows messages. Anything that the user does to your window, Windows will send a message to it to let it know.
Currently I am detecting the x and y position of a mouse click, storing it in a Point and displaying it through the message box.
I want to be able to read if another keyboard key is being held down such as the Shift or Control button.
Looking on MSDN I found the following information:
wParam Indicates whether various
virtual keys are down. This parameter
can be one or more of the following
values.
MK_CONTROL The CTRL key is down.
MK_MBUTTON The middle mouse button is
down.
MK_RBUTTON The right mouse button is
down.
MK_SHIFT The SHIFT key is down.
MK_XBUTTON1 Windows 2000/XP: The first
X button is down.
MK_XBUTTON2 Windows 2000/XP: The
second X button is down.
The problem I am having is I'm unsure as to how to store the results from wParam for each parameter and use them like I have to display them through the message box.
Here is my progress so far:
LRESULT CALLBACK WindowFunc(HWND hMainWindow, UINT message,
WPARAM wParam, LPARAM lParam)
{
POINTS mouseXY;
WCHAR buffer[256];
// Act on current message
switch(message)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_LBUTTONUP:
// Get mouse x, y
mouseXY = MAKEPOINTS(lParam);
// Output the co-ordinates
swprintf(buffer, 255, L"x = %d, y = %d", mouseXY.x, mouseXY.y);
MessageBox(0, buffer, L"Mouse Position", MB_OK);
break;
default:
return DefWindowProc(hMainWindow, message, wParam, lParam);
}
return 0;
}
Thanks for the help
The different virtual keys are ORed together in wParam. To check for single values, you have to AND them out (think basic bit operations).
Example:
swprintf(buffer, 255, L"x = %d, y = %d, Shift = %s, Ctrl = %s",
mouseXY.x, mouseXY.y,
wParam & MK_SHIFT ? L"yes" : L"no",
wParam & MK_CONTROL ? L"yes" : L"no");
You can use GetAsyncKeyState to find out the state of the most of the buttons:
SHORT lshift = GetAsyncKeyState(VK_LSHIFT);
SHORT rshift = GetAsyncKeyState(VK_RSHIFT);
// etc...
Here is a description of the difference between GetKeyState and GetAsyncKeyState.
You can also use GetKeyboardState:
BYTE keyboardState[256];
GetKeyboardState(keyboardState);