C#学习教程:如何捕捉屏幕的一部分分享


如何捕捉屏幕的一部分

我正在使用win32 PrintWindow函数将屏幕捕获到BitMap对象。

如果我只想捕获窗口的某个区域,我该如何在内存中裁剪图像?

这是我用来捕获整个窗口的代码:

[System.Runtime.InteropServices.DllImport(strUSER32DLL, CharSet = CharSet.Auto, SetLastError = true)] public static extern int PrintWindow(IntPtr hWnd, IntPtr hBltDC, uint iFlags); public enum enPrintWindowFlags : uint { ///  /// ///  PW_ALL = 0x00000000, ///  /// Only the client area of the window is copied. By default, the entire window is copied. ///  PW_CLIENTONLY = 0x00000001 } public System.Drawing.Bitmap CaptureWindow(IntPtr hWnd, enPrintWindowFlags eFlags) { System.Drawing.Rectangle rctForm = System.Drawing.Rectangle.Empty; using(System.Drawing.Graphics grfx = System.Drawing.Graphics.FromHdc(GetWindowDC(hWnd))) { rctForm = System.Drawing.Rectangle.Round(grfx.VisibleClipBounds); } System.Drawing.Bitmap pImage = new System.Drawing.Bitmap(rctForm.Width, rctForm.Height); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(pImage); IntPtr hDC = graphics.GetHdc(); //paint control onto graphics using provided options try { PrintWindow(hWnd, hDC, (uint)eFlags); } finally { graphics.ReleaseHdc(hDC); } return pImage; } 

您可以简单地抓取整个屏幕,然后将图像传递到裁剪function,该function选择整个图像的一个区域。 看一下Bitmap.Clone()方法。 例如

 public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight) { Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight); Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat); return cropped; } 

请注意,我从这个博客中删除了这个

这是捕获屏幕并创建100像素正方形裁剪图像的完整代码。 代码取自Click事件按钮。 用你需要的。

 Bitmap screenShot = null; Bitmap croppedImage; Graphics screen; if(saveFileDialog.ShowDialog() == DialogResult.OK) { this.Hide(); screenShot = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); screen = Graphics.FromImage(screenShot); screen.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); screenShot.Save(saveFileDialog.FileName, ImageFormat.Png); this.Show(); } //crop image if(screenShot != null) { if(saveFileDialog.ShowDialog() == DialogResult.OK) { int x = 100; int y = 100; int xWidth = 100; int yHeight = 100; Rectangle rect = new Rectangle(x, y, xWidth, yHeight); croppedImage = screenShot.Clone(rect, PixelFormat.Format32bppArgb); if (croppedImage != null) { croppedImage.Save(saveFileDialog.FileName, ImageFormat.Png); } } } 

省去一些麻烦,拿起Cropper来源。

上述就是C#学习教程:如何捕捉屏幕的一部分分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—猴子技术宅(www.ssfiction.com)

本文来自网络收集,不代表猴子技术宅立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ssfiction.com/ckf/959844.html

发表评论

邮箱地址不会被公开。 必填项已用*标注