0

I'm trying to know when a console window has moved so I created a new message-only window to get the messages of the console but I don't know if it is working because the message is apparently never being received.

#define WINVER 0x0501
#include <windows.h>
#include <iostream>

WNDPROC glpfnConsoleWindow; // NEW
using namespace std;

LRESULT APIENTRY MainWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_SIZE:
        cout<<"Window moved"<<endl;
        break;
        case WM_DESTROY:
        PostQuitMessage(0);
        break;
        default:
        // NEW
        return CallWindowProc(glpfnConsoleWindow, hwnd, uMsg, wParam, lParam);
        //return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    LPSTR lpCmdLine, int nCmdShow)
{
    HWND hwnd;
    MSG Msg;
    const char lpcszClassName[] = "messageClass";
    WNDCLASSEX  WindowClassEx;

    // == NEW
    HWND consHwnd;
    consHwnd = GetConsoleWindow();
    glpfnConsoleWindow = (WNDPROC)SetWindowLong(consHwnd, GWL_WNDPROC, (LONG)MainWndProc);
    // ==

    ZeroMemory(&WindowClassEx, sizeof(WNDCLASSEX));
    WindowClassEx.cbSize        = sizeof(WNDCLASSEX);
    WindowClassEx.lpfnWndProc   = MainWndProc;
    WindowClassEx.hInstance     = hInstance;
    WindowClassEx.lpszClassName = lpcszClassName;

    if (RegisterClassEx(&WindowClassEx) != 0)
    {
        // Create a message-only window
    hwnd = CreateWindowEx(0, lpcszClassName, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL);
        if (hwnd != NULL)
        cout<<"Window created"<<endl;
        else
        UnregisterClass(lpcszClassName, hInstance);
    }
    ShowWindow(hwnd,nCmdShow);
    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
     return (int)Msg.wParam;
}

1 Answers1

0

Perhaps you should process WM_MOVE, which, according to the documentation, is sent after the window has been moved. WM_SIZE is sent when the size changes.

I think your problem is that the WM_MOVE and WM_SIZE messages are going to the console window rather than to your hidden window.

I suspect you'll have to call GetConsoleWindow to get the console window handle, and then call SetWindowLong to attach your window proc to the console window. Be sure to pass messages on to the original window proc.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351