C# 模拟PrintScreen 和 Alt+PrintScreen截取屏幕图片
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace PrintScreen { public partial class Form1 : Form { [DllImport("user32.dll")] static extern void keybd_event ( byte bVk,// 虚拟键值 byte bScan,// 硬件扫描码 uint dwFlags,// 动作标识 IntPtr dwExtraInfo// 与键盘动作关联的辅加信息 ); /// <summary> /// 模拟Print Screen键盘消息,截取全屏图片。 /// </summary> public void PrintScreen() { keybd_event((byte)0x2c, 0, 0x0, IntPtr.Zero);//down Application.DoEvents(); keybd_event((byte)0x2c, 0, 0x2, IntPtr.Zero);//up Application.DoEvents(); } /// <summary> /// 模拟Alt Print Screen键盘消息,截取当前窗口图片。 /// </summary> public void AltPrintScreen() { keybd_event((byte)Keys.Menu, 0, 0x0, IntPtr.Zero); keybd_event((byte)0x2c, 0, 0x0, IntPtr.Zero);//down Application.DoEvents(); Application.DoEvents(); keybd_event((byte)0x2c, 0, 0x2, IntPtr.Zero);//up keybd_event((byte)Keys.Menu, 0, 0x2, IntPtr.Zero); Application.DoEvents(); Application.DoEvents(); } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } /// <summary> /// 从剪贴板获取图片 /// </summary> /// <returns></returns> private Bitmap GetScreenImage() { IDataObject newobject = null; Bitmap NewBitmap = null; try { Application.DoEvents(); newobject = Clipboard.GetDataObject(); if (Clipboard.ContainsImage()) { NewBitmap = (Bitmap)(Clipboard.GetImage().Clone()); } return NewBitmap; } catch(Exception ex) { Console.WriteLine(ex.Message); return null; } } private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; pictureBox1.Image = null; PrintScreen(); pictureBox1.Image = GetScreenImage(); button1.Enabled = true; Application.DoEvents(); } private void button2_Click(object sender, EventArgs e) { button2.Enabled = false; pictureBox1.Image = null; AltPrintScreen(); pictureBox1.Image = GetScreenImage(); button2.Enabled = true; Application.DoEvents(); } } }
PrintScreen没有任务问题,但使用AltPrintScreen时第一次总是不能得到正确的图片,不知道是为什么!希望高手路过指点一二,小弟不胜感激!