6

我要做的是使控件(在同一进程中,但我无法控制)重绘自身,并让我的代码阻塞,直到它完成重绘

我尝试使用UpdateWindow,但这似乎并没有等待重绘完成。

我需要等待它完成重绘的原因是我想在之后抓取屏幕。

该控件不是 dotNet 控件,而是常规的 windows 控件。

我已经确认:

  • 手柄是正确的。
  • UpdateWindow返回真。
  • 尝试InvalidateRect(hWnd, IntPtr.Zero, true)在调用之前发送UpdateWindow以确保窗口需要失效。
  • 尝试在控件的父窗口上做同样的事情。

使用的代码:

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool InvalidateRect(IntPtr hWnd, IntPtr rect, bool bErase);

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UpdateWindow(IntPtr hWnd);

public bool PaintWindow(IntPtr hWnd)
{
    InvalidateRect(hWnd, IntPtr.Zero, true);
    return UpdateWindow(hWnd);
}
//returns true
4

1 回答 1

1

您可以使用Application.DoEvents强制应用程序处理所有排队的消息(包括 WM_PAINT!)。像这样的东西:

public bool PaintWindow(IntPtr hWnd)
{
    InvalidateRect(hWnd, IntPtr.Zero, true);
    if (UpdateWindow(hWnd))
    {
        Application.DoEvents();
        return true;
    }

    return false;
}

WM_PRINT但如果你还是要抢屏,发消息一石两鸟不是更好吗?

您可以通过以下代码来完成:

internal static class NativeWinAPI
{
    [Flags]
    internal enum DrawingOptions
    {
        PRF_CHECKVISIBLE = 0x01,
        PRF_NONCLIENT = 0x02,
        PRF_CLIENT = 0x04,
        PRF_ERASEBKGND = 0x08,
        PRF_CHILDREN = 0x10,
        PRF_OWNED = 0x20
    }

    internal const int WM_PRINT = 0x0317;

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    internal static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg,
        IntPtr wParam, IntPtr lParam);
}

public static void TakeScreenshot(IntPtr hwnd, Graphics g)
{
    IntPtr hdc = IntPtr.Zero;
    try
    {
        hdc = g.GetHdc();

        NativeWinAPI.SendMessage(hwnd, NativeWinAPI.WM_PRINT, hdc,
            new IntPtr((int)(
                NativeWinAPI.DrawingOptions.PRF_CHILDREN |
                NativeWinAPI.DrawingOptions.PRF_CLIENT |
                NativeWinAPI.DrawingOptions.PRF_NONCLIENT |
                NativeWinAPI.DrawingOptions.PRF_OWNED
                ))
            );
    }
    finally
    {
        if (hdc != IntPtr.Zero)
            g.ReleaseHdc(hdc);
    }
}
于 2012-12-27T20:20:51.597 回答