MSPaint未接收通过PostCommand发送的命令

时间:2014-11-20 05:05:18

标签: c++ winapi window postmessage

我试图通过我的程序调用Paint并想要绘制一些东西

我所做的是 - 1.首先获取绘制窗口的句柄(我只生成了该过程),然后尝试将光标设置到中心并尝试获取该特定窗口的句柄,没有错误或警告,我已经检查了返回值和所有,但不知何故,事情没有被绘制..请参考代码

HWND    hWndPaint = NULL;
HWND    hTempWindow = NULL;


BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
{
    int     textLen = 0;
    PWSTR   pszMem;

    if (!hWnd)
        return TRUE;
    if (!::IsWindowVisible(hWnd))
        return TRUE;

    textLen = GetWindowTextLength(hWnd);
    pszMem = (PWSTR)VirtualAlloc(NULL, textLen + 1, MEM_COMMIT, PAGE_READWRITE);
    GetClassName(hWnd, pszMem, textLen + 1);
    if ((_wcsicmp(pszMem, L"MSPaintApp")) == 0)
    {
        hWndPaint = hWnd;
        return TRUE;
    }
    return TRUE;
}


HWND SpawnPaintAndGetDrawHandle()
{
    int width = 0, height = 0;

    ShellExecute(0, L"open", L"C:\\Windows\\System32\\mspaint.exe", NULL, NULL, SW_SHOWNORMAL);

    Sleep(1000);
    EnumWindows(EnumWindowsProc, NULL);
    if (hWndPaint)
        BOOL res = PostMessage(hWndPaint, WM_SYSCOMMAND, SC_MAXIMIZE, 0);

    RECT rect;
    if (GetWindowRect(hWndPaint, &rect))
    {
        width = rect.right - rect.left;
        height = rect.bottom - rect.top;

        SetCursorPos(width / 2, height / 2);
    }
    POINT   currentCusrsorPoint;
    currentCusrsorPoint.x = width / 2;
    currentCusrsorPoint.y = height / 2;
    return (ChildWindowFromPoint(hWndPaint, currentCusrsorPoint));

}

DWORD MakePosition(WORD x, WORD y)
{
    return ((DWORD)y << 16 | (DWORD)x);
}

int main()
{
    HWND hDrawArea = NULL;
    hDrawArea = SpawnPaintAndGetDrawHandle();

    if (hDrawArea == NULL)
    {
        std::cout << "Could not find the draw area.. something went wrong.";
        return 0;
    }

    // draw something on DarwArea
    int         pX = 0, pY = 0;
    BOOLEAN     bFirstPoint = true;

    for (double i = 0; i < 1; i += 0.1)
    {
        double radius = 10 * 2 * 3.14 * i;
        double x = cos(radius) * 100 * i;
        double y = sin(radius) * 100 * i;

        pX = (int)x + 300;
        pY = (int)y + 300;

        if (bFirstPoint)
        {
            bool res = PostMessage(hDrawArea, WM_LBUTTONDOWN, MK_LBUTTON, MakePosition(pX, pY));
            bFirstPoint = false;
        }
        PostMessage(hDrawArea, WM_MOUSEMOVE, MK_LBUTTON, MakePosition(pX, pY));
        PostMessage(hDrawArea, WM_MOUSEMOVE, MK_LBUTTON, MakePosition(pX, pY));
        Sleep(100);
    }

    PostMessage(hDrawArea, WM_LBUTTONUP, MK_LBUTTON, MakePosition(pX, pY));


    return 0;
}

1 个答案:

答案 0 :(得分:2)

问题在于return (ChildWindowFromPoint(hWndPaint, currentCusrsorPoint));

这个函数递归不起作用,我认为确实如此。这个函数返回的句柄不是我们实际绘制东西时应该接收点击的窗口。这个孩子是这个孩子的孩子,所以我需要自己解脱,直到我没有更多的孩子窗口,然后回到那个孩子的手柄

    do
    {
        curParent = ctrlParent;
        ctrlParent = ChildWindowFromPoint(curParent, currentCusrsorPoint);
    }while(ctrlParent != curParent);

这会给我一个窗口,它对点击消息起作用,并且能够生成&#34; draw&#34;结果