NEWS

[C#] Hướng dẫn chỉnh sửa Text của label trực tiếp trên winform

[C#] Hướng dẫn chỉnh sửa Text của label trực tiếp trên winform
Đăng bởi: Thảo Meo - Lượt xem: 2076 13:25:54, 15/05/2023DEVEXPRESS   In bài viết

Xin chào các bạn, bài viết này mình tiếp tục hướng dẫn các bạn các chỉnh sửa Text trực tiếp trên Label control khi ứng dụng đang chạy.

[C#] How to Edit Text in Label control Runtime

Giao diện, demo ứng dụng:

edit_label-runtime

Các bạn có thể ứng dụng bài viết này để tạo ghi chú comment trên hình ảnh.

Khi các bạn double click vào Label thì label sẽ chuyển thành TextBox cho các bạn chỉnh sửa text.

Và khi các bạn double click vào vùng Form thì nó sẽ chuyển ngược lại từ Textbox về Label.

Source code c#:

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

namespace LabelEditRunTime
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.DoubleClick += unClickLabel;
            label1.MouseDown += Label1_MouseDown;
            label1.MouseMove += Label1_MouseMove;


        }

        private void Label1_MouseMove(object sender, MouseEventArgs e)
        {
           
            if (e.Button == MouseButtons.Left)
            {
                label1. Left += e.X - mdLoc.X;
                label1.Top += e.Y - mdLoc.Y;
            }
        }

        private void Label1_MouseDown(object sender, MouseEventArgs e)
        {
         
            mdLoc = e.Location;
        }

        Point mdLoc;      

        private void label1_Click(object sender, EventArgs e)
        {
            TextBox tb = null;
            if (label1.Controls.Count > 0)  
            {
                tb = ((TextBox)label1.Controls[0]);
                
                tb.Size = new Size(label1.Size.Width + 15, label1.Size.Height + 15);
                if (tb.Visible) { label1.Text = tb.Text; tb.Hide(); return; };
            }
            else if (sender == null) return;  
            else 
            {
                tb = new TextBox();
                tb.BackColor = SystemColors.Control;
                tb.Parent = label1;    
                tb.Size = new Size(label1.Size.Width + 15, label1.Size.Height + 15); 
                tb.LostFocus += (ss, ee) => { label1.Text = tb.Text; tb.Hide(); };
            }
            tb.BorderStyle = BorderStyle.None;
            tb.Text = label1.Text;  
            tb.Show();
        }

        private void unClickLabel(object sender, EventArgs e) { label1_Click(null, null); }
    }
}

Thanks for watching!

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn chỉnh sửa Text của label trực tiếp trên winform
Đăng bởi: Thảo Meo - Lượt xem: 2076 13:25:54, 15/05/2023DEVEXPRESS   In bài viết

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

Đọc tiếp
.