GDI cơ bản

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VP3._1._3
{
    public partial class Form1 : Form
    {

        int x = 0;
        int y = 0;
        int w = 50;
        int h = 50;
        bool isClicked = false;
        public Form1()
        {


            this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);

            x = this.ClientRectangle.Width / 2;
            y = this.ClientRectangle.Height / 2;
            this.MouseMove += Form1_MouseMove;
            this.MouseClick += Form1_MouseClick;
            this.KeyPress += Form1_KeyPress;
            this.DoubleBuffered = true;


        }

        private void Form1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '+')
            {
                w += 10;
                h += 10;
            }
            else
             if (e.KeyChar == '-')
            {
                w -= 10;
                h -= 10;
            }
            this.Invalidate();
        }

        private void Form1_MouseClick(object sender, MouseEventArgs e)
        {
            Rectangle rect = new Rectangle(x, y, w, h);
            if (rect.Contains(e.X, e.Y))
            {
                if (isClicked)
                    isClicked = false;
                else
                    isClicked = true;
            }
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            if (isClicked)
            {
                x = e.X;
                y = e.Y;
                this.Invalidate();
            }

        }
        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.Clear(Color.White);
            g.FillRectangle(Brushes.Red, x, y, w, h);
        }
    }
}