111,131
社区成员
发帖
与我相关
我的任务
分享public partial class TextBoxEx : TextBox
{
public TextBoxEx()
{
InitializeComponent();
}
属性#region 属性
private int m_MaxByteLength = 0;
[Description("获取或设置用户可在文本框控件中键入或粘贴的最大字节数。0 为允许无限长度。")]
/**//// <summary>
/// 获取或设置用户可在文本框控件中键入或粘贴的最大字节数。0 为允许无限长度。
/// </summary>
public int MaxByteLength
{
get { return m_MaxByteLength; }
set { m_MaxByteLength = value; }
}
} protected override void WndProc(ref Message m)
{
//如果该属性没有设置,则允许输入
if (m_MaxByteLength == 0)
{
base.WndProc(ref m);
return;
}
switch (m.Msg)
{
case WM_CHAR:
int i = (int)m.WParam;
bool isBack = (i == (int)Keys.Back);
bool isCtr = (i == 24) || (i == 22) || (i == 26) || (i == 3);
if (isBack || isCtr)
{
//控制键不作处理
}
else
{
char c = (char)i;
if (CheckByteLengthFlow(c.ToString()))
{
break;
}
}
base.WndProc(ref m);
break;
case WM_PASTE:
IDataObject iData = Clipboard.GetDataObject();//取剪贴板对象
if (iData.GetDataPresent(DataFormats.Text)) //判断是否是Text
{
string text = (string)iData.GetData(DataFormats.Text);//取数据
if (CheckByteLengthFlow(text))
{
m.Result = (IntPtr)0;//不可以粘贴
break;
}
}
base.WndProc(ref m);
break;
default:
base.WndProc(ref m);
break;
}
}
/// <summary>
/// 判断即将输入的文本长度是否溢出
/// </summary>
/// <param name="text">文本</param>
/// <returns>是否溢出</returns>
private bool CheckByteLengthFlow(string text)
{
int len = GetByteLength(text); //输入的字符的长度
int tlen = GetByteLength(this.Text); //文本框原有文本的长度
int slen = GetByteLength(this.SelectedText); //文本框选中文本的长度
return (m_MaxByteLength < (tlen - slen + len));
}
/// <summary>
/// 计算文本字节长度,区分多字节字符
/// </summary>
/// <param name="text">文本</param>
/// <returns>文本字节长度</returns>
private int GetByteLength(string text)
{
return System.Text.Encoding.Default.GetBytes(text).Length;
}public string RealText
{
get
{
if (m_MaxByteLength == 0)
{
return this.Text;
}
if (m_MaxByteLength >= GetByteLength(this.Text))
{
return this.Text;
}
string text = this.Text;
if (string.IsNullOrEmpty(text))
{
return text;
}
char[] c = text.ToCharArray();
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < c.Length; i++)
{
count += GetByteLength(c[i].ToString());
if (m_MaxByteLength >= count)
{
sb.Append(c[i]);
}
}
return sb.ToString();
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text.Length > 32767)
{
return;
}
}