Нажатие нарисованных фигур в C# - PullRequest
1 голос
/ 26 января 2020

В этом коде я нарисовал красный прямоугольник. Мне было интересно, как сделать этот прямоугольник кликабельным. Таким образом, я могу сделать его синим, когда я нажму на него.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.Cursor = new Cursor(Application.StartupPath + "\\Cursor1.cur");
    }

    public Rectangle rect = new Rectangle(333, 333, 95, 95);

    private void Form1_Paint(object sender, PaintEventArgs e)
    {
        System.Drawing.SolidBrush fillRed = new System.Drawing.SolidBrush(Color.Red);
        System.Drawing.SolidBrush fillBlue = new System.Drawing.SolidBrush(Color.Blue);
        e.Graphics.FillRectangle(fillRed, rect);
    }

    private void rect_Click(object sender, EventArgs e)
    {
        System.Drawing.SolidBrush fillBlue = new System.Drawing.SolidBrush(Color.Blue);
        e.Graphics.FillRectangle(fillBlue, rect);
    }
}

1 Ответ

0 голосов
/ 26 января 2020

Цель: чтобы иметь возможность щелкнуть фигуру, создать прямоугольник в соответствии с кодом OP и изменить его цвет

Шаги:

  • Нарисуйте прямоугольник
  • Затем мы проверяем, происходит ли событие щелчка в пределах прямоугольника
  • При клике мы устанавливаем флаг IsRectClick на true
  • Перерисовать Панель

РЕДАКТИРОВАТЬ: добавлена ​​еще одна функция

  • Также теперь можно перемещать фигуры, перетаскивая
  • Redr aws shape при нажатии на другую область

Form1.cs

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

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {

        bool isRectClick = false;
        System.Drawing.SolidBrush newColor;
        public Rectangle rect = new Rectangle(200, 100, 50, 50);
        public Form1()
        {
            InitializeComponent();

        }



        private void panel1_Paint(object sender, PaintEventArgs e)
        {
            if (isRectClick == false)
            {

                System.Drawing.SolidBrush fillRed = new System.Drawing.SolidBrush(Color.Red);

                e.Graphics.FillRectangle(fillRed, rect);
            }
            else
            {


                e.Graphics.FillRectangle(newColor, rect);
            }

        }
        private void Panel1_MouseDown(object sender, MouseEventArgs e)
        {
            if (this.rect.Contains(e.Location))
            {
                newColor = new System.Drawing.SolidBrush(Color.Blue); //New Color
                isRectClick = true;
                panel1.Invalidate();
            }
            else
            {
                if (e.Button == MouseButtons.Left)
                {
                    rect = new Rectangle(e.X, e.Y, 50, 50);
                    panel1.Invalidate();
                }
            }

        }
        private void Panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                int initialX = 0, initialY = 0; 

                rect.X = (e.X - 200) + initialX;
                rect.Y = (e.Y - 100) + initialY;

                panel1.Invalidate();
            }
        }
    }
}

Form1.Designer.cs

using System.Drawing;

namespace WindowsFormsApp2
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.panel1 = new System.Windows.Forms.Panel();

            this.panel1.SuspendLayout();
            this.SuspendLayout();
            // 
            // panel1
            // 

            this.panel1.Location = new System.Drawing.Point(89, 63);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(646, 342);
            this.panel1.TabIndex = 0;
            this.panel1.Paint += new System.Windows.Forms.PaintEventHandler(this.panel1_Paint);
            this.panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Panel1_MouseDown);
          this.panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Panel1_MouseMove);

            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(800, 450);
            this.Controls.Add(this.panel1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.panel1.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.Panel panel1;


    }
}

Выход

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...