C#控件介绍及用法(详细版) 联系客服

发布时间 : 星期四 文章C#控件介绍及用法(详细版)更新完毕开始阅读aedeb87b27284b73f24250fb

/// 捕获Ctrl+V快捷键操作 ///

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {

if (keyData == (Keys)Shortcut.CtrlV) // 快捷键 Ctrl+V 粘贴操作 {

this.ClearSelection();

string text = Clipboard.GetText();

for (int k = 0; k < text.Length; k++) // can not use SendKeys.Send {

// 通过消息模拟键盘输入, SendKeys.Send()静态方法不行 SendCharKey(text[k]); }

return true; }

return base.ProcessCmdKey(ref msg, keyData); }

///

/// 屏蔽非数字键 ///

protected override void OnKeyPress(KeyPressEventArgs e) {

base.OnKeyPress(e); if (this.ReadOnly) {

return; }

// 特殊键, 不处理 if ((int)e.KeyChar <= 31) {

return; }

// 非数字键, 放弃该输入 if (!char.IsDigit(e.KeyChar)) {

e.Handled = true; return; } }

///

/// 通过消息模拟键盘录入 ///

private void SendCharKey(char c) {

Message msg = new Message(); msg.HWnd = this.Handle; msg.Msg = WM_CHAR; msg.WParam = (IntPtr)c; msg.LParam = IntPtr.Zero; base.WndProc(ref msg); }

///

/// 清除当前TextBox的选择 ///

private void ClearSelection() {

if (this.SelectionLength == 0)

{

return; }

int selLength = this.SelectedText.Length;

this.SelectionStart += this.SelectedText.Length; // 光标在选择之后 this.SelectionLength = 0;

for (int k = 1; k <= selLength; k++) {

this.DeleteText(Keys.Back); } }

///

/// 删除当前字符, 并计算SelectionStart值 ///

private void DeleteText(Keys key) {

int selStart = this.SelectionStart;

if (key == Keys.Delete) // 转换Delete操作为BackSpace操作 {

selStart += 1;

if (selStart > base.Text.Length) {

return; } }

if (selStart == 0 || selStart > base.Text.Length) // 不需要删除 {

return; }

if (selStart == 1 && base.Text.Length == 1) {

base.Text = \

base.SelectionStart = 0; }

else // selStart > 0 {

base.Text = base.Text.Substring(0, selStart - 1) +

base.Text.Substring(selStart, base.Text.Length - selStart); base.SelectionStart = selStart - 1; } } } }

我们在使用C# TextBox进行开发操作的时候经常会碰到C# TextBox的使用,那么C# TextBox的使用有没有一些常用的技巧呢?如C# TextBox换行的处理,其实就是一些常用的操作,那么这里就向你介绍几个我们常见的需求以及解决方法。 一、关于C# TextBox全选的判断:

? int SelectLength=this.textBox1.SelectionLength;//获取选中的字符长度 ?

? if (SelectLength == this.textBox1.Text.Length) {//判断是否全部选中

?

? MessageBox.Show(\你已经选中\); ? ? }

二、关于C# TextBox换行、设置光标位置、随文本滚动 ◆C# TextBox换行

? TextBoxControl.Text += Environment.NewLine;

如何在多行TextBox中写入文本时实现换行?由于Windows系统中,回车符需两上字符。因此方法是使用\\r\\n标记,如

? Label=\ \; ? textBox.AppendText(Label);

另外更有一个办法是用Environment.Newline的方法,能够兼容Windows和Linux系统。 ◆C# TextBox设置光标位置到文本最后

? TextBoxControl.SelectionStart = TextBoxControl.TextLength;

◆C# TextBox随文本滚动

? TextBoxControl.ScrollToCaret();

如何在多行TextBox中用滚动条,使添加文本后自动滚动显示到最后一行?方法是使用ScrollToCaret方法,自动滚动到插入符的位置,如:

? textBox.AppendText(Label); ? textBox.ScrollToCaret();

那么对于C# TextBox常用操作的内容就向你介绍到这里,希望对你了解和学习C# TextBox的使用有所帮助。