如何处理仅消息窗口以从控制台窗口获取消息?

时间:2013-05-18 20:04:03

标签: winapi console windows-console

我试图知道控制台窗口何时移动,所以我创建了一个新的仅消息窗口来获取控制台的消息,但我不知道它是否正常工作,因为消息显然从未被接收过。

#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 个答案:

答案 0 :(得分:0)

也许您应该处理WM_MOVE,根据文档,在窗口移动后发送。GetConsoleWindow。当大小改变时发送WM_SIZE。

我认为您的问题是WM_MOVEWM_SIZE消息将转到控制台窗口而不是隐藏窗口。

我怀疑您必须调用SetWindowLong来获取控制台窗口句柄,然后调用{{3}}将窗口proc附加到控制台窗口。务必将消息传递到原始窗口proc。