【语言-c#】捕获当前鼠标指针,并存成png图片

软件界面 WinForm .NetFramework

运行结果

源码资源

logo.ico

Form1.cs 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing.Imaging;
using System.IO;

namespace MousePointerMonitor
{
    /// <summary>
    /// 
    /// </summary>
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        static extern bool GetCursorInfo(out CURSORINFO pci);
        private const int CURSOR_SHOWING = 0x00000001;
        [StructLayout(LayoutKind.Sequential)]
        struct CURSORINFO
        {
            public int cbSize;
            public int flags;
            public IntPtr hCursor;
            public Point ptScreenPos;
        }
        /// <summary>
        /// 定时器
        /// </summary>
        public Timer timer = new Timer();
        public Form1()
        {
            InitializeComponent();
            timer.Tick += Timer_Tick;
            timer.Interval = 1000;
        }
        /// <summary>
        /// 将图像转化为Base64字符串格式存入字典
        /// </summary>
        public Dictionary<string, string> temps = new Dictionary<string, string>();
        /// <summary>
        /// 定时采集当前鼠标的指针
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Tick(object sender, EventArgs e)
        {
            try
            {
                CURSORINFO vCurosrInfo;
                vCurosrInfo.cbSize = Marshal.SizeOf(typeof(CURSORINFO));
                GetCursorInfo(out vCurosrInfo);
                if ((vCurosrInfo.flags & CURSOR_SHOWING) != CURSOR_SHOWING) return;

                string file = GetDir() + DateTime.Now.ToString("HH_mm_ss") + ".png";
                using (Cursor vCursor = new Cursor(vCurosrInfo.hCursor))
                {
                    using (Bitmap bmp = new Bitmap(vCursor.Size.Width, vCursor.Size.Height))
                    {
                        using (var g = Graphics.FromImage(bmp))
                        {
                            Rectangle vRectangle = new Rectangle(0, 0, vCursor.Size.Width, vCursor.Size.Height);
                            vCursor.Draw(g, vRectangle);
                            string temp = ImgToBase64String(bmp);
                            this.pictureBox1.BackgroundImage = (Bitmap)bmp.Clone();
                            if(temps.ContainsKey(temp) == false)
                            {
                                temps.Add(temp,file);
                                bmp.Save(file, ImageFormat.Png);
                                SetStatus(file + " | " + vCursor.Size.Width + "x" + vCursor.Size.Height);
                            }
                            else
                            {
                                SetStatus("已保存");
                            }
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                SetStatus(exp.Message);
            }
        }
        /// <summary>
        /// 将图像转换为Base64字符串
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public string ImgToBase64String(Bitmap bmp)
        {
            string temp = "";
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] arr = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(arr, 0, (int)ms.Length);
                    ms.Close();
                    temp = Convert.ToBase64String(arr);
                }
            }
            catch (Exception exp)
            {
                SetStatus(exp.Message);
            }
            return temp;
        }
        /// <summary>
        /// 设置状态
        /// </summary>
        /// <param name="message"></param>
        public void SetStatus(string message)
        {
            toolStripStatusLabel1.Text = DateTime.Now.ToString("[yyyy-MM-dd HH:mm:ss]") + " " + message;
        }
        /// <summary>
        /// 采集/停止采集鼠标指针
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button1_Click_1(object sender, EventArgs e)
        {
            try
            {
                if(button1.Text == "启动")
                {
                    button1.Text = "停止";
                    button1.BackColor = System.Drawing.Color.FromArgb(192,255,192);
                    timer.Interval = (int)numericUpDown1.Value * 1000;
                    timer.Start();
                    SetStatus("正在启动");
                }
                else
                {
                    button1.BackColor = System.Drawing.Color.FromArgb(255,192,192);
                    button1.Text = "启动";
                    timer.Stop();
                    SetStatus("已停止");
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
        }
        /// <summary>
        /// 获取采集图像存放路径
        /// </summary>
        /// <returns></returns>
        public string GetDir()
        {
           string path = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString("yyyy-MM-dd");
            if(System.IO.Directory.Exists(path) == false)
            {
                System.IO.Directory.CreateDirectory(path);
            }
            return path + "\\";
        }
        /// <summary>
        /// 打开存放采集鼠标指针的文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("Explorer.exe", GetDir());
        }
        /// <summary>
        /// 清空文件夹的文件和缓存字典
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (button1.Text == "停止")
                {
                    MessageBox.Show("正在采集,请先停止!");
                    return;
                }
                SetStatus("正在清空");

                System.IO.DirectoryInfo directoryInfo = new DirectoryInfo(GetDir());
                var files = directoryInfo.GetFiles();
                int i = 1;
                foreach (var file in files)
                {
                    if (file.Exists)
                    {
                        try
                        {
                            System.IO.File.Delete(file.FullName);
                            SetStatus(i + "、已删除 " + file.Name);
                        }
                        catch (Exception exp)
                        {
                            SetStatus(exp.Message);
                        }
                            i++;
                    }
                }
                temps.Clear();
                SetStatus("清空完成!");
            }
            catch (Exception exp)
            {
                SetStatus(exp.Message);
            }
        }
        /// <summary>
        /// 将窗体置顶/取消置顶
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button4_Click(object sender, EventArgs e)
        {
            if (button4.Text == "置顶")
            {
                button4.Text = "取消置顶";
                this.TopMost = true;
            }
            else
            {
                button4.Text = "置顶";
                this.TopMost = false;
            }
        }
    }
}

Form1.Designer.cs

namespace MousePointerMonitor
{
    partial class Form1
    {
        /// <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()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.button1 = new System.Windows.Forms.Button();
            this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
            this.button2 = new System.Windows.Forms.Button();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.button3 = new System.Windows.Forms.Button();
            this.button4 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
            this.statusStrip1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // button1
            // 
            this.button1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
            this.button1.Location = new System.Drawing.Point(169, 28);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(64, 23);
            this.button1.TabIndex = 0;
            this.button1.Text = "启动";
            this.button1.UseVisualStyleBackColor = false;
            this.button1.Click += new System.EventHandler(this.Button1_Click_1);
            // 
            // numericUpDown1
            // 
            this.numericUpDown1.Location = new System.Drawing.Point(89, 29);
            this.numericUpDown1.Maximum = new decimal(new int[] {
            60,
            0,
            0,
            0});
            this.numericUpDown1.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.numericUpDown1.Name = "numericUpDown1";
            this.numericUpDown1.Size = new System.Drawing.Size(64, 21);
            this.numericUpDown1.TabIndex = 1;
            this.numericUpDown1.Value = new decimal(new int[] {
            1,
            0,
            0,
            0});
            // 
            // button2
            // 
            this.button2.Location = new System.Drawing.Point(249, 28);
            this.button2.Name = "button2";
            this.button2.Size = new System.Drawing.Size(64, 23);
            this.button2.TabIndex = 0;
            this.button2.Text = "打开";
            this.button2.UseVisualStyleBackColor = true;
            this.button2.Click += new System.EventHandler(this.Button2_Click);
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripStatusLabel1});
            this.statusStrip1.Location = new System.Drawing.Point(0, 88);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(491, 22);
            this.statusStrip1.TabIndex = 2;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // toolStripStatusLabel1
            // 
            this.toolStripStatusLabel1.Name = "toolStripStatusLabel1";
            this.toolStripStatusLabel1.Size = new System.Drawing.Size(0, 17);
            // 
            // pictureBox1
            // 
            this.pictureBox1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
            this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.pictureBox1.Location = new System.Drawing.Point(12, 12);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(64, 64);
            this.pictureBox1.TabIndex = 3;
            this.pictureBox1.TabStop = false;
            // 
            // button3
            // 
            this.button3.Location = new System.Drawing.Point(329, 28);
            this.button3.Name = "button3";
            this.button3.Size = new System.Drawing.Size(64, 23);
            this.button3.TabIndex = 4;
            this.button3.Text = "清空";
            this.button3.UseVisualStyleBackColor = true;
            this.button3.Click += new System.EventHandler(this.Button3_Click);
            // 
            // button4
            // 
            this.button4.Location = new System.Drawing.Point(415, 29);
            this.button4.Name = "button4";
            this.button4.Size = new System.Drawing.Size(64, 23);
            this.button4.TabIndex = 0;
            this.button4.Text = "置顶";
            this.button4.UseVisualStyleBackColor = true;
            this.button4.Click += new System.EventHandler(this.Button4_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(491, 110);
            this.Controls.Add(this.button3);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.numericUpDown1);
            this.Controls.Add(this.button4);
            this.Controls.Add(this.button2);
            this.Controls.Add(this.button1);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "Form1";
            this.Text = "鼠标指针抓取小工具";
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.NumericUpDown numericUpDown1;
        private System.Windows.Forms.Button button2;
        private System.Windows.Forms.StatusStrip statusStrip1;
        private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.Button button3;
        private System.Windows.Forms.Button button4;
    }
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值