C#实现屏幕抓图并保存的示例代码

.NET
263
0
0
2023-07-01
标签   C#
目录
  • 实践过程
  • 效果
  • 代码

实践过程

效果

代码

public partial class Form : Form
{
    public Form()
    {
        InitializeComponent();
    }

    private int _X, _Y;

    [StructLayout(LayoutKind.Sequential)]
    private struct ICONINFO
    {
        public bool fIcon;
        public Int xHotspot;
        public Int yHotspot;
        public IntPtr hbmMask;
        public IntPtr hbmColor;
    }

    [StructLayout(LayoutKind.Sequential)]
    private struct CURSORINFO
    {
        public Int cbSize;
        public Int flags;
        public IntPtr hCursor;
        public Point ptScreenPos;
    }

    [DllImport("user.dll", EntryPoint = "GetSystemMetrics")]
    private static extern int GetSystemMetrics(int mVal);

    [DllImport("user.dll", EntryPoint = "GetCursorInfo")]
    private static extern bool GetCursorInfo(ref CURSORINFO cInfo);

    [DllImport("user.dll", EntryPoint = "CopyIcon")]
    private static extern IntPtr CopyIcon(IntPtr hIcon);

    [DllImport("user.dll", EntryPoint = "GetIconInfo")]
    private static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO iInfo);

    [DllImport("kernel")]
    private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

    [DllImport("kernel")]
    private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retval,
        int size, string filePath);

    #region 定义快捷键

    //如果函数执行成功,返回值不为。       
    //如果函数执行失败,返回值为。要得到扩展错误信息,调用GetLastError。        
    [DllImport("user.dll", SetLastError = true)]
    public static extern bool RegisterHotKey(
        IntPtr hWnd, //要定义热键的窗口的句柄            
        int id, //定义热键ID(不能与其它ID重复)                       
        KeyModifiers fsModifiers, //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效         
        Keys vk //定义热键的内容            
    );

    [DllImport("user.dll", SetLastError = true)]
    public static extern bool UnregisterHotKey(
        IntPtr hWnd, //要取消热键的窗口的句柄            
        int id //要取消热键的ID            
    );

    //定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值)        
    [Flags()]
    public enum KeyModifiers
    {
        None =,
        Alt =,
        Ctrl =,
        Shift =,
        WindowsKey =
    }

    #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();
        int i = GetPrivateProfileString(section, key, "", temp,, path);
        return temp.ToString();
    }

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

        return _Source;
    }


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

            _X = ( - _Source.Width) / 2;
            _Y = ( - _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 ==x00000001)
            {
                _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 button_Click(object sender, EventArgs e)
    {
        try
        {
            path = Application.StartupPath.ToString();
            path = path.Substring(, path.LastIndexOf("\\"));
            path = path.Substring(, path.LastIndexOf("\\"));
            path += @"\Setup.ini";
            if (checkBox.Checked == true)
            {
                Cursor = "";
            }
            else
            {
                Cursor = "";
            }

            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 button_Click(object sender, EventArgs e)
    {
        this.Hide();
    }

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

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

    public bool flag = true;

    private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
    {
        //注销Id号为的热键设定    
        UnregisterHotKey(Handle,);
        timer.Stop();
        flag = false;
        Application.Exit();
    }

    string MyCursor;
    string MyPicPath;

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

            txtSavaPath.Text = MyPicPath;
        }
    }

    private void getImg()
    {
        DirectoryInfo di = new DirectoryInfo(MyPicPath);
        if (!di.Exists)
        {
            Directory.CreateDirectory(MyPicPath);
        }

        if (MyPicPath.Length ==)
            MyPicPath = MyPicPath.Remove(MyPicPath.LastIndexOf(":") +);
        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 == "")
        {
            bt = CaptureNoCursor();
            bt.Save(PicPath);
        }
        else
        {
            bt = CaptureDesktop();
            bt.Save(PicPath);
        }
    }

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

                break;
        }

        base.WndProc(ref m);
    }

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

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

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

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

    private void Form_Load(object sender, EventArgs e)
    {
    }
}
partial class Form
{
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows 窗体设计器生成的代码

    /// <summary>
    /// 设计器支持所需的方法 - 不要
    /// 使用代码编辑器修改此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form));
        this.button = new System.Windows.Forms.Button();
        this.button = new System.Windows.Forms.Button();
        this.groupBox = new System.Windows.Forms.GroupBox();
        this.button = new System.Windows.Forms.Button();
        this.txtSavaPath = new System.Windows.Forms.TextBox();
        this.label = new System.Windows.Forms.Label();
        this.checkBox = new System.Windows.Forms.CheckBox();
        this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
        this.notifyIcon = new System.Windows.Forms.NotifyIcon(this.components);
        this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
        this.设置ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
        this.退出ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
        this.timer = new System.Windows.Forms.Timer(this.components);
        this.groupBox.SuspendLayout();
        this.contextMenuStrip.SuspendLayout();
        this.SuspendLayout();
        // 
        // button
        // 
        this.button.Location = new System.Drawing.Point(82, 91);
        this.button.Name = "button1";
        this.button.Size = new System.Drawing.Size(75, 23);
        this.button.TabIndex = 2;
        this.button.Text = "保存设置";
        this.button.UseVisualStyleBackColor = true;
        this.button.Click += new System.EventHandler(this.button1_Click);
        // 
        // button
        // 
        this.button.Location = new System.Drawing.Point(163, 91);
        this.button.Name = "button2";
        this.button.Size = new System.Drawing.Size(75, 23);
        this.button.TabIndex = 3;
        this.button.Text = "关闭";
        this.button.UseVisualStyleBackColor = true;
        this.button.Click += new System.EventHandler(this.button2_Click);
        // 
        // groupBox
        // 
        this.groupBox.Controls.Add(this.button3);
        this.groupBox.Controls.Add(this.txtSavaPath);
        this.groupBox.Controls.Add(this.label1);
        this.groupBox.Controls.Add(this.checkBox1);
        this.groupBox.Location = new System.Drawing.Point(13, 14);
        this.groupBox.Name = "groupBox1";
        this.groupBox.Size = new System.Drawing.Size(301, 71);
        this.groupBox.TabIndex = 5;
        this.groupBox.TabStop = false;
        this.groupBox.Text = "功能设置";
        // 
        // button
        // 
        this.button.Location = new System.Drawing.Point(257, 42);
        this.button.Name = "button3";
        this.button.Size = new System.Drawing.Size(35, 23);
        this.button.TabIndex = 3;
        this.button.Text = "...";
        this.button.UseVisualStyleBackColor = true;
        this.button.Click += new System.EventHandler(this.button3_Click);
        // 
        // txtSavaPath
        // 
        this.txtSavaPath.BackColor = System.Drawing.Color.White;
        this.txtSavaPath.Location = new System.Drawing.Point(, 44);
        this.txtSavaPath.Name = "txtSavaPath";
        this.txtSavaPath.ReadOnly = true;
        this.txtSavaPath.Size = new System.Drawing.Size(, 21);
        this.txtSavaPath.TabIndex =;
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(9, 49);
        this.label.Name = "label1";
        this.label.Size = new System.Drawing.Size(65, 12);
        this.label.TabIndex = 1;
        this.label.Text = "存放目录:";
        // 
        // checkBox
        // 
        this.checkBox.AutoSize = true;
        this.checkBox.Location = new System.Drawing.Point(11, 20);
        this.checkBox.Name = "checkBox1";
        this.checkBox.Size = new System.Drawing.Size(198, 16);
        this.checkBox.TabIndex = 0;
        this.checkBox.Text = "抓取鼠标(抓图快捷键为Shift+F)";
        this.checkBox.UseVisualStyleBackColor = true;
        // 
        // notifyIcon
        // 
        this.notifyIcon.ContextMenuStrip = this.contextMenuStrip1;
        this.notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
        this.notifyIcon.Text = "啸天屏幕抓图";
        this.notifyIcon.Visible = true;
        this.notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.notifyIcon1_MouseDoubleClick);
        // 
        // contextMenuStrip
        // 
        this.contextMenuStrip.AutoSize = false;
        this.contextMenuStrip.BackColor = System.Drawing.Color.White;
        this.contextMenuStrip.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
        this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
        this.设置ToolStripMenuItem,
        this.退出ToolStripMenuItem});
        this.contextMenuStrip.Name = "contextMenuStrip1";
        this.contextMenuStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional;
        this.contextMenuStrip.ShowImageMargin = false;
        this.contextMenuStrip.ShowItemToolTips = false;
        this.contextMenuStrip.Size = new System.Drawing.Size(50, 55);
        // 
        // 设置ToolStripMenuItem
        // 
        this.设置ToolStripMenuItem.AutoSize = false;
        this.设置ToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
        this.设置ToolStripMenuItem.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)()))), ((int)(((byte)(128)))), ((int)(((byte)(255)))));
        this.设置ToolStripMenuItem.Name = "设置ToolStripMenuItem";
        this.设置ToolStripMenuItem.Size = new System.Drawing.Size(, 22);
        this.设置ToolStripMenuItem.Text = "设置";
        this.设置ToolStripMenuItem.Click += new System.EventHandler(this.设置ToolStripMenuItem_Click);
        // 
        // 退出ToolStripMenuItem
        // 
        this.退出ToolStripMenuItem.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
        this.退出ToolStripMenuItem.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
        this.退出ToolStripMenuItem.Name = "退出ToolStripMenuItem";
        this.退出ToolStripMenuItem.Size = new System.Drawing.Size(, 22);
        this.退出ToolStripMenuItem.Text = "退出";
        this.退出ToolStripMenuItem.Click += new System.EventHandler(this.退出ToolStripMenuItem_Click);
        // 
        // timer
        // 
        this.timer.Enabled = true;
        this.timer.Tick += new System.EventHandler(this.timer1_Tick);
        // 
        // Form
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(, 123);
        this.Controls.Add(this.groupBox);
        this.Controls.Add(this.button);
        this.Controls.Add(this.button);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Name = "Form";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "屏幕抓图";
        this.StyleChanged += new System.EventHandler(this.Form_StyleChanged);
        this.Load += new System.EventHandler(this.Form_Load);
        this.Activated += new System.EventHandler(this.Form_Activated);
        this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form_FormClosing);
        this.groupBox.ResumeLayout(false);
        this.groupBox.PerformLayout();
        this.contextMenuStrip.ResumeLayout(false);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.Button button;
    private System.Windows.Forms.Button button;
    private System.Windows.Forms.GroupBox groupBox;
    private System.Windows.Forms.TextBox txtSavaPath;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.CheckBox checkBox;
    private System.Windows.Forms.Button button;
    private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog;
    private System.Windows.Forms.NotifyIcon notifyIcon;
    private System.Windows.Forms.ContextMenuStrip contextMenuStrip;
    private System.Windows.Forms.ToolStripMenuItem 设置ToolStripMenuItem;
    private System.Windows.Forms.ToolStripMenuItem 退出ToolStripMenuItem;
    private System.Windows.Forms.Timer timer;
}