Translating WM_MOUSEWHEEL Delphi code to C++ Builder - c++

I have these links with code:
WMMouseWheel not working in Delphi
How to disable MouseWheel if mouse is not over VirtualTreeView (TVirtualStringTree)
Translated it to C++ Builder but it doesn't work:
UPDATE: After narrowing the problem down it appears that WM_MOUSEWHEEL messages don't work over unfocused TVirtualStringTree control only, they work over other controls. When focus is on e.g. TMemo control, other TMemo control scrolls on wheel but not TVirtualStringTree control. When focus is on TVirtualStringTree it scrolls TVirtualStringTree but not other controls. So the problem is now specific to TVirtualStringTree only.
void __fastcall TForm1::ApplicationEventsMessage(tagMSG &Msg, bool &Handled)
{
TPoint Pt;
HWND Wnd;
if (Msg.message == WM_MOUSEWHEEL ||
Msg.message == WM_VSCROLL ||
Msg.message == WM_HSCROLL)
{
if (GetCursorPos(&Pt))
{
Wnd = WindowFromPoint(Pt);
// It must be a VCL control otherwise we could get access violations
if (IsWindowEnabled(Wnd) && FindControl(Wnd) != NULL)
{
Msg.hwnd = Wnd; // change the message receiver to the control under the cursor
}
}
}
}
Different version of the similar code, also doesn't work:
TPoint pnt;
TWinControl *ctrl;
if ((Msg.message == WM_MOUSEWHEEL ||
Msg.message == WM_VSCROLL ||
Msg.message == WM_HSCROLL) &&
GetCursorPos(&pnt))
{
ctrl = FindVCLWindow(pnt);
if (ctrl != NULL)
{
SendMessage(ctrl->Handle, Msg.message, Msg.wParam, Msg.lParam); // No effect
// SendMessage(ctrl->Handle, WM_VSCROLL, 1, 0); // This is the only thing that actually moves scrollbars but this is not exactly the same message like above
// Msg.hwnd = ctrl->Handle; // No effect
this->Caption=ctrl->Name; // This shows correct control name so the message IS GETTING THROUGH!
Handled = true;
}
}
It should work but it doesn't. Tried other code as well. No effect - mouse wheel does not operate on unfocused control. As you can see, I checked for all 3 variants of wheel messages, it gets correct control under the mouse, it shows that control name but the control doesn't receive wheel messages.
Any ideas what piece of the puzzle am I missing to get it to work?

As nobody offered any proper solution, I am posting my own. The solution is not perfect but at least it does what it needs to do - mouse wheel scrolls all controls under it, including the VirtualTreeView controls. The code in solution is in C++ but Delphi version is very similar (it only needs to be translated).
My current solution is to grab WM_MOUSEWHEEL events and translate them into WM_VSCROLL or WM_HSCROLL to which VirtualTreeView reacts and scrolls the content. Additionally, it needs to take into account high-precision mouse wheels which can have smaller value than WHEEL_DELTA (which is set to 120). Finally, it needs to take into account user setting for number of lines to scroll (set in Control Panel in Windows). So here goes:
Put a TApplicationEvents to a form and in the OnMessage event do this:
void __fastcall TFormMain::ApplicationEventsMessage(tagMSG &Msg, bool &Handled)
{
// Check these 3 messages because some mouse drivers may use VSCROLL instead of MOUSESWHEEL message
if (Msg.message == WM_MOUSEWHEEL || Msg.message == WM_VSCROLL || Msg.message == WM_HSCROLL)
{
TPoint pnt;
TWinControl *ctrl;
if (!GetCursorPos(&pnt)) return;
ctrl = FindVCLWindow(pnt);
if (ctrl != NULL)
{
// ToDo: implement if user needs wheel-click - then we also need KEYSTATE but for this example it is not needed
// int fwKeys = GET_KEYSTATE_WPARAM(Msg.wParam);
int zDelta = GET_WHEEL_DELTA_WPARAM(Msg.wParam),
pvParam = 3; // Windows default value
unsigned MyMsg = WM_VSCROLL;
// ToDo: extract SystemParametersInfo somewhere else so it is not extracted for each WM_MOUSEWHEEL message which may not be needed
switch (Msg.message)
{
// This will translate WM_MOUSEWHEEL into WM_VSCROLL
case WM_MOUSEWHEEL:
case WM_VSCROLL:
// Windows setting which determines how many lines to scroll - we'll send that many WM_VSCROLL or WM_HSCROLL messages
SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &pvParam, 0);
MyMsg = WM_VSCROLL;
break;
case WM_HSCROLL:
// Same as above but for WM_HSCROLL (horizontal wheel)
SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &pvParam, 0);
MyMsg = WM_HSCROLL;
break;
}
// This calculation takes into account high-precision wheels with delta smaller than 120
// Possible TODO: Round up values smaller than 1 (e.g. 0.75 * pvParam) if pvParam is 1
int ScrollBy = ((double)zDelta / (double)WHEEL_DELTA) * pvParam;
// Send multiple messages based on how much the zDelta value was
if (zDelta > 0)
{
do
{
SendMessage(ctrl->Handle, MyMsg, SB_LINEUP, 0);
}
while (--ScrollBy > 0);
}
else
{
do
{
SendMessage(ctrl->Handle, MyMsg, SB_LINEDOWN, 0);
}
while (++ScrollBy < 0);
}
Handled = true;
}
}
}

Related

Windows api programming-How to send/post messages to an application window to call up the menu items?

The problem
I have been working on a Windows cloud desktop project this week. One feature requires the server side can response to the users' inputs (mouse, keyboard...) from the client. I post the input messages (e.g., WM_LBUTTONDOWN, WM_KEYDOWN...) from the client to the specific application window in the server. Everything works fine when inputs target is the client area of an application window. However, the menu bar's item ("File" in notepad.exe, for example) does not response to the mouse clicking events. Here list part of my codes:
struct MouseMsg {
UINT msg;
WPARAM wParam;
LPARAM lParam;
};
enum class MouseEvent : unsigned int {
DOWN = 0,
UP,
MOVE,
WHEEL
};
struct MouseInputData
{
int32_t button;
int32_t wheel;
int32_t px;
int32_t py;
};
void ConstructMouseClickMsg(MouseMsg& mouseMsg, MouseInputData* mData, MouseEvent motion)
{
mouseMsg.lParam = MAKELPARAM(mData->px, mData->py);
switch (mData->button)
{
case 0:
{
mouseMsg.wParam = MK_LBUTTON;
mouseMsg.msg = (motion == MouseEvent::DOWN) ? WM_LBUTTONDOWN : WM_LBUTTONUP;
break;
}
case 1:
{
mouseMsg.wParam = MK_RBUTTON;
mouseMsg.msg = (motion == MouseEvent::DOWN) ? WM_RBUTTONDOWN : WM_RBUTTONUP;
break;
}
case 2:
{
mouseMsg.wParam = MK_MBUTTON;
mouseMsg.msg = (motion == MouseEvent::DOWN) ? WM_MBUTTONDOWN : WM_MBUTTONUP;
break;
}
default:
LOG->warn("Unknown mouse button types");
break;
}
}
void OnMouseClick(MouseInputData* mData, MouseEvent motion)
{
HWND mTargetHwnd = GetInputWindow(); // Omit details.
// This function can get the target window's handle
// and can tell if the window is client or menu (parent)
if (!mTargetHwnd)
{
LOG->warn("Null window");
return;
}
// construct mouse clicking messages
MouseMsg mouseMsg;
ConstructMouseClickMsg(mouseMsg, mData->button, motion);
if (mIsClientArea) // in client area or the menu bar? set in GetInputWindow()
{
PostMessageA(mTargetHwnd, mouseMsg.msg, mouseMsg.wParam, mouseMsg.lParam);
}
else
{
// How to ???
}
}
What I have tried
I used spy++ to monitor what messages a window received when the menu bar was clicked (as lines 1296~1327 in the following picture shows). WM_NCHITTEST, WM_NCLBUTTONDOWN, WM_SYSCOMMAND seemed to be the solution. I tried post all these messages but no response either.
Have-a-try codes:
if (mIsClientArea) // in client area or the menu bar? set in GetInputWindow()
{
PostMessageA(mTargetHwnd, mouseMsg.msg, mouseMsg.wParam, mouseMsg.lParam);
}
else
{
// How to ???
LOG->info("try to call up menu");
if (motion == MouseEvent::DOWN)
{
PostMessageA(mTargetHwnd, WM_NCLBUTTONDOWN, HTMENU, mouseMsg.lParam);
//PostMessageA(mCurrentHwnd, WM_SYSCOMMAND, SC_MOUSEMENU | 0x0005, mouseMsg.lParam);
}
else
{
PostMessageA(mTargetHwnd, WM_NCLBUTTONUP, HTMENU, mouseMsg.lParam);
}
}
Help!!!
Are there any specialist on Windows system can give me some hints please? Thanks sincerely!

PostMessage not clicking buttons

I've played with PostMessage just clicking different tabs which seemed to work. But I'm trying to automate some button clicks and when running this function it highlights the button as if I was hovering over it but doesn't click.
I thought somehow the button changing of colour made the boolean false so I added the exception of the buttons colour whilst it's hovered. Made no difference, and I do not wish to use SetCursorPos & simulate a mouseclick using SendInput. I wish to understand the problem/issue I'm having as to why it's not clicking.
void click(const std::vector<uint_16>& x, const uint_16& y)
{
for(uint_8 i = 0; i < 5; i++)
{
if(content::MyClass().firstMatch(GetPixel(hdc, x[i], y)))
{
PostMessage(hwnd, WM_LBUTTONDOWN, 0, MAKELPARAM(x[i], y));
return;
}
}
if(content::MyClass().secondMatch(GetPixel(hdc, x[4], y)))
{
PostMessage(hwnd, WM_LBUTTONDOWN, 0, MAKELPARAM(x[4], y));
}
}
The solution you are using is unreliable because you are short-circuiting the input system on the window and not specifically targeting which button you are trying to press.
As for the reason your code is not currently working, you only send a WM_LBUTTONDOWN message to the window. Since most buttons work off a combination of WM_LBUTTONDOWN and WM_LBUTTONUP your program isn't causing the buttons click method to activate.
Adding PostMessage(hwnd, WM_LBUTTONUP, 0, MAKELPARAM(x[i], y)); after the mouse down will cause the button click to register.
In future as a more reliable solution that will specifically target a button on the window and click it you may want to look at the BM_CLICK PostMessage argument. Using this instead of trying to emulate a mouse click is more correct because windows will trigger events that may otherwise be forgotten when using the mouse down and mouse up post commands.
An example:
int retVal = 0;
HANDLE hwndDialog;
HANDLE hwndButton;
/* First, see if the dialog box (titled "Inactivity Warning" ) is currently open. */
hwndDialog = FindWindow( 0, "Inactivity Warning" );
if ( hwndDialog == 0 ) return;
/* Now get a handle to the "Resume" button in the dialog. */
hwndButton = FindWindowEx( hwndDialog, 0, 0, "Resume" );
/* After making sure that the dialog box is the active window, click "Resume". */
retval = SetActiveWindow( hwndDialog );
/* converted from SendMessage. */
retval = PostMessage( hwndButton, BM_CLICK, 0, 0 );
Source found Here, Converted from VB by me.
For some further reading on the input system Here is a good article.
A Blog Post by Raymond Chen goes into a bit of detail about these commands and their caveats as well.

Detecting Enter/Return on Keydown event in C++

I am trying to detect in my application, if the Enter/Return buttons are pressed. My problem is that the LVN_KEYDOWN event (Indicates that a key has been pressed) does not detect the Enter/Return key.
I have seen similar questions for other languages, but can not find a solution for C++.
My event to read the key press is:
void ListOption::OnLvnKeydownList1(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMLVKEYDOWN pLVKeyDow = reinterpret_cast<LPNMLVKEYDOWN>(pNMHDR);
// TODO: Add your control notification handler code here
if(pLVKeyDow->wVKey == VK_RETURN)
{
OnItemActivateList1(pNMHDR, pResult);
*pResult = 1;
}
*pResult = 0;
}
This code works for almost any key, execept for the Enter key.
My dialog has only one button, and it's "Default Button" value is FALSE. How is it possible to detect the keypress?
Update: My application uses modal dialogs.. It contains a CImageSheet that contains CImagePages(tabs). Here is an image to explain better (I have placed grey blocks to hide some private data).
When I press Enter, I wish to open a new dialog to change the option. Currently this is done with the LVN_ITEMCTIVATE event (when the user double clicks an item):
You can override PreTranslateMessage in the window which owns the ListView. In this case it seems to be a CPropertyPage.
BOOL CMyPropertyPage::PreTranslateMessage(MSG* pMsg)
{
//optional: you can handle keys only when ListView has focus
if (GetFocus() == &List)
if (pMsg->message == WM_KEYDOWN)
{
if (pMsg->wParam == VK_RETURN)
{
//return 1 to eat the message, or allow for default processing
int sel = List.GetNextItem(-1, LVNI_SELECTED);
if (sel >= 0)
{
MessageBox("VK_RETURN");
TRACE("ListView_GetNextItem %d\n", sel);
return 1;
}
else
TRACE("ListView_GetNextItem not-selected, %d\n", sel);
}
if (pMsg->wParam == VK_ESCAPE)
{
//do nothing!
}
}
return CPropertyPage::PreTranslateMessage(pMsg);
}

C++ window draggable by its menu bar

So I'm using Visual C++, and I have created a draggable, borderless window. Anyway, there is a toolbar along the top, and i want to be able to drag the window by that toolbar. I still want the toolbar to be functional, but i have no earthly idea how to be able to drag the window by it. This is my current window (see the toolbar on the top):
And this is my current code to make it draggable:
case WM_NCHITTEST: {
LRESULT hit = DefWindowProc(hWnd, message, wParam, lParam);
if(hit == HTCLIENT) hit = HTCAPTION;
return hit;
}
break;
You are on the right track with hooking WM_NCHITTEST. Now, you need to make change what constitutes a client hit versus a caption hit. If I understand your code right now, anywhere you click within the client area of the window (everything but the border) will allow you to drag the window elsewhere. This will make interacting with your application very difficult. Instead, you should be returning HTCAPTION only after you have determined that the hit was within the menubar area. Specifically, the area of the menubar that does not hold the File/Edit/Help buttons.
case WM_NCHITTEST: {
LRESULT hit = DefWindowProc(hWnd, message, wParam, lParam);
if (hit == HTCLIENT) { // The hit was somewhere in the client area. Don't know where yet.
// Perform your test for whether the hit was in the region you would like to intercept as a move and set hit only when it is.
// You will have to pay particular attention to whether the user is actually clicking on File/Edit/Help and take care not to intercept this case.
// hit = HTCAPTION;
}
return hit;
break;
}
Some things to keep in mind here:
This can be very confusing to a user that wants to minimize, close, or move your application. Menubars do not convey to the user that you can move the window by dragging them.
If you are concerned with vertical pixels you may consider doing what other applications on Windows are starting to do -- moving the menubar functionality to a single button that is drawn in the titlebar. (See recent versions of Firefox/Opera or Windows explorer in Windows 8 for some idea to move things to the titlebar.
In one of my applications I also wanted to make the window what I call "client area draggable". Unfortunately the mentioned solution (replacing HTCLIENT with HTCAPTION)
does have a serious flaws:
Double-clicking in the client area now shows the same behaviour as
double-clicking the caption (i.e. minimizing/maximizing the window)!
To solve this I did the following in my message handler (excerpt):
case WM_MOUSEMOVE:
// Move window if we are dragging it
if (mIsDragging) // variable: bool mIsDragging;
{
POINT mousePos = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
mIsDragging = (ClientToScreen(hWnd, &mousePos) &&
SetWindowPos(hWnd,
NULL,
mDragOrigin.left + mousePos.x - mDragPos.x,
mDragOrigin.top + mousePos.y - mDragPos.y,
0,
0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE));
}
break;
case WM_LBUTTONDOWN:
// Check if we are dragging and safe current cursor position in case
if (wParam == MK_LBUTTON)
{
POINT mousePos = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)};
if (ClientToScreen(hWnd, &mousePos) &&
DragDetect(hWnd, mousePos))
{
// Check if the cursor is pointing to your new caption here!!!!
mIsDragging = true;
mDragPos = mousePos;
GetWindowRect(hWnd, &mDragOrigin);
SetCapture(hWnd);
}
}
break;
// Remove this case when ESC key handling not necessary
case WM_KEYDOWN:
// Restore original window position if ESC is pressed and dragging active
if (!mIsDragging || wParam != VK_ESCAPE)
{
break;
}
// ESC key AND dragging... we restore original position of window
// and fall through to WM_LBUTTONUP as if mouse button was released
// (i.o.w. NO break;)
SetWindowPos(hWnd, NULL, mDragOrigin.left, mDragOrigin.top, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
case WM_LBUTTONUP:
ReleaseCapture();
break;
case WM_CAPTURECHANGED:
mIsDragging = false;
break;
The (pseudo) code omits the return values (default: 0) and variable definitions but
should make the procedure clear anyway!? (If not drop me a line and I'll add more
or all code).
ps: I just found another comprehensive description which also explains the differences
of these two solutions: http://tinyurl.com/bqtyt3q

PostMessage() succeeds but my message processing code never receives the message

In my C++ application's GUI object I have the following in the main window procedure:
case WM_SIZE:
{
OutputDebugString(L"WM_SIZE received.\n");
RECT rect = {0};
GetWindowRect(hwnd, &rect);
if (!PostMessage(0, GUI_MSG_SIZECHANGED, w, MAKELONG(rect.bottom - rect.top, rect.right - rect.left))) {
OutputDebugString(L"PostMessage failed.\n"); // <--- never called
}
}
return 0; // break;
The GUI object also has the following getMessage() method:
int GUI::getMessage(MSG & msg) {
BOOL result = 0;
while ((result = GetMessage(&msg, 0, 0, 0)) > 0) {
if (msg.message > (GUI_MSG_BASE-1) && msg.message < (GUI_MSG_LAST+1)) {
OutputDebugString(L"GUI message received.\n");
break;
}
else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return result;
}
The application object calls this method in the following way:
while ((result = _gui.getMessage(msg)) > 0) {
switch (msg.message) {
// TODO: Add gui message handlers
case GUI_MSG_SIZECHANGED:
OutputDebugString(L"GUI_MSG_SIZECHANGED received.\n");
_cfg.setWndWidth(HIWORD(msg.lParam));
_cfg.setWndHeight(LOWORD(msg.lParam));
if (msg.wParam == SIZE_MAXIMIZED)
_cfg.setWndShow(SW_MAXIMIZE);
else if (msg.wParam == SIZE_MINIMIZED)
_cfg.setWndShow(SW_MINIMIZE);
else if (msg.wParam == SIZE_RESTORED)
_cfg.setWndShow(SW_SHOWNORMAL);
break;
}
}
The application object is interested in the window size because it stores this information in a configuration file.
When I run this in Visual Studio's debugger, the output window looks like this after resizing the window:
WM_SIZE received.
GUI message received.
GUI_MSG_SIZECHANGED received.
WM_SIZE received.
WM_SIZE received.
WM_SIZE received.
WM_SIZE received.
...etc...
The PostMessage() function never fails, but seems to only send GUI_MSG_SIZECHANGED (#defined as WM_APP + 0x000d) the first time WM_SIZE is handled, which is right after handling WM_CREATE.
I have no idea what could be causing this. I tried using SendMessage and PostThreadMessage but the result is the same. Also read through MSDN's message handling documentation but couldn't find what's wrong with my code.
Could anyone help?
Hacking a custom message loop is something you'll live to regret some day. You hit it early.
Don't post messages with a NULL window handle, they can only work if you can guarantee that your program only ever pumps your custom message loop. You cannot make such a guarantee. These messages fall into the bit bucket as soon as you start a dialog or Windows decides to pump a message loop itself. Which is the case when the user resizes a window, the resize logic is modal. Windows pumps its own message loop, WM_ENTERSIZEMOVE announces it. This is also the reason that PostThreadMessage is evil if the thread is capable of displaying any window. Even a MessageBox is fatal. DispatchMessage cannot deliver the message.
Create a hidden window that acts as the controller. Now you can detect GUI_MSG_SIZECHANGED in its window procedure and no hacks to the message loop are necessary. That controller is not infrequently the main window of your app btw.