推荐如下代码: 窗体被遮挡也不影响,但是有一个bug 绘画显示在前面的控件在程序上界面上要设置到底层 (底层控件优先显示)
--效率高,稳如狗
TitleForm_Big titleForm= new TitleForm_Big();
//创建一个全局画布
Bitmap bmp = new Bitmap(1280, 720);
private void MainForm_Load(object sender, EventArgs e)
{
titleForm.Show();
titleForm.Location = new Point(0, -from.Size.Width);
}
private void TransferTimer_Tick(object sender, EventArgs e)
{
TransferTimer.Enabled = false;
try
{
//释放画布放置内存积累
bmp?.Dispose();
bmp = new Bitmap(1280, 720);
//绘画
titleForm.DrawToBitmap(bmp, new Rectangle(new Point(0, 0), titleForm.Size));
//显示
pictureBox1.Image = bmp;
}
catch (Exception ex)
{
mt.Show(ex.ToString(), true);
}
TransferTimer.Enabled = true;
}
------------------------------下面为WinAPI 截图 不推荐,内存会骤增----------------------------------
/// <summary>
/// 截屏
/// </summary>
/// <param name="ctrl"></param>
/// <returns></returns>
[DllImport("User32.dll")]
private static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);
public Bitmap CaptureControl(Control ctrl)
{
if (ctrl == null || ctrl.IsDisposed)
{
return null;
}
Bitmap image = new Bitmap(ctrl.Width, ctrl.Height);
using (Graphics graphics = Graphics.FromImage(image))
{
IntPtr hdc = graphics.GetHdc();
try
{
if (!PrintWindow(ctrl.Handle, hdc, 0))
{
return null;
}
}
catch (Exception ex)
{
mt.Show("异常CaptureControl:" + ex.ToString(), true);
}
finally
{
graphics.ReleaseHdc(hdc);
}
}
return image;
}