效果
1.创建控件
在当前项目右击 -> 添加 -> 用户控件,命名为SizableTextBox
2.添加TextBox和Lable控件
3.功能实现
F7进入代码
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 WinFormsApp1
{
public partial class SizableTextBox : UserControl
{
private bool handleClick;
public SizableTextBox()
{
InitializeComponent();
InitTextBox();
InitHandle();
InitComp();
}
#region 初始化
// 初始化控件
private void InitComp()
{
this.Size = new Size(
lableHandle.Location.X + lableHandle.Width, textBox.Height);
}
// 初始化TextBox
private void InitTextBox()
{
textBox.Location = new Point(0, 0);
}
// 初始化手柄
private void InitHandle()
{
// 尺寸位置
lableHandle.Text = "";
lableHandle.AutoSize = false;
lableHandle.Size = new Size(8, 8);
lableHandle.Location = new Point(
textBox.Width - 4, (textBox.Height / 2) - 4);
// 显示
lableHandle.Visible = false;
lableHandle.FlatStyle = FlatStyle.Flat;
lableHandle.BorderStyle = BorderStyle.FixedSingle;
lableHandle.Cursor = Cursors.SizeWE;
// 事件
textBox.Enter += new EventHandler(TextBox_Enter);
textBox.Leave += new EventHandler(TextBox_Leave);
lableHandle.MouseDown += new MouseEventHandler(Handle_MouseDown);
lableHandle.MouseMove += new MouseEventHandler(Handle_MouseMove);
lableHandle.MouseUp += new MouseEventHandler(Handle_MouseUp);
}
#endregion
#region 事件
// 点击TextBox时显示
private void TextBox_Enter(object sender, EventArgs e)
{
lableHandle.Visible = true;
}
// 点击其他控件时隐藏
private void TextBox_Leave(object sender, EventArgs e)
{
lableHandle.Visible = false;
}
// 手柄点击
private void Handle_MouseDown(object sender, MouseEventArgs e)
{
handleClick = true;
}
// 手柄移动
private void Handle_MouseMove(object sender, MouseEventArgs e)
{
if (handleClick)
{
textBox.Size = new Size(
textBox.Size.Width + e.X, textBox.Size.Height);
this.Size = new Size(
textBox.Size.Width + 4, this.Size.Height);
lableHandle.Location = new Point(
textBox.Location.X + textBox.Size.Width - 4, lableHandle.Location.Y);
}
}
// 手柄松开
private void Handle_MouseUp(object sender, MouseEventArgs e)
{
handleClick = false;
}
#endregion
}
}
4.使用控件
生成 → 重新生成解决方案
拖动SizableTextBox到窗口或用户控件即可使用