Get DeviceContext of Entire Screen with Multiple Montiors

时光总嘲笑我的痴心妄想 提交于 2019-12-07 14:31:17

问题


I need to draw a line (with the mouse) over everything with C#. I can get a Graphics object of the desktop window by using P/Invoke:

DesktopGraphics = Graphics.FromHdc(GetDC(IntPtr.Zero));

However, anything I draw using this graphics object is only showing on the left monitor, and nothing on the right monitor. It doesn't fail or anything, it just doesn't show.

After I create the Graphics object, it shows the visible clip region to be 1680 x 1050 which is the resolution of my left monitor. I can only assume that it's only getting a device context for the left monitor. Is their a way to get the device context for both (or any number) monitors?


EDIT 3/7/2009: Additional information about the fix I used.

I used the fix provided by colithium to come up with the following code for creating a graphics object for each monitor as well as a way to store the offset so that I can translate global mouse points to valid points on the graphics surface.

private void InitializeGraphics()
{
    // Create graphics for each display using compatibility mode
    CompatibilitySurfaces = Screen.AllScreens.Select(s => new CompatibilitySurface()
        {
            SurfaceGraphics = Graphics.FromHdc(CreateDC(null, s.DeviceName, null, IntPtr.Zero)),
            Offset = new Size(s.Bounds.Location)
        }).ToArray();
}

private class CompatibilitySurface : IDisposable
{
    public Graphics SurfaceGraphics = null;
    public Size Offset = default(Size);

    public PointF[] OffsetPoints(PointF[] Points)
    {
        return Points.Select(p => PointF.Subtract(p, Offset)).ToArray();
    }

    public void Dispose()
    {
        if (SurfaceGraphics != null)
            SurfaceGraphics.Dispose();
    }
}

[DllImport("gdi32.dll")]
static extern IntPtr CreateDC(string lpszDriver, string lpszDevice, string lpszOutput, IntPtr lpInitData);

回答1:


Here is a link to another person that had the same problem. It was solved with a call to:

CreateDC(TEXT("DISPLAY"),NULL,NULL,NULL)

which will return a DC to all monitors.




回答2:


Following URL to get EnumDisplayMonitor may solve your problem

MSDN

To retrieve information about all of the display monitors, use code like this:

EnumDisplayMonitors(NULL, NULL, MyInfoEnumProc, 0); One more URL given at MSJ



来源:https://stackoverflow.com/questions/576476/get-devicecontext-of-entire-screen-with-multiple-montiors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!