今天一位同事想写一个全屏幕截图的代码当然要实现的第一步是能够获取整个屏幕的位图记得Win API的CreateDC BitBlt等函数可以使用于是上网查了下果然屏幕截图用这些函数但winform已经可以把API都忘记了所以得寻找一个无Win API的实现方式综合了网上的实现以及自己的一些设计实现思路如下 开始截图时创建一个与屏幕大小一样的位图然后用GraphicsCopyFromScreen()把屏幕位图拷贝到该位图上这是很关键的一步这样所有的操作就都可以在该位图上进行了而无实际屏幕无关了
int width = ScreenPrimaryScreenBoundsWidth;
int height = ScreenPrimaryScreenBoundsHeight;
Bitmap bmp = new Bitmap(width height);
using (Graphics g = GraphicsFromImage(bmp)) {
gCopyFromScreen( new Size(width height));
}
接下来为了方便在这之上进行截图有一个很重要的设计实现方式用全屏幕窗体代替现有真实屏幕这样就可以把截图过程的所有操作都在那个窗体上实现(该窗体设置成无边框高宽等于屏幕大小即可)另外为了显示掩蔽效果(只能正常显示选择的部分屏幕内容而其实部分用一个如半透明层覆盖)就添加一层半透明位置位图具体代码如下
public partial class FullScreenForm : Form {
private Rectangle rectSelected = RectangleEmpty;
private bool isClipping = false;
private Bitmap screen;
private Bitmap coverLayer = null;
private Color coverColor;
private Brush rectBrush = null;
private Bitmap resultBmp = null;
public FullScreenForm(Bitmap screen) {
InitializeComponent();
int width = ScreenPrimaryScreenBoundsWidth;
int height = ScreenPrimaryScreenBoundsHeight;
coverLayer = new Bitmap(width height);
coverColor = ColorFromArgb( );
rectBrush = new SolidBrush(coverColor);
using (Graphics g = GraphicsFromImage(coverLayer)) {
gClear(coverColor);
}
thisBounds = new Rectangle( width height);
thisscreen = screen;
thisDoubleBuffered = true;
}
protected override void OnMouseDown(MouseEventArgs e) {
if (eButton == MouseButtonsLeft) {
isClipping = true;
rectSelectedLocation = eLocation;
}
else if (eButton == MouseButtonsRight) {
thisDialogResult = DialogResultOK;
}
}
protected override void OnMouseMove(MouseEventArgs e) {
if (eButton == MouseButtonsLeft && isClipping) {
rectSelectedWidth = eX rectSelectedX;
rectSelectedHeight = eY rectSelectedY;
thisInvalidate();
}
}
protected override void OnMouseUp(MouseEventArgs e) {
if (eButton == MouseButtonsLeft && isClipping) {
rectSelectedWidth = eX rectSelectedX;
rectSelectedHeight = eY rectSelectedY;
thisInvalidate();
resultBmp = new Bitmap(rectSelectedWidth rectSelectedHeight);
using (Graphics g = GraphicsFromImage(resultBmp)) {
gDrawImage(screennew Rectangle( rectSelectedWidth rectSelectedHeight) rectSelected GraphicsUnitPixel);
}
thisDialogResult = DialogResultOK;
}
}
protected override void OnPaint(PaintEventArgs e) {
Graphics g = eGraphics;
gDrawImage(screen );
gDrawImage(coverLayer );
PaintRectangle();
}
protected override void OnPaintBackground(PaintEventArgs e) {
}
protected override void OnKeyDown(KeyEventArgs e) {
if (eKeyCode == KeysEscape) {
thisDialogResult = DialogResultCancel;
}
}
private void PaintRectangle() {
using (Graphics g = GraphicsFromImage(coverLayer)) {
gClear(coverColor);
GraphicsPath path = new GraphicsPath();
pathAddRectangle(thisBounds);
pathAddRectangle(rectSelected);
gFillPath(rectBrush path);
gDrawRectangle(PensBlue rectSelected);
}
}
public Bitmap ResultBitmap {
get { return resultBmp; }
}
}
上面的代码都很容易看明白这里有一个技巧就是GraphicsPath它自动会形成一个中空的区域上面的实现很容易扩展多区域截图多裁判截图等都很容易实现