浅析如何用C#.NET做屏幕截图软件以及注册全局快捷键(上)
2010-09-30 22:42:43 来源:WEB开发网最近为了学习C#,决定自己做一个屏幕截图工具,来代替长久以来每次都要按下PrintScreen键然后到Clipboard里面寻找之麻烦。学以致用~
用C#做屏幕截图,大致有三种方法。
1、最managed大概就是使用Graphics.CopyFromScreen()方法,此方法有四个重载,不过经反编可见最后调用的都是:
CopyFromScreen(int sourceX, int sourceY, int destinationX, int destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
调用该方法的优点是代码简单,不用平台调用。不过最大的缺点是:不能截取半透明窗体。你要想截图透明窗体的话,可以加一个参数,它就是:CopyPixelOperation.CaptureBlt。但是,这样的话,只能截图透明窗体,截不到屏幕的其他部分了。所以,该方法已经基本可以放弃了。不过我们还是来研究了一下CopyFromScreen()的内部实现吧,看看问题之所在。下面是该方法的具体实现,reflect自System.Drawing.dll
CopyFromScreen
public void CopyFromScreen(int sourceX, int sourceY, int destinationX, int destinationY, Size blockRegionSize, CopyPixelOperation copyPixelOperation)
{
switch (copyPixelOperation)
{
case CopyPixelOperation.NotSourceErase:
case CopyPixelOperation.NotSourceCopy:
case CopyPixelOperation.NoMirrorBitmap:
case CopyPixelOperation.Blackness:
case CopyPixelOperation.SourceErase:
...
case CopyPixelOperation.SourceCopy:
case CopyPixelOperation.SourceAnd:
case CopyPixelOperation.MergePaint:
case CopyPixelOperation.SourcePaint:
case CopyPixelOperation.PatCopy:
case CopyPixelOperation.PatPaint:
case CopyPixelOperation.Whiteness:
case CopyPixelOperation.CaptureBlt:
{
new UIPermission(UIPermissionWindow.AllWindows).Demand();
int width = blockRegionSize.Width;
int height = blockRegionSize.Height;
using (DeviceContext context = DeviceContext.FromHwnd(IntPtr.Zero))
{
HandleRef hSrcDC = new HandleRef(null, context.Hdc);
HandleRef hDC = new HandleRef(null, this.GetHdc());
try
{
if (SafeNativeMethods.BitBlt(hDC, destinationX, destinationY, width, height, hSrcDC, sourceX, sourceY, (int) copyPixelOperation) == 0)
{
throw new Win32Exception();
}
}
finally
{
this.ReleaseHdc();
}
}
return;
}
}
throw new InvalidEnumArgumentException("value", (int) copyPixelOperation, typeof(CopyPixelOperation));
}
更多精彩
赞助商链接