0

私は次のように長方形を描きました:

Rectangle rectangle=new Rectangle(10,10,40,40);
g.FillRectangle(new SolidBrush(Color.Red),rectangle);

誰かがクリックしたときに長方形の背景色を取得できるという考えを教えてもらえますか:

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
            if (rectangle.Contains(e.Location))
            {
                //get the color here that it should be Red
                Console.WriteLine("COLOR IS: " ????);
            }
}

前もって感謝します

4

1 に答える 1

1

この回答を見てください。

基本的な考え方は、クリック イベントが発生するピクセルの色を取得することです ( )。そのために、gdi32.dll のメソッドe.Locationを使用できます。GetPixel

リンクにあるコードのわずかに変更されたバージョン:

class PixelColor
{
    [DllImport("gdi32")]
    public static extern uint GetPixel(IntPtr hDC, int XPos, int YPos);

    [DllImport("User32.dll", CharSet = CharSet.Auto)]
    public static extern IntPtr GetWindowDC(IntPtr hWnd);

    /// <summary> 
    /// Gets the System.Drawing.Color from under the given position. 
    /// </summary> 
    /// <returns>The color value.</returns> 
    public static Color Get(int x, int y)
    {
        IntPtr dc = GetWindowDC(IntPtr.Zero);

        long color = GetPixel(dc, x, y);
        Color cc = Color.FromArgb((int)color);
        return Color.FromArgb(cc.B, cc.G, cc.R);
    }
}

関数を呼び出す前に、X 座標と Y 座標を画面座標に変換する必要がある場合があることに注意してください。

しかし、あなたの場合、本当の答えは赤です。:)

于 2014-05-26T13:50:15.033 に答える