2016年10月24日 星期一

[C#] [WinForm] 取得Form1上滑鼠移動座標、Click座標、顏色

[C#] [WinForm] 取得Form1上滑鼠移動座標、Click座標、顏色

2016-10-24

使用 Visual Studio 2015 with Update 3

Form1.cs 內容

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MouseGetPosition
{
    public partial class Form1 : Form
    {
        [DllImport("gdi32")]
        private static extern int GetPixel(IntPtr hdc, int x, int y);
        [DllImport("User32")]
        private static extern IntPtr GetWindowDC(IntPtr hwnd);
        public Form1()
        {
            InitializeComponent();
            //p1 = new Point(0, 0);
            //p2 = (Point)this.ClientSize;
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            label2.Text = "Move : " +  System.Windows.Forms.Cursor.Position.X + ", " + System.Windows.Forms.Cursor.Position.Y;
        }
        public static System.Drawing.Color GetPixelAtCursor()
        {
            System.Drawing.Point p = Cursor.Position;
            return System.Drawing.Color.FromArgb(GetPixel(GetWindowDC(IntPtr.Zero), p.X, p.Y));
        }
        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            label1.Text = "Click : " + System.Windows.Forms.Cursor.Position.X + ", " + System.Windows.Forms.Cursor.Position.Y;
            string colorString = GetPixelAtCursor().ToString();
            Color backX = GetPixelAtCursor();
            label3.Text = colorString;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
        }
    }
}



(完)

沒有留言:

張貼留言