如何修改自动定时截屏批处理文件实现指定区域截屏?
修改后的批处理文件
@echo off REM 截取指定屏幕区域,每5秒一次 Set CaptureScreenFolder=C:\ScreenCapture\ If Not Exist "%CaptureScreenFolder%" MD "%CaptureScreenFolder%" Set WaitTimeSeconds=5 REM 定义截取区域参数:起始坐标(X,Y)、宽高 Set CaptureX=100 Set CaptureY=100 Set CaptureWidth=900 Set CaptureHeight=900 :Loop Call :ScreenShot echo 截图已保存于 %Date% @ %Time%,路径:"%CaptureScreenFolder%" Timeout /T %WaitTimeSeconds% /NoBreak>nul Goto Loop ::---------------------------------------------------------------------------- :ScreenShot Powershell ^ $Path = '%CaptureScreenFolder%';^ Add-Type -AssemblyName System.Windows.Forms;^ Add-Type -AssemblyName System.Drawing;^ $sourceX = %CaptureX%;^ $sourceY = %CaptureY%;^ $captureWidth = %CaptureWidth%;^ $captureHeight = %CaptureHeight%;^ $image = New-Object System.Drawing.Bitmap($captureWidth, $captureHeight);^ $graphic = [System.Drawing.Graphics]::FromImage($image);^ $sourcePoint = New-Object System.Drawing.Point($sourceX, $sourceY);^ $destPoint = New-Object System.Drawing.Point(0, 0);^ $graphic.CopyFromScreen($sourcePoint, $destPoint, $image.Size);^ $cursorPos = [System.Windows.Forms.Cursor]::Position;^ # 仅当光标在截取区域内时,绘制光标到截图上 if ($cursorPos.X -ge $sourceX -and $cursorPos.X -lt ($sourceX + $captureWidth) -and $cursorPos.Y -ge $sourceY -and $cursorPos.Y -lt ($sourceY + $captureHeight)) {^ $relativeX = $cursorPos.X - $sourceX;^ $relativeY = $cursorPos.Y - $sourceY;^ $cursorBounds = New-Object System.Drawing.Rectangle($relativeX, $relativeY, [System.Windows.Forms.Cursor]::Current.Size.Width, [System.Windows.Forms.Cursor]::Current.Size.Height);^ [System.Windows.Forms.Cursors]::Default.Draw($graphic, $cursorBounds);^ }^ $FileName = $((Get-Date).ToString('dd-MM-yyyy_HH_mm_ss')+'.jpg');^ $FilePath = Join-Path -Path $Path -ChildPath $FileName;^ $FormatJPEG = [System.Drawing.Imaging.ImageFormat]::jpeg;^ $image.Save($FilePath,$FormatJPEG);^ $graphic.Dispose();^ $image.Dispose();^ Exit /B
修改说明
- 新增区域配置变量:在批处理开头添加
CaptureX、CaptureY、CaptureWidth、CaptureHeight四个变量,直接修改这些值就能调整截取范围(比如你要从(100,100)到(1000,1000),宽高就是900,因为1000-100=900)。 - 调整位图尺寸:创建截图位图时,不再使用屏幕全屏大小,改用你定义的区域宽高。
- 指定截取源位置:修改
CopyFromScreen的参数,第一个参数是屏幕上的起始坐标,第三个参数是截取的区域尺寸,实现精准截取。 - 修正光标绘制逻辑:判断光标是否在截取区域内,计算光标相对于截图左上角的位置后再绘制,避免光标位置错位。
- 添加资源释放:新增
$graphic.Dispose()和$image.Dispose(),避免长期运行导致内存泄漏。
注意:Windows系统的屏幕坐标原点是左上角,如果你要求的左下角是原点,需要把CaptureY换算为屏幕高度 - 目标结束Y坐标,比如屏幕高度为1080,目标结束Y坐标为1000(左下角原点),那实际CaptureY就是1080-1000=80,CaptureHeight仍为900。
内容的提问来源于stack exchange,提问作者RollingThunder
相关产品推荐
相关产品推荐

