【WinForm】实现拾色功能

    今天在一个群里有人问道画图软件中的拾色功能()是怎么实现的。我只提供了一个简单思路。

    总共有两种思路。

    思路一:用GDI截取桌面图片之后,用一个无边框窗体显示出来。再通过鼠标事件获取到点击位置,就可以获取到相应的颜色值。

    思路二:不用假窗体。直接注册一个底层钩子监视鼠标。再获取到相应位置的颜色。(可能会被视为病毒行为)

    第一个思路实现起来要简单一点。第二个思路实现之后,在拾色的时候还能够与应用交互。

    这里把第一种思路的代码贴出。

using System.Drawing;
using System.Windows.Forms;

namespace ColorPickerDemo
{
    public class PickColorForm : Form
    {
        public PickColorForm()
        {
            Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.CopyFromScreen(0, 0, 0, 0, bmp.Size);
            }

            this.FormBorderStyle = FormBorderStyle.None;
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);

            this.DesktopLocation = new Point(0, 0);
            this.Size = bmp.Size;
            this.Cursor = Cursors.Cross;
            this.MouseUp += (ss, ee) =>
            {
                if (ee.Button == MouseButtons.Left)
                {
                    this.Color = bmp.GetPixel(ee.X, ee.Y);
                    this.DialogResult = DialogResult.OK;
                }
                else
                {
                    Color = null;
                    this.DialogResult = DialogResult.Cancel;
                }
                this.Close();
            };
            this.KeyDown += (ss, ee) =>
            {
                if (ee.KeyCode == Keys.Escape)
                    this.Close();
            };

            this.BackgroundImage = bmp;
        }

        public Color? Color { get; private set; }
    }
}

调用方法:

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            PickColorForm f = new PickColorForm();
            if (f.ShowDialog() == DialogResult.OK)
            {
                this.BackColor = f.Color.Value;
            }
        }

PS:今晚无聊才写的,所以文章内容很简单。如果不太懂,可以留言。

什么时候若是把思路二给实现了,会更新此博文。

原文地址:https://www.cnblogs.com/Aimeast/p/2134266.html