NEWS

[C#] Custom control PictureBox cho phép di chuyển trong Winform

[C#] Custom control PictureBox cho phép di chuyển trong Winform
Đăng bởi: Thảo Meo - Lượt xem: 7730 10:49:54, 25/10/2019C#   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách cho phép di chuyển PictureBox Control trong Winform của lập trình C#.

[C#] Move PictureBox Inside Winform Csharp

Trong lập trình Winform, khi các bạn thiết kế các control trong Winform thì khi chạy lên nó sẽ cố định.

Và bây giờ mình muốn di chuyển nó trong Winform thì làm thế nào, trong bài viết này mình sẽ hướng dẫn các bạn tạo mới component My_PictureBox, kế thừa từ control PictureBox của Winform C#.

Sau đó, mình sẽ overiride lại hai sự kiện OnMouseMoveOnMouseDown

Lúc đó, các bạn kéo control ra và sử dụng bình thường.

Dưới đây là demo ứng dụng di chuyển hình ảnh trong Winform C#:

MovePictureBoxInsideWinForm_demo (1)

Source code Component My_PictureBox c#:

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

namespace MovePictureBoxInsideWinForm
{
    public partial class MyPictureBox : PictureBox
    {
        public MyPictureBox()
        {
            InitializeComponent();
        }

        public MyPictureBox(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        Point mdLoc;
        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            mdLoc = e.Location;
        }
        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (e.Button == MouseButtons.Left)
            {
                this.Left += e.X - mdLoc.X;
                this.Top += e.Y - mdLoc.Y;
            }
        }
    }
}

Thanks for watching!

 

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Custom control PictureBox cho phép di chuyển trong Winform
Đăng bởi: Thảo Meo - Lượt xem: 7730 10:49:54, 25/10/2019C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.