简体   繁体   English

如何获得Windows窗体相对于显示器的正确位置?

[英]How to get the correct position of a Windows Form relative to the display?

I have searched for hours and tried many things. 我已经搜索了几个小时,尝试了很多事情。

I have a transparent Windows Form and I am trying to capture the screen within the bounds of that form. 我有一个透明的Windows窗体,我正在尝试捕获该窗体范围内的屏幕。

For whatever reason, I am unable to get the correct form area... 无论出于什么原因,我都无法获得正确的表格区域...

[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr ptr);

[DllImport("user32.dll")]
public static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC);

private void LocationChanged(object sender, EventArgs e)
{
    var position = form.PointToScreen(Point.Empty);
    bounds = new Rectangle(position, new Size(50, 50));
    DrawRectangle(bounds);
}

void DrawRectangle(Rectangle rect)
{
    IntPtr desktopPtr = GetDC(IntPtr.Zero);
    Graphics g = Graphics.FromHdc(desktopPtr);

    SolidBrush b = new SolidBrush(Color.Green);
    g.FillRectangle(b, rect);

    g.Dispose();
    ReleaseDC(IntPtr.Zero, desktopPtr);
}

This is the result: 结果如下:

在此处输入图片说明

The green square should completely cover the form with the red border on the left. 绿色方块应完全覆盖表格,左侧带有红色边框。

I've tried different monitors, I've made sure scaling is 100% ( what to do if it is not? ), I'e tried passing the form.Location to form.PointToScreen 我尝试了其他监视器,确保缩放比例为100%( 如果不是该怎么办? ),我尝试将form.Location传递给form.PointToScreen

What am I doing wrong? 我究竟做错了什么?

You can try setting the property form.StartPosition = FormPosition.Manual 您可以尝试设置属性form.StartPosition = FormPosition.Manual

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.form.startposition?view=netframework-4.7.2 https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.form.startposition?view=netframework-4.7.2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM