我有一个表单,其中有一个覆盖控件(透明的灰色背景,白色文本在“Drop here...”和一个图标上),只有在将文件拖到表单上时才可见。通过在其背面绘制控件,然后用透明灰色 (ARGB) 填充,可以使 Overlay 变得透明。该方法在 Overlay 应该位于不是 Form 的 Control 上时效果很好,但是当我Control.DrawToBitmap
用来呈现 Form 而不是通常的 Control 时,它也会呈现标题栏和边框。
1248 次
3 回答
2
Form.DrawToBitmap
绘制包括非客户区在内的整个表格。您可以使用BitBlt
. BitBlt 函数执行将对应于像素矩形的颜色数据从指定的源设备上下文到目标设备上下文的位块传输。
const int SRCCOPY = 0xCC0020;
[DllImport("gdi32.dll")]
static extern int BitBlt(IntPtr hdc, int x, int y, int cx, int cy,
IntPtr hdcSrc, int x1, int y1, int rop);
Image PrintClientRectangleToImage()
{
var bmp = new Bitmap(ClientSize.Width, ClientSize.Height);
using (var bmpGraphics = Graphics.FromImage(bmp))
{
var bmpDC = bmpGraphics.GetHdc();
using (Graphics formGraphics = Graphics.FromHwnd(this.Handle))
{
var formDC = formGraphics.GetHdc();
BitBlt(bmpDC, 0, 0, ClientSize.Width, ClientSize.Height, formDC, 0, 0, SRCCOPY);
formGraphics.ReleaseHdc(formDC);
}
bmpGraphics.ReleaseHdc(bmpDC);
}
return bmp;
}
于 2019-02-11T11:43:26.307 回答
1
Control.DrawToBitmap方法始终返回从控件左上角绘制的位图,即使您向该方法传递具有特定边界的 Rectangle 也是如此。
在这里,ClientRectangle
Form 的部分使用它的 Size 进行转换Bounds
。
请注意,如果您的应用程序不是 DPIAware,您可能会从所有返回 Point 或 Rectangle 的方法中得到错误的度量。包括非 DPIAware Windows API。
如果您需要保存生成的位图,请PNG
用作目标格式:它的无损压缩更适合这种渲染。
ClientAreaOnly
使用设置为的参数调用此方法以true
使其返回ClientArea
唯一的位图。
public Bitmap FormScreenShot(Form form, bool clientAreaOnly)
{
var fullSizeBitmap = new Bitmap(form.Width, form.Height, PixelFormat.Format32bppArgb);
// .Net 4.7+
fullSizeBitmap.SetResolution(form.DeviceDpi, form.DeviceDpi);
form.DrawToBitmap(fullSizeBitmap, new Rectangle(Point.Empty, form.Size));
if (!clientAreaOnly) return fullSizeBitmap;
Point p = form.PointToScreen(Point.Empty);
var clientRect =
new Rectangle(new Point(p.X - form.Bounds.X, p.Y - form.Bounds.Y), form.ClientSize);
var clientAreaBitmap = fullSizeBitmap.Clone(clientRect, PixelFormat.Format32bppArgb);
fullSizeBitmap.Dispose();
return clientAreaBitmap;
}
于 2019-02-11T11:49:12.913 回答
0
您可以渲染整个表单,然后只使用Bitmap.Clone()
. 在这里,您已经解释了如何做到这一点。
于 2019-02-11T11:07:23.343 回答