c#获取鼠标位置的颜色

基本思路:

由于从DC中获取颜色的方法有一定的问题,有些情况下不能很好的支持。所以采用图像的方式。

1、从屏幕上获取屏幕的图像。

2、从图像上获取坐标点的颜色。

话不多说,直接上代码。

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

        private void button1_Click(object sender, EventArgs e)
        {
            timer1_Tick(sender, e);
        }

        [DllImport("gdi32.dll")]//取指定点颜色
        private static extern int GetPixel(IntPtr hdc, Point p);


        private void timer1_Tick(object sender, EventArgs e)
        {

            //把坐标显示到窗口上
            Xvalue.Text = MousePosition.X.ToString();
            Yvalue.Text = MousePosition.Y.ToString();

            Size s = new Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Bitmap memoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics memoryGraphics = Graphics.FromImage(memoryImage);
            memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
            Color cl = memoryImage.GetPixel(MousePosition.X, MousePosition.Y);
            
            Colorvalue.Text = "#" + cl.R.ToString("X").PadLeft(2, '0') + cl.G.ToString("X").PadLeft(2, '0') + cl.B.ToString("X").PadLeft(2, '0');//输出16进制颜色
            RGBvalue.Text = cl.R.ToString() + ',' + cl.G.ToString() + ',' + cl.B.ToString();//输出RGB
            //设置颜色框
            pictureBox1.BackColor = cl;
            //pictureBox1.Image = memoryImage;
            //ReleaseDC(IntPtr.Zero, hdc);
            memoryGraphics.Dispose();
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值