我写了一个函数,它将带有一个控件和一个文件目标,并保存控件覆盖的表格区域。
我的问题是,当我从外接显示器移动到笔记本电脑的主屏幕时,捕获区域的移动量不一致。我终于弄清楚应归咎于扩展(DPI)。当我将其降低到100%(96 DPI)时,它可以在笔记本电脑的屏幕上工作。所有其他屏幕均已设置为100%。回到125%,这只是笔记本电脑屏幕上的问题。我如何允许125%?
在笔记本电脑的屏幕上,表格越靠近屏幕左上方,图像的位置越准确。在任何屏幕上生成的图像大小都是相同的,只是位置在笔记本电脑屏幕上会发生变化。另外,当我从外接显示器切换到笔记本电脑显示器时,该表格的大小也会随之调整。调整大小后,才出现此问题。
private void capture(Control ctrl, string fileName)
{
Rectangle bounds = ctrl.Bounds;
Point pt = ctrl.PointToScreen(bounds.Location);
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(new Point(pt.X - ctrl.Location.X, pt.Y - ctrl.Location.Y), Point.Empty, bounds.Size);
}
string filetype = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
switch (filetype)
{
case ".png":
bitmap.Save(fileName, ImageFormat.Png);
break;
case ".jpeg":
bitmap.Save(fileName, ImageFormat.Jpeg);
break;
case ".bmp":
bitmap.Save(fileName, ImageFormat.Bmp);
break;
default:
break;
}
}
答案 0 :(得分:0)
我不确定您如何用当前代码复制屏幕的正确部分。 Bounds()属性返回相对于 PARENT 控件的矩形,但是您是在要求控件本身(而不是父级)转换为屏幕坐标:
获取或设置控件的大小和位置,包括控件的大小和位置 相对于父控件的非客户端元素(以像素为单位)。
我希望看到更多类似的东西:
:
不过,我不知道在不同的缩放模式下能否正常工作。
答案 1 :(得分:-1)
我找不到解决方法。我更改了方法,并在窗体上使用了DrawToBitmap,然后从控件位置制作了图像。我必须考虑一个固定的偏移量。我认为这与顶部栏包含在表单的位图中,而不包含在表单中控件的位置有关。
要考虑的一件事是DrawToBitmap以相反的堆栈顺序绘制。如果您有重叠对象,则可能需要颠倒DrawToBitmap的顺序。
private void capture(Control ctrl, string fileName)
{
Bitmap bitmapForm = new Bitmap(this.Width, this.Height);
this.DrawToBitmap(bitmapForm, new Rectangle(0, 0, this.Width, this.Height));
Rectangle myControlRect = new Rectangle(ctrl.Location,ctrl.Size);
//Correct for boarder around form
myControlRect.Offset(8,31);
Bitmap bitmap = bitmapForm.Clone(myControlRect, PixelFormat.DontCare);
string filetype = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
switch (filetype)
{
case ".png":
bitmap.Save(fileName, ImageFormat.Png);
break;
case ".jpeg":
bitmap.Save(fileName, ImageFormat.Jpeg);
break;
case ".bmp":
bitmap.Save(fileName, ImageFormat.Bmp);
break;
default:
break;
}
}