动态获取当前屏幕中光标所在位置的颜色,模仿QQ截图功能
分类:高并发

//////////////////////////////////////////////////////////////////////////

前阵子改了段C#截图功能的代码,现贴上来希望对大家有用

编程思路(API 编程):
先调用 GetForegroundWindow 获取当前活动程序窗口句柄,然后调用 GetWindowDC 获取窗口的设备句柄(或 GetDC 函数),调用 BitBlt 位图传输函数将位图拷贝到兼容的设备场景中(拷贝时可以指定位置和大小),最后保存位图文件。

 

/// 程序:屏幕取色

主文件

以下源代码内容转自 CSDN 论坛。

ClockControl.cs

/// 功能:动态获取当前屏幕中光标所在位置的颜色

CaptureScreenForm.cs

要想完成这个功能,首先要了解一下在C#中如何调用API(应用程序接口)函数。虽然在.Net框架中已经提供了许多类库,这些类库的功能也十分强大,但对于一些Windows底层编程来说,还是要通过调用这些API函数才可以实现。所有API都在"Kernel"、"User "和"GDI"三个库中得以运行:其中"Kernel",他的库名为 "KERNEL32.DLL", 他主要用于产生与操作系统之间的关联,譬如:程序加载,上下文选择,文件输入输出,内存管理等等。"User "这个类库在Win32中名叫 "USER32.DLL"。 它允许管理全部的用户接口。譬如:窗口 、菜单 、对话框 、图标等等。"GDI"(图象设备接口),它在Win32中的库名为:"GDI32.dll",它是图形输出库。使用GDI Windows"画"出窗口、菜单以及对话框等;它能创建图形输出;它也能保存图形文件。由于本文所涉及到是图象问题,所有调用的类库是"GDI32.dll"。在本文程序中我们使用的API函数是"BitBlt",这个函数对于广大程序员来说,一定不感觉到陌生,因为在图象处理方面他的用途是相对广的,在用其他程序语言编程中,时常也要和他打交道。在.Net FrameWork SDK中有一个名字空间"System.Runtime.InteropServices",此名字空间提供了一系列的类来访问COM对象,和调用本地的API函数。下面是在C#中声明此函数:

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace ClockTime
{
 ///
 /// ClockControl 的摘要说明。
 ///
 public class ClockControl:System.Windows.Forms.UserControl

/// 作者:黎波

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;

[ System.Runtime.InteropServices.DllImportAttribute ( "gdi32.dll" ) ]
private static extern bool BitBlt (
IntPtr hdcDest , // 目标 DC的句柄
int nXDest ,
int nYDest ,
int nWidth ,
int nHeight ,
IntPtr hdcSrc , // 源DC的句柄
int nXSrc ,
int nYSrc ,
System.Int32 dwRop // 光栅的处理数值
) ;

 {
  private DateTime dt;

/// 网名:upto(阿球)

namespace CaptureScreen
{
 ///
 /// CaptureScreenForm 的摘要说明。
 ///
 public class CaptureScreenForm : System.Windows.Forms.Form
 {
  private System.Windows.Forms.PictureBox picbox;
  private System.Windows.Forms.Button exitBtn;
  private System.Windows.Forms.Button aboutBtn;
  private System.Windows.Forms.Button ClearBtn;
  private System.Windows.Forms.Button saveBtn;
  private System.Windows.Forms.Button fullScreenBtn;
  private System.Windows.Forms.Button mouseCaptureBtn;

通过上面这个声明,就可以在下面的代码中使用此函数了。

  public ClockControl()
  {
   //
   // TODO: 在此处添加构造函数逻辑
   //
   this.ResizeRedraw=true;
   this.Enabled=false;

/// 邮箱:itfun@163.com

  public static Image image = null ;
  private System.Windows.Forms.Panel panel1;

下面是用C#做屏幕捕获程序的具体实现步骤:

  }
  public DateTime Time
  {
   set
   {
    Graphics grfx=this.CreateGraphics(,',',');
    Pen pn=new Pen(this.BackColor,',',');
    InitializeCoordinates(grfx,',',');
    if(dt.Hour!=value.Hour)
    {
     DrawHourHand(grfx,pn,',',');
    }
    if(dt.Minute!=value.Minute)
    {
     DrawHourHand(grfx,pn,',',');
     DrawMinuteHand(grfx,pn,',',');
 
    }
    if(dt.Second!=value.Second)
    {
     DrawMinuteHand(grfx,pn,',',');
     DrawSecondHand(grfx,pn,',',');
    }
    if(dt.Millisecond!=value.Millisecond)
    {
     DrawSecondHand(grfx,pn,',',');
    }
    dt=value;
    pn=new Pen(ForeColor,',',');
    DrawHourHand(grfx,pn,',',');
    DrawMinuteHand(grfx,pn,',',');
    DrawSecondHand(grfx,pn,',',');
    grfx.Dispose(,',',');
   }
   get
   {return dt;
   }
  }
  protected override  void OnPaint(PaintEventArgs e)
  {
   Graphics grfx=e.Graphics;
   Pen pn=new Pen(ForeColor,',',');
   SolidBrush br=new SolidBrush(ForeColor,',',');
   InitializeCoordinates(grfx,',',');
   DrawDots(grfx,br,',',');
   DrawHourHand(grfx,pn,',',');
   DrawSecondHand(grfx,pn,',',');
   DrawMinuteHand(grfx,pn,',',');
  }
  protected virtual void InitializeCoordinates(Graphics grfx)
  {
   if(this.Width==0 || this.Height==0) return;
   grfx.TranslateTransform(this.Width/2,this.Height/2,',',');
   Single fInches=Math.Min(this.Width/grfx.DpiX,this.Height/grfx.DpiY,',',');
   grfx.ScaleTransform(fInches*grfx.DpiX/2000,fInches*grfx.DpiY/2000,',',');

/// 日期:2004年3月31日

  ///
  /// 必需的设计器变量。
  ///
  private System.ComponentModel.Container components = null;

(1).首先要获得当前屏幕的graphic对象,通过以下代码可以实现:

  }
  protected virtual  void  DrawDots(Graphics grfx ,Brush br)
  {
   int i,iSize;
   for(i=0;i<=59;i++)
   {
    if(i%5==0)
    {
     iSize=100;
    }
    else
     iSize=30;
    grfx.FillEllipse(br,0-iSize/2,-900-iSize/2,iSize,iSize,',',');
    grfx.RotateTransform(6,',',');

//////////////////////////////////////////////////////////////////////////

  public CaptureScreenForm()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

Graphics g1 = this.CreateGraphics ( ) ;

   }
  }
 protected virtual void  DrawHourHand(Graphics grfx,Pen pn)
  {
   GraphicsState gs=grfx.Save(,',',');
   grfx.RotateTransform(360.0F*Time.Hour/12+30.0F*Time.Minute/60,',',');
   grfx.DrawPolygon(pn,new Point[]{new Point(0,150),new Point(100,0),new Point(0,-600),new Point(-100,0)},',',');
   grfx.Restore(gs,',',');
  }
protected virtual void  DrawMinuteHand(Graphics grfx,Pen pn)
  {
   GraphicsState gs=grfx.Save(,',',');
   grfx.RotateTransform(360.0F*Time.Minute/60+6.0F*Time.Second/60,',',');
   grfx.DrawPolygon(pn,new Point[]{new Point(0,200),new Point(50,0),new Point(0,-800),new Point(-50,0)},',',');
   grfx.Restore(gs,',',');
  }
protected virtual void  DrawSecondHand(Graphics grfx,Pen pn)
  {
   GraphicsState gs=grfx.Save(,',',');
   grfx.RotateTransform(360.0F*Time.Second/60+6.0F*Time.Millisecond/1000,',',');
   grfx.DrawLine(pn,0,0,0,-800,',',');
   grfx.Restore(gs,',',');
  
  }
 }
}

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

(2).创建一个Bitmap对象,并且这个Bitmap对象的大小是当前屏幕:

form1.cs

namespace LiBo.ColorPicker
{
///
/// Form1 的摘要说明。
///
public class Form1 : System.Windows.Forms.Form
{
// 桌面工作区的尺寸
Size workingArea;
// Form 的初始位置和在左下角,右下角的位置
Point formLoc, ptLeftBottom, ptRightBottom;

  ///
  /// 清理所有正在使用的资源。
  ///
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

首先要获得当前屏幕的大小,通过名字空间"System.Windows.Forms"中的"Screen"类的GetWorkingArea()方法,可以实现。下面是得到当前屏幕的长(Height)和宽(Width):

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using ClockTime;

private System.Windows.Forms.Label lblColor;
private System.Windows.Forms.TextBox txtArgb;
private System.Windows.Forms.Timer tmr;
private System.Windows.Forms.ToolTip tip;
private System.ComponentModel.IContainer components;

  #region Windows 窗体设计器生成的代码
  ///
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///
  private void InitializeComponent()
  {
   this.picbox = new System.Windows.Forms.PictureBox();
   this.fullScreenBtn = new System.Windows.Forms.Button();
   this.mouseCaptureBtn = new System.Windows.Forms.Button();
   this.ClearBtn = new System.Windows.Forms.Button();
   this.saveBtn = new System.Windows.Forms.Button();
   this.aboutBtn = new System.Windows.Forms.Button();
   this.exitBtn = new System.Windows.Forms.Button();
   this.panel1 = new System.Windows.Forms.Panel();
   this.panel1.SuspendLayout();
   this.SuspendLayout();
   //
   // picbox
   //
   this.picbox.Location = new System.Drawing.Point(0, 40);
   this.picbox.Name = "picbox";
   this.picbox.Size = new System.Drawing.Size(680, 312);
   this.picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
   this.picbox.TabIndex = 0;
   this.picbox.TabStop = false;
   //
   // fullScreenBtn
   //
   this.fullScreenBtn.Location = new System.Drawing.Point(0, 0);
   this.fullScreenBtn.Name = "fullScreenBtn";
   this.fullScreenBtn.Size = new System.Drawing.Size(96, 32);
   this.fullScreenBtn.TabIndex = 1;
   this.fullScreenBtn.Text = "全屏截取";
   this.fullScreenBtn.Click += new System.EventHandler(this.fullScreenBtn_Click);
   //
   // mouseCaptureBtn
   //
   this.mouseCaptureBtn.Location = new System.Drawing.Point(120, 0);
   this.mouseCaptureBtn.Name = "mouseCaptureBtn";
   this.mouseCaptureBtn.Size = new System.Drawing.Size(96, 32);
   this.mouseCaptureBtn.TabIndex = 2;
   this.mouseCaptureBtn.Text = "鼠标截取";
   this.mouseCaptureBtn.Click += new System.EventHandler(this.mouseCaptureBtn_Click);
   //
   // ClearBtn
   //
   this.ClearBtn.Location = new System.Drawing.Point(240, 0);
   this.ClearBtn.Name = "ClearBtn";
   this.ClearBtn.Size = new System.Drawing.Size(88, 32);
   this.ClearBtn.TabIndex = 3;
   this.ClearBtn.Text = "清除截取图片";
   this.ClearBtn.Click += new System.EventHandler(this.ClearBtn_Click);
   //
   // saveBtn
   //
   this.saveBtn.Location = new System.Drawing.Point(352, 0);
   this.saveBtn.Name = "saveBtn";
   this.saveBtn.Size = new System.Drawing.Size(96, 32);
   this.saveBtn.TabIndex = 4;
   this.saveBtn.Text = "保存截取图片";
   this.saveBtn.Click += new System.EventHandler(this.saveBtn_Click);
   //
   // aboutBtn
   //
   this.aboutBtn.Location = new System.Drawing.Point(472, 0);
   this.aboutBtn.Name = "aboutBtn";
   this.aboutBtn.Size = new System.Drawing.Size(96, 32);
   this.aboutBtn.TabIndex = 5;
   this.aboutBtn.Text = "关  于";
   this.aboutBtn.Click += new System.EventHandler(this.aboutBtn_Click);
   //
   // exitBtn
   //
   this.exitBtn.Location = new System.Drawing.Point(592, 0);
   this.exitBtn.Name = "exitBtn";
   this.exitBtn.Size = new System.Drawing.Size(88, 32);
   this.exitBtn.TabIndex = 6;
   this.exitBtn.Text = "退  出";
   this.exitBtn.Click += new System.EventHandler(this.exitBtn_Click);
   //
   // panel1
   //
   this.panel1.Controls.Add(this.fullScreenBtn);
   this.panel1.Controls.Add(this.mouseCaptureBtn);
   this.panel1.Controls.Add(this.ClearBtn);
   this.panel1.Controls.Add(this.saveBtn);
   this.panel1.Controls.Add(this.aboutBtn);
   this.panel1.Controls.Add(this.exitBtn);
   this.panel1.Location = new System.Drawing.Point(0, 0);
   this.panel1.Name = "panel1";
   this.panel1.Size = new System.Drawing.Size(680, 32);
   this.panel1.TabIndex = 7;
   //
   // CaptureScreenForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.AutoScroll = true;
   this.ClientSize = new System.Drawing.Size(696, 358);
   this.Controls.Add(this.panel1);
   this.Controls.Add(this.picbox);
   this.Name = "CaptureScreenForm";
   this.Text = "截取屏幕";
   this.panel1.ResumeLayout(false);
   this.ResumeLayout(false);

Rectangle rect = new Rectangle ( ) ;
rect = Screen.GetWorkingArea ( this ) ;
"屏幕宽"= rect.Width ;
"屏幕长"= rect.Height ;

namespace ClockTime
{
 ///
 /// Form1 的摘要说明。
 ///
 public class Form1 : System.Windows.Forms.Form
 {
  private System.ComponentModel.IContainer components;
  private System.Windows.Forms.Timer tmr;
 private ClockTime.ClockControl clkctrl;
  public Form1()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent(,',',');

public Form1()
{
InitializeComponent();

  }
  #endregion

至此就可以得到我们想要的Bitmap了,通过下列语句可以实现:

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
this.StartPosition = FormStartPosition.CenterScreen;

  ///
  /// 应用程序的主入口点。
  ///
  [STAThread]
  static void Main()
  {
   Application.Run(new CaptureScreenForm());
  }

Image MyImage = new Bitmap ( rect.Width , rect.Height , g1 ) ;
//创建以屏幕大小为标准的位图

  ///
  /// 清理所有正在使用的资源。
  ///
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose(,',',');
    }
   }
   base.Dispose( disposing ,',',');
  }

Rectangle rect = SystemInformation.WorkingArea;
workingArea = new Size(rect.Width, rect.Height);
ptLeftBottom = new Point(0, workingArea.Height - this.Height);
ptRightBottom = new Point(workingArea.Width - this.Width,
workingArea.Height - this.Height);

  protected override void OnPaint(PaintEventArgs e)
  {
   base.OnPaint (e);
   if(image != null)
   {
    this.picbox.Image = image;
   }
   else
   {
    this.picbox.Image = null;
    this.picbox.Refresh();
   }
  }

(3).获得当前屏幕和此Bitmap对象的DC,这可以通过下列语句实现:

  #region Windows 窗体设计器生成的代码
  ///
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///
  private void InitializeComponent()
  {
   this.components = new System.ComponentModel.Container(,',',');
   this.clkctrl = new ClockTime.ClockControl(,',',');
   this.tmr = new System.Windows.Forms.Timer(this.components,',',');
   this.SuspendLayout(,',',');
   //
   // clkctrl
   //
   this.clkctrl.BackColor = System.Drawing.Color.Black;
   this.clkctrl.Dock = System.Windows.Forms.DockStyle.Fill;
   this.clkctrl.Enabled = false;
   this.clkctrl.ForeColor = System.Drawing.Color.White;
   this.clkctrl.Location = new System.Drawing.Point(0, 0,',',');
   this.clkctrl.Name = "clkctrl";
   this.clkctrl.Size = new System.Drawing.Size(292, 273,',',');
   this.clkctrl.TabIndex = 0;
   this.clkctrl.Time = new System.DateTime(2005, 6, 24, 10, 19, 26, 62,',',');
   //
   // tmr
   //
   this.tmr.Enabled = true;
   this.tmr.Interval = 1000;
   this.tmr.Tick += new System.EventHandler(this.tmr_Tick,',',');
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14,',',');
   this.BackColor = System.Drawing.SystemColors.Window;
   this.ClientSize = new System.Drawing.Size(292, 273,',',');
   this.Controls.Add(this.clkctrl,',',');
   this.ForeColor = System.Drawing.SystemColors.WindowText;
   this.Name = "Form1";
   this.Text = "ClockControl";
   this.ResumeLayout(false,',',');

String tipMsg = "在窗体空白处双击鼠标左键开始取色,按ESC键确定颜色";
tip.SetToolTip(this, tipMsg);
tip.SetToolTip(lblColor, tipMsg);
tip.SetToolTip(txtArgb, tipMsg);
}

  // 引用API

//得到屏幕的DC
IntPtr dc1 = g1.GetHdc ( ) ;
//得到Bitmap的DC
IntPtr dc2 = g2.GetHdc ( ) ;

  }
  #endregion

///
/// 清理所有正在使用的资源。
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

  [System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
  public static extern bool BitBlt(
   IntPtr hdcDest, //目标设备的句柄
   int nXDest, // 目标对象的左上角的X坐标
   int nYDest, // 目标对象的左上角的X坐标
   int nWidth, // 目标对象的矩形的宽度
   int nHeight, // 目标对象的矩形的长度
   IntPtr hdcSrc, // 源设备的句柄
   int nXSrc, // 源对象的左上角的X坐标
   int nYSrc, // 源对象的左上角的X坐标
   System.Int32 dwRop // 光栅的操作值
   );

(4).调用API函数,把当前屏幕拷贝到创建的Bitmap中:

  ///
  /// 应用程序的主入口点。
  ///
  [STAThread]
  static void Main()
  {
   
   Application.Run(new Form1(),',',');
  }

#region Windows Form Designer generated code
///
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
///
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.lblColor = new System.Windows.Forms.Label();
this.tmr = new System.Windows.Forms.Timer(this.components);
this.txtArgb = new System.Windows.Forms.TextBox();
this.tip = new System.Windows.Forms.ToolTip(this.components);
this.SuspendLayout();
//
// lblColor
//
this.lblColor.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lblColor.Location = new System.Drawing.Point(8, 8);
this.lblColor.Name = "lblColor";
this.lblColor.TabIndex = 0;
//
// tmr
//
this.tmr.Tick += new System.EventHandler(this.tmr_Tick);
//
// txtArgb
//
this.txtArgb.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtArgb.Font = new System.Drawing.Font("Arial", 10.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.txtArgb.Location = new System.Drawing.Point(8, 40);
this.txtArgb.Name = "txtArgb";
this.txtArgb.TabIndex = 1;
this.txtArgb.Text = "";
this.txtArgb.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtArgb_KeyPress);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(115, 70);
this.Controls.Add(this.txtArgb);
this.Controls.Add(this.lblColor);
this.Name = "Form1";
this.Text = "屏幕取色(upto)";
this.DoubleClick += new System.EventHandler(this.Form1_DoubleClick);
this.MouseEnter += new System.EventHandler(this.Form1_MouseEnter);
this.ResumeLayout(false);

  private void exitBtn_Click(object sender, System.EventArgs e)
  {
   Application.Exit();
  }

BitBlt ( dc2 , 0 , 0 , rect.Width , rect.Height , dc1 , 0 , 0 , 13369376 ) ;

  private void tmr_Tick(object sender, EventArgs e)
  {
  
   clkctrl.Time=DateTime.Now;
  }
 }
}

}
#endregion

  private void aboutBtn_Click(object sender, System.EventArgs e)
  {
   MessageBox.Show("Code by Star in 2006-3-17,E_mail: ygh_01@163.com ,thank you to use this.");
  }

(5).释放当前屏幕和此Bitmap对象的DC,通过下面代码可以实现:

编译过程:

///
/// 应用程序的主入口点。
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}

  private void ClearBtn_Click(object sender, System.EventArgs e)
  {
   CaptureScreenForm.image = null;
   this.Invalidate();
  }

//释放掉屏幕的DC
g1.ReleaseHdc ( dc1 ) ;
//释放掉Bitmap的DC
g2.ReleaseHdc ( dc2 ) ;

csc /t:library clockcontrol.cs

[ DllImport ( "gdi32.dll" ) ]
private static extern bool BitBlt (
IntPtr hdcDest, // 目标设备的句柄
int nXDest, // 目标对象的左上角的X坐标
int nYDest, // 目标对象的左上角的X坐标
int nWidth, // 目标对象的矩形的宽度
int nHeight, // 目标对象的矩形的长度
IntPtr hdcSrc, // 源设备的句柄
int nXSrc, // 源对象的左上角的X坐标
int nYSrc, // 源对象的左上角的X坐标
int dwRop // 光栅的操作值
);

  private void saveBtn_Click(object sender, System.EventArgs e)
  {
   bool isSave = true;
   SaveFileDialog saveImageDialog = new SaveFileDialog();
   saveImageDialog.Title = "Capture screen image save dialog";
   saveImageDialog.Filter= @"jpeg|*.jpg|bmp|*.bmp|gif|*.gif";

(6).保存Bitmap对象,形成jpg图片:

csc /t:winexe /r:clockcontrol.dll form1.cs

[ DllImport ( "gdi32.dll" ) ]
private static extern IntPtr CreateDC (
string lpszDriver, // 驱动名称
string lpszDevice, // 设备名称
string lpszOutput, // 无用,可以设定位"NULL"
IntPtr lpInitData // 任意的打印机数据
);

   if(saveImageDialog.ShowDialog() == DialogResult.OK)
   {
     string fileName = saveImageDialog.FileName.ToString();
    
    if(fileName != "" && fileName != null)
    {
     string fileExtName = fileName.Substring(fileName.LastIndexOf(".")+1).ToString();

MyImage.Save ( @"c:Capture.jpg" , ImageFormat.Jpeg );

private void Form1_DoubleClick(object sender, EventArgs e)
{
formLoc = this.Location;
this.Location = ptRightBottom;
this.TopMost = true;
tmr.Enabled = true;
}

     System.Drawing.Imaging.ImageFormat imgformat = null;     
 
     if(fileExtName!="")
     {
      switch(fileExtName)
      {
       case "jpg":
        imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
        break;
       case "bmp":
        imgformat = System.Drawing.Imaging.ImageFormat.Bmp;
        break;
       case "gif":
        imgformat = System.Drawing.Imaging.ImageFormat.Gif;
        break;
       default:
        MessageBox.Show("只能存取为: jpg,bmp,gif 格式");
        isSave = false;
        break;
      }

当然你也可以根据自己的需要,把屏幕以其他图片的格式来保存,如果你想把图片保存为位图文件,可以把"ImageFormat.Jpeg"改换成"ImageFormat.Bmp";想把图片保存为Gif文件,就把"ImageFormat.Jpeg"改换成"ImageFormat.Gif"。你可以保存的文件类型大概有十多种,这里就不一一介绍了,当然你也要相应改变保存文件的后缀。

private void tmr_Tick(object sender, EventArgs e)

     }

用C#来捕获屏幕的源程序代码(Capture.cs):

{

     //默认保存为JPG格式
     if(imgformat == null)
     {
      imgformat = System.Drawing.Imaging.ImageFormat.Jpeg;
     }
                   
     if(isSave)
     {
      try
      {
       CaptureScreenForm.image.Save(fileName,imgformat);
       MessageBox.Show("图片已经成功保存!~~");
      }
      catch
      {
       MessageBox.Show("保存失败,你还没有截取过图片或已经清空图片!");
      }
     }

图片 1using System ; 
图片 2using System.Drawing ; 
图片 3using System.Collections ; 
图片 4using System.ComponentModel ; 
图片 5using System.Windows.Forms ; 
图片 6using System.Data ; 
图片 7using System.Drawing.Imaging ; 
图片 8public class Form1 : Form 
图片 9图片 10图片 11
图片 12    private Button button1 ; 
图片 13    private System.ComponentModel.Container components = null ; 
图片 14
图片 15    public Form1 ( ) 
图片 16图片 17    图片 18
图片 19        //初始化窗体中的各个组件 
图片 20        InitializeComponent ( ) ; 
图片 21    } 
图片 22    // 清除程序中使用过的资源 
图片 23    protected override void Dispose ( bool disposing ) 
图片 24图片 25    图片 26
图片 27        if ( disposing ) 
图片 28图片 29        图片 30
图片 31            if ( components != null ) 
图片 32图片 33            图片 34
图片 35                components.Dispose ( ) ; 
图片 36            } 
图片 37        } 
图片 38        base.Dispose ( disposing ) ; 
图片 39    } 
图片 40    private void InitializeComponent ( ) 
图片 41图片 42    图片 43
图片 44        button1 = new Button ( ); 
图片 45        SuspendLayout ( ) ; 
图片 46        button1.Location = new System.Drawing.Point ( 64 , 40 ) ; 
图片 47        button1.Name = "button1" ; 
图片 48        button1.Size = new System.Drawing.Size ( 80 , 32 ) ; 
图片 49        button1.TabIndex = 0 ; 
图片 50        button1.Text = "捕获" ; 
图片 51        button1.Click += new System.EventHandler ( button1_Click ) ; 
图片 52
图片 53        AutoScaleBaseSize = new System.Drawing.Size ( 6 , 14 ) ; 
图片 54        ClientSize = new System.Drawing.Size ( 216 , 125 ) ; 
图片 55        Controls.Add ( button1 ) ; 
图片 56        MaximizeBox = false ; 
图片 57        MinimizeBox = false ; 
图片 58        Name = "Form1" ; 
图片 59        Text = "C#捕获当前屏幕!" ; 
图片 60        ResumeLayout ( false ) ; 
图片 61
图片 62    } 
图片 63    //声明一个API函数 
图片 64    [ System.Runtime.InteropServices.DllImportAttribute ( "gdi32.dll" ) ] 
图片 65    private static extern bool BitBlt ( 
图片 66        IntPtr hdcDest , // 目标 DC的句柄 
图片 67        int nXDest , 
图片 68        int nYDest , 
图片 69        int nWidth , 
图片 70        int nHeight , 
图片 71        IntPtr hdcSrc , // 源DC的句柄 
图片 72        int nXSrc , 
图片 73        int nYSrc , 
图片 74        System.Int32 dwRop // 光栅的处理数值 
图片 75        ) ; 
图片 76
图片 77    static void Main ( ) 
图片 78图片 79    图片 80
图片 81        Application.Run ( new Form1 ( ) ) ; 
图片 82    } 
图片 83    private void button1_Click ( object sender , System.EventArgs e ) 
图片 84图片 85    图片 86
图片 87        //获得当前屏幕的大小 
图片 88        Rectangle rect = new Rectangle ( ) ; 
图片 89        rect = Screen.GetWorkingArea ( this ) ; 
图片 90        //创建一个以当前屏幕为模板的图象 
图片 91        Graphics g1 = this.CreateGraphics ( ) ; 
图片 92        //创建以屏幕大小为标准的位图 
图片 93        Image MyImage = new Bitmap ( rect.Width , rect.Height , g1 ) ; 
图片 94        Graphics g2 = Graphics.FromImage ( MyImage ) ; 
图片 95        //得到屏幕的DC 
图片 96        IntPtr dc1 = g1.GetHdc ( ) ; 
图片 97        //得到Bitmap的DC 
图片 98        IntPtr dc2 = g2.GetHdc ( ) ; 
图片 99        //调用此API函数,实现屏幕捕获 
图片 100        BitBlt ( dc2 , 0 , 0 , rect.Width , rect.Height , dc1 , 0 , 0 , 13369376 ) ; 
图片 101        //释放掉屏幕的DC 
图片 102        g1.ReleaseHdc ( dc1 ) ; 
图片 103        //释放掉Bitmap的DC 
图片 104        g2.ReleaseHdc ( dc2 ) ; 
图片 105        //以JPG文件格式来保存 
图片 106        MyImage.Save ( @"c:Capture.jpg" , ImageFormat.Jpeg ); 
图片 107        MessageBox.Show ( "当前屏幕已经保存为C盘的capture.jpg文件!" ) ; 
图片 108    } 
图片 109}

// 创建显示器的DC

    }

来源:

IntPtr hdlDisplay = CreateDC("DISPLAY", null, null, IntPtr.Zero);

   }
  }

// 从指定设备的句柄创建新的 Graphics 对象

  private void fullScreenBtn_Click(object sender, System.EventArgs e)
  {
      CaptureScreenForm.image = windowFullScreen();
   picbox.Image = CaptureScreenForm.image;
  }

Graphics gfxDisplay = Graphics.FromHdc(hdlDisplay);

  public static Bitmap windowFullScreen()
  {
   //建立屏幕Graphics
   Graphics grpScreen = Graphics.FromHwnd(IntPtr.Zero);
   //根据屏幕大小建立位图
   Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,Screen.PrimaryScreen.Bounds.Height,grpScreen);
   //建立位图相关Graphics
   Graphics grpBitmap = Graphics.FromImage(bitmap);
            //建立屏幕上下文
   IntPtr hdcScreen = grpScreen.GetHdc();
   //建立位图上下文
   IntPtr hdcBitmap = grpBitmap.GetHdc();
   //将屏幕捕获保存在图位中
   BitBlt(hdcBitmap,0,0,bitmap.Width,bitmap.Height,hdcScreen,0,0,0x00CC0020);
   //关闭位图句柄
   grpBitmap.ReleaseHdc(hdcBitmap);
   //关闭屏幕句柄
   grpScreen.ReleaseHdc(hdcScreen);
   //释放位图对像
   grpBitmap.Dispose();
   //释放屏幕对像
   grpScreen.Dispose();

// 创建只有一个象素大小的 Bitmap 对象

   //返回捕获位图
   return bitmap;
  }

Bitmap bmp = new Bitmap(1, 1, gfxDisplay);

  private void mouseCaptureBtn_Click(object sender, System.EventArgs e)
  {
   MouseCaptureForm mouseCapture = new MouseCaptureForm();
   mouseCapture.Show();
  }
 }
}

// 从指定 Image 对象创建新的 Graphics 对象

另一个截屏文件:

Graphics gfxBmp = Graphics.FromImage(bmp);

MouseCaptureForm.cs

// 获得屏幕的句柄

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

IntPtr hdlScreen = gfxDisplay.GetHdc();

namespace CaptureScreen
{
 ///
 /// MouseCaptureForm 的摘要说明。
 ///
 public class MouseCaptureForm : System.Windows.Forms.Form
 {
  ///
  /// 必需的设计器变量。
  ///
  //
  //自定义变量
  //
  private Point pot;
  private Rectangle area = Rectangle.Empty;
  private Image img;
  private int index = -1;
  private string noselectString   =  "n.请按下鼠标左键不放拖动选取截图区域nn .单击鼠标右键或按ESC取消截图";
  private string selectingString  =  "n.松开鼠标左键确定选取范围nn.按ESC重新选择";
  private string selectedString   =  "n.按鼠标左键调整选择范围nn .双击鼠标左键保存截图 nn.按鼠标右键重新选择 nn.ESC键取消截图";
  private System.Windows.Forms.Label tiptext;
       
  //
  //系统生成定义
  //
  private System.ComponentModel.Container components = null;

// 获得位图的句柄

  public MouseCaptureForm()
  {
   this.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
   this.BackgroundImage = CaptureScreenForm.windowFullScreen(); 

IntPtr hdlBmp = gfxBmp.GetHdc();

   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();

// 把当前屏幕中鼠标指针所在位置的一个象素拷贝到位图中

   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

BitBlt(hdlBmp, 0, 0, 1, 1, hdlScreen, MousePosition.X, MousePosition.Y, 13369376);

  ///
  /// 清理所有正在使用的资源。
  ///
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if(components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

// 释放屏幕句柄

  #region Windows 窗体设计器生成的代码
  ///
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///
  private void InitializeComponent()
  {
   this.tiptext = new System.Windows.Forms.Label();
   this.SuspendLayout();
   //
   // tiptext
   //
   this.tiptext.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255)));
   this.tiptext.ForeColor = System.Drawing.Color.White;
   this.tiptext.Location = new System.Drawing.Point(10, 10);
   this.tiptext.Name = "tiptext";
   this.tiptext.Size = new System.Drawing.Size(166, 140);
   this.tiptext.TabIndex = 0;
   this.tiptext.MouseMove += new System.Windows.Forms.MouseEventHandler(this.tiptext_MouseMove);
   //
   // MouseCaptureForm
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(456, 320);
   this.Controls.Add(this.tiptext);
   this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
   this.Name = "MouseCaptureForm";
   this.ShowInTaskbar = false;
   this.StartPosition = System.Windows.Forms.FormStartPosition.WindowsDefaultBounds;
   this.Text = "鼠标截屏";
   this.TopMost = true;
   this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
   this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.MouseCaptureForm_KeyDown);
   this.Load += new System.EventHandler(this.MouseCaptureForm_Load);
   this.DoubleClick += new System.EventHandler(this.MouseCaptureForm_DoubleClick);
   this.ResumeLayout(false);

gfxDisplay.ReleaseHdc(hdlScreen);

  }

// 释放位图句柄

  #endregion

gfxBmp.ReleaseHdc(hdlBmp);

  ///
  /// 重载MouseDown
  ///
  ///
  protected override void OnMouseDown(MouseEventArgs e)
  {    
   base.OnMouseDown (e);
    {
   if(this.area == Rectangle.Empty && e.Button == MouseButtons.Left)
   {
    this.tiptext.Text = selectingString;
    this.area.Location = new Point(e.X,e.Y);
   }
   this.pot = new Point(e.X,e.Y);
   this.index = this.GetSelectedHandle(new Point(e.X,e.Y));
   this.SetCursor();    
    }
  }

lblColor.BackColor = bmp.GetPixel(0, 0); // 获取像素的颜色

  ///
  /// 设置鼠标方案
  ///
  private void SetCursor()
  {
   Cursor cr = Cursors.Default;
 
   if(index == 1 || index == 5)
   {
    cr = Cursors.SizeNWSE;
   }
   else if(index == 2 || index == 6)
   {
    cr = Cursors.SizeNS;
   }
   else if(index == 3 || index == 7)
   {
    cr = Cursors.SizeNESW;
   }
   else if(index == 4 || index == 8)
   {
    cr = Cursors.SizeWE;
   }
   else if(index == 0)
   {
    cr = Cursors.SizeAll;
   }
   Cursor.Current = cr;
  }

txtArgb.Text = "0x" + lblColor.BackColor.ToArgb().ToString("x").ToUpper();

  protected override void OnPaint(PaintEventArgs e)
  {
   base.OnPaint(e);
   e.Graphics.DrawRectangle(new Pen(this.ForeColor),this.area);
 
   for(int i = 1;i < 9;i++)
   {
    e.Graphics.FillRectangle(new SolidBrush(Color.Green),this.GetHandleRect(i));
   }
  }

gfxDisplay.Dispose();
gfxBmp.Dispose();

  private Rectangle GetHandleRect(int index)
  {
   Point point = GetHandle(index);
   return new Rectangle(point.X - 3, point.Y - 3, 6, 6);
  }

bmp.Dispose(); // 释放 bmp 所使用的资源

  private Point GetHandle(int index)
  {
   int x, y, xCenter, yCenter;

}

   xCenter = area.X + area.Width/2;
   yCenter = area.Y + area.Height/2;
   x = area.X;
   y = area.Y;

private void txtArgb_KeyPress(object sender, KeyPressEventArgs e)
{
// 当按下ESC键时,确定所取的颜色ARGB值
// 注意:只有当窗体处于激活状态时才有效
if (e.KeyChar == (char)Keys.Escape)
{
tmr.Enabled = false;
this.Location = formLoc;
this.TopMost = false;
txtArgb.SelectAll();
}
}

   switch ( index )
   {
    case 1:
     x = area.X;
     y = area.Y;
     break;
    case 2:
     x = xCenter;
     y = area.Y;
     break;
    case 3:
     x = area.Right;
     y = area.Y;
     break;
    case 4:
     x = area.Right;
     y = yCenter;
     break;
    case 5:
     x = area.Right;
     y = area.Bottom;
     break;
    case 6:
     x = xCenter;
     y = area.Bottom;
     break;
    case 7:
     x = area.X;
     y = area.Bottom;
     break;
    case 8:
     x = area.X;
     y = yCenter;
     break;
   }

private void Form1_MouseEnter(object sender, EventArgs e)
{
if (this.Location == ptLeftBottom) //窗体在左下角
{
this.Location = ptRightBottom;
}
else if (this.Location == ptRightBottom) // 窗体在右下角
{
this.Location = ptLeftBottom;
}
}
}
}

   return new Point(x, y);
  }

  protected override void OnMouseUp(MouseEventArgs e)
  {
   base.OnMouseUp (e);
   int left = area.Left;
   int top = area.Top;
   int right = area.Right;
   int bottom = area.Bottom;
   area.X = Math.Min(left,right);
   area.Y = Math.Min(top,bottom);
   area.Width = Math.Abs(left-right);
   area.Height = Math.Abs(top-bottom);
   this.tiptext.Text = selectedString;
   if(e.Button == MouseButtons.Right)
   {
    if(this.area == Rectangle.Empty)
    {
     this.Close();
    }
    else
    {
     this.area=Rectangle.Empty;
     this.Invalidate();
    }
   }
   this.index = this.GetSelectedHandle(new Point(e.X,e.Y));
   this.SetCursor();
  }

  private int GetSelectedHandle(Point p)
  {
   int index = -1;
   for(int i = 1;i < 9;i++)
   {
    if(GetHandleRect(i).Contains(p))
    {
     index=i;
     break;
    }
   }
   if(this.area.Contains(p))index = 0;

   return index;
  }

  protected override void OnMouseMove(MouseEventArgs e)
  {
   base.OnMouseMove (e);
   if(this.Capture)
   {
    this.MoveHandleTo(new Point(e.X,e.Y));
    this.Invalidate();
   }
   else
   {
    this.index = this.GetSelectedHandle(new Point(e.X,e.Y));
    this.SetCursor();
   }
  }

  private void MoveHandleTo(Point point)
  {
   int left = area.Left;
   int top = area.Top;
   int right = area.Right;
   int bottom = area.Bottom;

   switch ( index )
   {
    case 0:
     area.X +=point.X - this.pot.X;
     area.Y += point.Y - pot.Y;
     this.pot = point;
     return;
    case 1:
     left = point.X;
     top = point.Y;
     break;
    case 2:
     top = point.Y;
     break;
    case 3:
     right = point.X;
     top = point.Y;
     break;
    case 4:
     right = point.X;
     break;
    case 5:
     right = point.X;
     bottom = point.Y;
     break;
    case 6:
     bottom = point.Y;
     break;
    case 7:
     left = point.X;
     bottom = point.Y;
     break;
    case 8:
     left = point.X;
     break;
   }
   this.pot = point;
   area.X = left;
   area.Y = top;
   area.Width = right - left;
   area.Height = bottom - top;
  }

  private void MouseCaptureForm_DoubleClick(object sender, System.EventArgs e)
  {
   //修正截取图片过界提示内存不足BUG
   int left   =  area.Left;
   int right  =  area.Right;
   int top    =  area.Top;
   int bottom =  area.Bottom;
   if(left < Screen.PrimaryScreen.Bounds.Left)
   {left = Screen.PrimaryScreen.Bounds.Left; }
   if(right > Screen.PrimaryScreen.Bounds.Right )
   {right = Screen.PrimaryScreen.Bounds.Right;}
   if(top < Screen.PrimaryScreen.Bounds.Top)
   {top = Screen.PrimaryScreen.Bounds.Top;}
   if(bottom > Screen.PrimaryScreen.Bounds.Bottom)
   {bottom = Screen.PrimaryScreen.Bounds.Bottom;}
   area.X = left;
   area.Y = top;
   area.Width = right - left;
   area.Height = bottom - top;

   //截取选择区域图片
   Bitmap bm  = new Bitmap(this.BackgroundImage);
   this.img = bm.Clone(this.area,System.Drawing.Imaging.PixelFormat.Format16bppArgb1555);
   CaptureScreenForm.image = img;
   CaptureScreenForm.ActiveForm.Invalidate();
   this.Close();
  }

  private void MouseCaptureForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
  {
   if(e.KeyData == Keys.Escape && System.Windows.Forms.Button.MouseButtons == MouseButtons.Left)
   {
    this.area=Rectangle.Empty;
    this.Invalidate(); 
    tiptext.Text = noselectString;
   }
   else if(e.KeyData == Keys.Escape)
   {this.Close();}
  }

  private void tiptext_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
  {
   if (tiptext.Location.X == 10 && tiptext.Location.Y == 10)
   {
    Point formloc = new Point((Screen.PrimaryScreen.Bounds.Width - 176),10) ;
    tiptext.Location = formloc;
   }
   else
   {tiptext.Location = new Point(10,10);}    
  }

  private void MouseCaptureForm_Load(object sender, System.EventArgs e)
  {
   tiptext.Text = noselectString;
  }
 }
}

本文由10bet手机官网发布于高并发,转载请注明出处:动态获取当前屏幕中光标所在位置的颜色,模仿QQ截图功能

上一篇:织梦DeDeCms列表分页和内容页分页错位解决办法,探秘河北首家人类精子库 下一篇:入门代码,为什么会有use
猜你喜欢
热门排行
精彩图文