同步Redraw窗口控制(使用阻止方法)



我要做的是引起控制(在同一过程中,但我无法控制)重新绘制本身,,让我的代码阻止直到它完成了重绘

我尝试使用UpdateWindow,但这似乎不等待重新绘制完成。

我需要等待它完成重新绘制的原因是我想在后面抓住屏幕。

控件不是dotnet控件,它是常规的窗口控制。

我已经确认:

  • 手柄是正确的。
  • UpdateWindow返回true。
  • 尝试在呼叫之前将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

您可以使用应用程序。这样的东西:

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);
    }
}

最新更新