c#截屏的代码

作者&投稿:长孙妹 (若有异议请与网页底部的电邮联系)
怎么用c#窗体做截屏功能 求代码~

/// /// 截取窗体内任意位置成图片,自动保存到项目Play文件夹中img.jpg文件. /// /// 开始位置X坐标 /// 开始位置Y坐标 /// 图片大小宽度 /// 图片大小高度 private void SubPictureAutoSave(int location_X, int location_Y, int size_X, int size_Y) { Bitmap bitSize = new Bitmap(size_X, size_Y); Graphics g = Graphics.FromImage(bitSize); Point pl = new Point(this.Location.X + location_X, this.Location.Y + location_Y); g.CopyFromScreen(pl, new Point(0, 0), bitSize.Size); bitSize.Save(Application.StartupPath + "\\PlayImg\\img.jpg"); g.Dispose(); } /// /// 截取窗体内任意位置,另存为图片. /// /// 开始位置X坐标 /// 开始位置Y坐标 /// 图片大小宽度 /// 图片大小高度 private void SubPictureSaveAs(int location_X, int location_Y, int size_X, int size_Y) { Bitmap bitSize = new Bitmap(size_X, size_Y); Graphics g = Graphics.FromImage(bitSize); Point pl = new Point(this.Location.X + location_X, this.Location.Y + location_Y); g.CopyFromScreen(pl, new Point(0, 0), bitSize.Size); SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "jpg|*.jpg|bmp|*.bmp|gif|*.gif"; saveFileDialog.FileName = "img" + DateTime.Now.ToString("yyyyMMddHHmmss"); if (saveFileDialog.ShowDialog() != DialogResult.Cancel) { bitSize.Save(saveFileDialog.FileName); } g.Dispose(); }

QQ截图的核心其实就是调用WINDOWS API函数,主要涉及两个核心组件, user32.dll和gdi32.dll。
如下是,C#代码调用上述两个核心组件的完整示例:
namespace WindowsFormsApplication1{ /// /// 屏幕捕获类 /// public class ScreenCapture { /// /// 创建一个包含整个桌面的截图Image对象(捕获到的桌面是当前WINDOWS操作系统活动桌面) /// /// public Image CaptureScreen() { return CaptureWindow(User32.GetDesktopWindow()); } /// /// 创建一个包含特定窗口的截图Image对象 /// /// 启动本程序的句柄窗口(在Windows上这是由Handle属性获得) /// public Image CaptureWindow(IntPtr handle) { // 获取目标窗口的HDC IntPtr hdcSrc = User32.GetWindowDC(handle); // 获取它的大小 User32.RECT windowRect = new User32.RECT(); User32.GetWindowRect(handle, ref windowRect); int width = windowRect.right - windowRect.left; int height = windowRect.bottom - windowRect.top; // 创建设备上下文对象 IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc); IntPtr hBitmap = GDI32.CreateCompatibleBitmap(hdcSrc, width, height); IntPtr hOld = GDI32.SelectObject(hdcDest, hBitmap); GDI32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, GDI32.SRCCOPY); GDI32.SelectObject(hdcDest, hOld); GDI32.DeleteDC(hdcDest); User32.ReleaseDC(handle, hdcSrc); Image img = Image.FromHbitmap(hBitmap); GDI32.DeleteObject(hBitmap); return img; } /// /// 获取特定窗口,并保存它 /// /// /// /// public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format) { Image img = CaptureWindow(handle); img.Save(filename, format); } /// /// 捕获整个windows活动窗口并保存它 /// /// /// public void CaptureScreenToFile(string filename, ImageFormat format) { Image img = CaptureScreen(); img.Save(filename, format); } /// /// GDI32 相关的API函数 /// private class GDI32 { public const int SRCCOPY = 0x00CC0020; [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hObjectSource, int nXSrc, int nYSrc, int dwRop); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); } /// /// User32 API相关函数 /// private class User32 { [StructLayout(LayoutKind.Sequential)] public struct RECT { public int left; public int top; public int right; public int bottom; } [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("user32.dll")] public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect); } }}// 调用示例:private void button1_Click(object sender, EventArgs e) { ScreenCapture sc = new ScreenCapture(); // 捕获整个屏幕并保存到一个文件里 Image img = sc.CaptureScreen(); // 将捕获的图片显示在图片控件里 this.pictureBox1.Image = img; // 捕获当前运行窗体并保存在C盘,文件名和后缀为temp.png sc.CaptureWindowToFile(this.Handle, "C:\emp.png", ImageFormat.Gif); }

下面的代码可以设置放置路径 根据鼠标的点击来截图 快捷键shift+f
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
namespace GetScreen
{
public partial class Frm_Main : Form
{
public Frm_Main()
{
InitializeComponent();
}
private int _X, _Y;
[StructLayout(LayoutKind.Sequential)]
private struct ICONINFO
{
public bool fIcon;
public Int32 xHotspot;
public Int32 yHotspot;
public IntPtr hbmMask;
public IntPtr hbmColor;
}
[StructLayout(LayoutKind.Sequential)]
private struct CURSORINFO
{
public Int32 cbSize;
public Int32 flags;
public IntPtr hCursor;
public Point ptScreenPos;
}
[DllImport("user32.dll", EntryPoint = "GetSystemMetrics")]
private static extern int GetSystemMetrics(int mVal);
[DllImport("user32.dll", EntryPoint = "GetCursorInfo")]
private static extern bool GetCursorInfo(ref CURSORINFO cInfo);
[DllImport("user32.dll", EntryPoint = "CopyIcon")]
private static extern IntPtr CopyIcon(IntPtr hIcon);
[DllImport("user32.dll", EntryPoint = "GetIconInfo")]
private static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO iInfo);
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retval,int size,string filePath);

#region 定义快捷键
//如果函数执行成功,返回值不为0。
//如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。
[DllImport("user32.dll", SetLastError = true)]
public static extern bool RegisterHotKey(
IntPtr hWnd, //要定义热键的窗口的句柄
int id, //定义热键ID(不能与其它ID重复)
KeyModifiers fsModifiers, //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效
Keys vk //定义热键的内容
);
[DllImport("user32.dll", SetLastError = true)]
public static extern bool UnregisterHotKey(
IntPtr hWnd, //要取消热键的窗口的句柄
int id //要取消热键的ID
);
//定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值)
[Flags()]
public enum KeyModifiers
{
None = 0,
Alt = 1,
Ctrl = 2,
Shift = 4,
WindowsKey = 8
}
#endregion

public string path;
public void IniWriteValue(string section, string key, string value)
{
WritePrivateProfileString(section,key,value,path);
}
public string IniReadValue(string section, string key)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(section,key,"",temp,255,path);
return temp.ToString();
}

private Bitmap CaptureNoCursor()//抓取没有鼠标的桌面
{
Bitmap _Source = new Bitmap(GetSystemMetrics(0), GetSystemMetrics(1));
using (Graphics g = Graphics.FromImage(_Source))
{
g.CopyFromScreen(0, 0, 0, 0, _Source.Size);
g.Dispose();
}
return _Source;
}

private Bitmap CaptureDesktop()//抓取带鼠标的桌面
{
try
{
int _CX = 0, _CY = 0;
Bitmap _Source = new Bitmap(GetSystemMetrics(0), GetSystemMetrics(1));
using (Graphics g = Graphics.FromImage(_Source))
{

g.CopyFromScreen(0, 0, 0, 0, _Source.Size);
g.DrawImage(CaptureCursor(ref _CX, ref _CY), _CX, _CY);
g.Dispose();
}
_X = (800 - _Source.Width) / 2;
_Y = (600 - _Source.Height) / 2;
return _Source;
}
catch
{
return null;
}
}

private Bitmap CaptureCursor(ref int _CX, ref int _CY)
{
IntPtr _Icon;
CURSORINFO _CursorInfo = new CURSORINFO();
ICONINFO _IconInfo;
_CursorInfo.cbSize = Marshal.SizeOf(_CursorInfo);
if (GetCursorInfo(ref _CursorInfo))
{
if (_CursorInfo.flags == 0x00000001)
{
_Icon = CopyIcon(_CursorInfo.hCursor);

if (GetIconInfo(_Icon, out _IconInfo))
{
_CX = _CursorInfo.ptScreenPos.X - _IconInfo.xHotspot;
_CY = _CursorInfo.ptScreenPos.Y - _IconInfo.yHotspot;
return Icon.FromHandle(_Icon).ToBitmap();
}
}
}
return null;
}

string Cursor;
string PicPath;
private void button1_Click(object sender, EventArgs e)
{
try
{
path = Application.StartupPath.ToString();
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
path += @"\Setup.ini";
if (checkBox1.Checked == true)
{
Cursor = "1";
}
else
{
Cursor = "0";
}
if (txtSavaPath.Text == "")
{
PicPath = @"D:\";
}
else
{
PicPath = txtSavaPath.Text.Trim();
}
IniWriteValue("Setup", "CapMouse", Cursor);
IniWriteValue("Setup", "Dir", PicPath);
MessageBox.Show("保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message,"警告",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}

private void button2_Click(object sender, EventArgs e)
{
this.Hide();
}

private void button3_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
txtSavaPath.Text = folderBrowserDialog1.SelectedPath;
}
}

private void Form1_StyleChanged(object sender, EventArgs e)
{
RegisterHotKey(Handle, 81, KeyModifiers.Shift, Keys.F);
}
public bool flag=true;
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
//注销Id号为81的热键设定
UnregisterHotKey(Handle, 81);
timer1.Stop();
flag = false;
Application.Exit();
}

string MyCursor;
string MyPicPath;
private void Form1_Activated(object sender, EventArgs e)
{
RegisterHotKey(Handle, 81, KeyModifiers.Shift, Keys.F);
path = Application.StartupPath.ToString();
path = path.Substring(0, path.LastIndexOf("\\"));
path = path.Substring(0, path.LastIndexOf("\\"));
path += @"\Setup.ini";
MyCursor = IniReadValue("Setup", "CapMouse");
MyPicPath = IniReadValue("Setup", "Dir");
if (MyCursor == "" || MyPicPath == "")
{
checkBox1.Checked = true;
txtSavaPath.Text = @"D:\";
}
else
{
if (MyCursor == "1")
{
checkBox1.Checked = true;
}
else
{
checkBox1.Checked = false;
}
txtSavaPath.Text = MyPicPath;
}
}

private void getImg()
{
DirectoryInfo di = new DirectoryInfo(MyPicPath);
if (!di.Exists)
{
Directory.CreateDirectory(MyPicPath);
}
if (MyPicPath.Length == 3)
MyPicPath = MyPicPath.Remove(MyPicPath.LastIndexOf(":")+1);
string PicPath = MyPicPath+"\\IMG_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + ".bmp";
Bitmap bt;
if (MyCursor=="0")
{
bt = CaptureNoCursor();
bt.Save(PicPath);
}
else
{
bt = CaptureDesktop();
bt.Save(PicPath);
}
}

protected override void WndProc(ref Message m)
{
const int WM_HOTKEY = 0x0312;
//按快捷键
switch (m.Msg)
{
case WM_HOTKEY:
switch (m.WParam.ToInt32())
{
case 81: //按下的是Shift+Q
getImg();
break;
}
break;
}
base.WndProc(ref m);
}

private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)//双击显示设置窗体
{
this.Show();
}

private void 设置ToolStripMenuItem_Click(object sender, EventArgs e)//单击设置打开设置窗体
{
this.Show();
}

private void timer1_Tick(object sender, EventArgs e)
{
RegisterHotKey(Handle, 81, KeyModifiers.Shift, Keys.F);
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
if (flag == true)
{
e.Cancel = true;
}
}

private void Form1_Load(object sender, EventArgs e)
{

}
}
}


大悟县17759385942: C#求截屏代码 -
汗厚艾力: win32 api Bitblt

大悟县17759385942: 怎么用c#窗体做截屏功能 求代码 -
汗厚艾力: /// 截取窗体内任意位置成图片,自动保存到项目Play文件夹中img.jpg文件. ////// 开始位置X坐标 /// 开始位置Y坐标 /// 图片大小宽度 /// 图片大小高度 private void SubPictureAutoSave(int location_X, int location_Y, int size_X, int size_Y) { Bitmap ...

大悟县17759385942: 如何用C#.NET做屏幕截图软件 -
汗厚艾力: 学以致用~powered by 25175.net 用C#做屏幕截图,大致有三种方法. 1、最managed大概就是使用Graphics.CopyFromScreen()方法,此方法有四个重载,不过经反编可见最后调用的都是:CopyFromScreen(int sourceX, int ...

大悟县17759385942: C#窗体截屏功能?求大神指导 求代码 -
汗厚艾力: using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //获得...

大悟县17759385942: 再C#中QQ截图的代码怎么写 -
汗厚艾力: QQ截图的核心其实就是调用WINDOWS API函数,主要涉及两个核心组件, user32.dll和gdi32.dll.如下是,C#代码调用上述两个核心组件的完整示例:namespace WindowsFormsApplication1 { /// <summary> /// 屏幕捕获类/// </summary> ...

大悟县17759385942: 用c#绘图板中的截图怎么做? -
汗厚艾力: Image myImg = new Bitmap(Screen.AllScreens[0].Bounds.Width, Screen.AllScreens[0].Bounds.Height); Graphics g = Graphics.FromImage(myImg); g.CopyFromScreen(new Poi...

大悟县17759385942: C# 调用 API 截图的 -
汗厚艾力: 截屏是吧??C#可以直接截屏不需要API,下面给出答案:Bitmap bit = new Bitmap(Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height); Graphics g = Graphics.FromImage(bit); g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.WorkingArea.Size);//bit就是截屏得到的图片了

大悟县17759385942: 如何用C#给当前窗体截图,并显示到一个图片框中?(不需要连续截图) -
汗厚艾力: 截当前窗体的根据你的FORM改一下坐标/// <summary>/// 获取整个屏幕的图片/// </summary>/// <returns></returns>public static Image GetScreenImage(){Image image = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen....

大悟县17759385942: C#如何截取当前程序窗口的截图 -
汗厚艾力: |Bitmap bit = new Bitmap(this.Width, this.Height); Graphics g = Graphics.FromImage(bit); g.CopyFromScreen(new Point(this.Location.X,this.Location.Y), new Point(0, 0), bit.Size); SaveFileDialog saveFileDialog = new SaveFileDialog(); ...

大悟县17759385942: 谁会C# B/S模式下实现截图功能 有源码最好 有用果断给分! -
汗厚艾力: 截屏//创建和屏幕同宽 高的位图 Image myImage=new Bitmap(width,height); //创建Graphics对象 Graphics myGraphics=Graphics.FromImage(myImage); myGraphics.CopyFromScreen(new Point(pointX, pointY), new Point(0, 0),myImage.Size); myImage.Image.Save 方法 (Stream, ImageFormat)保存到内存流 读取内存流到 byte[] socket 传输 byte[]到客户端

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 星空见康网