WinForm——Summary of basic usage of Text control

Table of contents

1. Common attributes:

Text property

MaxLength Property

MultiLine Property

HideSelection Property

ReadOnlyProperty

PasswordChar Property

ScrollBarsProperty

SelectionLengthProperty

SelectionStartProperty

SelectedText Property

Lines

Modified

TextLength Property

WordWrap

PasswordChar Property

ShorcutsEnabledProperty

2. Commonly used methods:

AppendText method

Clear method

Focus method

Copy method

Cut method

Paste method

Undo method

ClearUndo method

Select method

SelectAll method

3. Common events

GotFocusEvent

LostFocusEvent

TextChanged event

4. Usage examples

Block system key combinations such as Ctrl+C/V/X.

Disable right mouse button

Segmented display color

TextBox automatically selects all when it gets input focus

Only numbers and decimals can be entered

Only positive integers no larger than two digits can be entered.

Only Chinese characters can be entered

Only numbers and characters can be entered, and Chinese characters can be blocked.

Write validation class

Customized TextBox control, the border has only one bottom horizontal line.

1. Commonly used attributes:
Text attribute
The Text attribute is the most important attribute of the text box, because the text to be displayed is contained in the Text attribute. By default, up to 2048 characters can be entered in a text box. If you set the MultiLine property to true, you can enter up to 32KB of text. The Text property can be set at design time using the [Properties] window, or at runtime using code or through user input. The current contents of the text box can be obtained at runtime by reading the Text property.

The MaxLength property
is used to set the maximum length of characters allowed to be entered in the text box. When the value of this property is 0, there is no limit to the number of characters entered.

The MultiLine property
is used to set whether the text in the text box can be entered in multiple lines and displayed in multiple lines. When the value is true, multiple lines are allowed. When the value is false, multi-line display is not allowed. Once the text exceeds the width of the text box, the excess part will not be displayed.

The HideSelection property
is used to determine whether the selected text will still be displayed in the selected mode after the focus leaves the text box. If the value is true, it will not be displayed in the selected mode. If the value is false, it will still be displayed in the selected mode.

The ReadOnly property
is used to get or set a value that indicates whether the text in the text box is read-only. When the value is true, it is read-only, and when the value is false, it is readable and writable.

The PasswordChar attribute
is a string type that allows you to set a character. When the program is run, all the content entered into Text will be displayed as the attribute value, thereby maintaining confidentiality. It is usually used to enter a password or password.

The ScrollBars property
is used to set the scroll bar mode. There are four options: ScrollBars.None (no scroll bar), ScrollBars.Horizontal (horizontal scroll bar), ScrollBars.Vertical (vertical scroll bar), ScrollBars.Both (horizontal and vertical scroll bars) ).

Note: This property value is only valid when the MultiLine property is true. When the WordWrap attribute value is true,

Horizontal scrollbar will not work

The SelectionLength property
is used to get or set the number of characters selected in the text box. Can only be used in code. When the value is 0, it means that no characters are selected.

The SelectionStart property
is used to get or set the starting point of the selected text in the text box. Can only be used in code, the first character is at position 0, the second character is at position 1, and so on.

The SelectedText property
is used to get or set a string indicating the currently selected text in the control. Can only be used in code.

Lines
This property is an array property used to get or set the text lines in the text box control. That is, each line in the text box is stored in an element of the Lines array.

Modified
is used to get or set a value that indicates whether the user has modified the content of the text box control since the control was created or the content of the control was last set. A value of true indicates that it has been modified, and a value of false indicates that it has not been modified.

The TextLength property
is used to get the length of the text in the control.

WordWrap
is used to indicate whether the multi-line text box control will automatically wrap to the beginning of the next line when the input characters exceed the width of one line. A value of true means that it will automatically wrap to the beginning of the next line. A value of false means that it will not automatically wrap to the next line. start.

PasswordChar attribute
PasswordChar is set to a specific character to implement a password box.

The ShorcutsEnabled property
indicates whether to enable the shortcut keys specified for the control. Setting ShortcutsEnabled to False can block both the right click and the Ctrl+V and Ctrl+C shortcut keys.

2. Commonly used methods:
AppendText method
adds a string to the back of the text in the file box. The general format of the call is as follows:

Text box object.AppendText(str) parameter str is the string to be added.

Clear method
clears all text from the text box control. The general format of the call is as follows: Text box object.Clear() This method has no parameters.

The Focus method
sets the focus for the text box. If the focus is set successfully, the value is true, otherwise it is false. The general format of the call is as follows

Bottom: Text box object.Focus() This method has no parameters.

Copy method
Copies the current selection in the text box to the clipboard. The general format of the call is as follows:

Text box object.Copy() This method has no parameters.

Cut method
moves the current selection in the text box to the clipboard. The general format of the call is as follows:

Text box object.Cut() This method has no parameters.

Paste method
replaces the currently selected content in the text box with the contents of the clipboard. The general format of the call is as follows:

Text box object.Paste() This method has no parameters.

Undo method
Undoes the last editing operation in the text box. The general format of the call is as follows:

Text box object.Undo() method has no parameters.

ClearUndo method
Clears information about recent operations from the undo buffer of this text box, depending on the application

The state of the program, which can be used to prevent repeated undo operations. The general format of the call is as follows:

Text box object.ClearUndo() This method has no parameters.

Select method
is used to set the selected text in the text box. The general format of the call is as follows:

Text box object.Select(start,length)

This method has two parameters. The first parameter start is used to set the position of the first character of the currently selected text in the text box.

setting, the second parameter length is used to set the number of characters to be selected.

SelectAll method
is used to select all text in the text box. The general format of the call is as follows:

Text box object.SelectAll() This method has no parameters.

3. Commonly used events
GotFocus event
This event occurs when the text box receives focus.

LostFocus event
This event occurs when the text box loses focus.

TextChanged event
This event occurs when the value of the Text property changes. This event is raised whether the value of the Text property of a text box is changed through programmatic modification or user interaction.

4. Usage example:
Block the system's Ctrl+C/V/X and other key combinations.
This example mainly uses the Control property, KeyCode property and Handled property of the KeyEventArgs class. The Control property of the KeyEventArgs class is used to obtain a value that indicates whether the Ctrl key has been pressed. The syntax format is:

public bool Control {get;}

Code:

private void textBox1_KeyDown(object sender, KeyEventArgs e)

    {

        if (e.Control && e.KeyCode == Keys.V)

        {

            e.Handled = true;

            MessageBox.Show("Ctrl+V组合键已屏蔽!");

        }

        if (e.Control && e.KeyCode == Keys.X)

        {

            e.Handled = true;

            MessageBox.Show("Ctrl+X组合键已屏蔽!");

        }

        if (e.Control && e.KeyCode == Keys.C)

        {

            e.Handled = true;

            MessageBox.Show("Ctrl+C组合键已屏蔽!");

        }

    }

Note: The best way to block the right mouse button and shortcut keys Ctrl+C and Ctrl+V is to set ShortcutsEnabled to False

Disable the right mouse button
The MouseEventArgs class mainly provides data for the MouseUp, MouseDown, and MouseMove events, and its Button property is used to obtain the mouse button that was pressed. Syntax format: public MouseButtons Button{get;}

Parameter description: One of the MouseButton enumeration values.

enumerate

illustrate

Left

Press the left mouse button

None

No mouse button pressed

Right

Press the right mouse button

Middle

Press the middle mouse button

XButton1

Press the first XButton button

XButton2

Press the second XButton button

private void txtBox_MouseDown(object sender,MouseEventArgs e)

{

   if (e.Buttom==MouseButton.Right)

{

   txtBox.ContextMenu=new ContextMenu();

}

}

Displaying colors in segments
This example only uses the Select method and SelectColor property of the RichTextBox control. The Select method is mainly used to select a text range in the text box. This method can be overloaded. The overloaded form used in this example is as follows: public void Select(int start, int length);

Parameter description: start is the first position of the currently selected text in the start text box. The number of characters selected by length.

The SelectionColor property is used to get or set the text color of the currently selected text or insertion point.

[BrowsableAttribute(false)]

public Color Selection{get;set;}

Property value: Color representing the color of the currently selected text or text entered after the insertion point.
Insert image description here

private void Form1_Load(object sender, EventArgs e)

    {

        this.richTextBox1.Text = "0123456789522";

        this.richTextBox1.Select(0, 3);//选中钱3个号码

        this.richTextBox1.SelectionColor = Color.Red;

        this.richTextBox1.Select(3, 3);

        this.richTextBox1.SelectionColor = Color.Blue;//显示蓝色

    }

TextBox automatically selects all when it gets the input focus.
Idea: If the TextBox itself does not get the focus, click the left mouse button to get the focus and then select all.

If the TextBox itself has received focus, clicking the left mouse button will no longer select all.

using System;

using System.Collections.Generic;

using System.Windows.Forms;

using System.Globalization;

using System.Drawing;

namespace WindowsFormsApp3

{

public partial class Form1 : Form

{

    public Form1()

    {

        InitializeComponent();

        textBox1.Tag = false;

        textBox1.GotFocus += TextBox1_GotFocus;

    }

    private void TextBox1_GotFocus(object sender, EventArgs e)

    {

        textBox1.Tag = true;

        textBox1.SelectAll();//注意1

    }

    private void textBox1_MouseDown(object sender, MouseEventArgs e)

    {

        if (e.Button == MouseButtons.Left && (bool)(textBox1.Tag) == true)

        {

            textBox1.SelectAll();

        }

        textBox1.Tag = false;//取消全选标记

    }

}

}

Note: Although the Mouseup event has already performed a full selection, at the location in "Note 1" in the code, we still need to perform a full selection in the GotFocus event. The reason is that the method for letting the TextBox gain focus is not only through mouse clicks, but also through mouse clicks. By switching the focus through Tab, Moseup will not be started, but new words will not have the problem of Mouseup deselecting all, so it is still necessary to select all once in the GetFocus event.

Only numbers and decimals can be entered
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

    {

        if (!Char.IsNumber(e.KeyChar) && (!Char.IsPunctuation(e.KeyChar)) && (!Char.IsControl(e.KeyChar)))

        {

            e.Handled = true;

        }

        else if (Char.IsPunctuation(e.KeyChar))

        {

            if (e.KeyChar == '.')

            {

                if (((TextBox)sender).Text.LastIndexOf('.') != -1)

                {

                    e.Handled = true;

                }

            }

            else

            {

                e.Handled = true;

            }

        }

   }

Only positive integers no larger than two digits can be entered
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

    {

        if (!((e.KeyChar > '0' && e.KeyChar <= '9') || e.KeyChar == '\b'))

        {

            //如果不是数字值或者左删除键

            e.Handled = true;//不处理当前事件

        }

        else

        {

            //如果文本框的字符串长度大于等于2

            if (((TextBox)sender).Text.Length >= 2)

            {//如果当前键不是左删除键

                if (e.KeyChar != '\b')

                {

                    e.Handled = true;//不处理当前事件

                }

            }

            if (((TextBox)sender).SelectedText.Length <= 2 && ((TextBox)sender).SelectedText.Length >= 1)

            { e.Handled = false; }

        }

   }

Only Chinese characters can be entered
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

    {

        Regex rg = new Regex("^[\u4e00-\u9fa5]$");

        if (!rg.IsMatch(e.KeyChar.ToString()) && e.KeyChar != '\b')

        {

            e.Handled = true;

        }

}

or

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

    {

        Regex rg = new Regex("^[\u4e00-\u9fa5\b]$"); //\b是退格键

        if (!rg.IsMatch(e.KeyChar.ToString()))

        {

            e.Handled = true;

        }

    }

Only numbers and characters can be entered, and Chinese characters are blocked
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)

    {

        Regex rg = new Regex("^[\u4e00-\u9fa5\b]$"); //\b是退格键

        if (!rg.IsMatch(e.KeyChar.ToString()))

        {

            e.Handled = true;

        }

        else

        {

            if (char.IsLetterOrDigit(e.KeyChar) || e.KeyChar == '\b')

            {

                e.Handled = false;

            }

            else

            {

                e.Handled = true;

            }

        }

  }

Write the validation class
public class ValidationRegex

{

    /// <summary>

    /// 正则表达式字符串。

    /// </summary>

    /// <param name="pattern">正则表达式</param>

    /// <param name="validteString">待验证字符串</param>

    /// <returns></returns>

    private static bool PublicMethod(string pattern, string validteString)

    {

        Regex reg = new Regex(pattern);

        Match match = reg.Match(validteString);

        return match.Success;

    }

    /// <summary>

    /// 验证正整数

    /// </summary>

    /// <param name="validteString"></param>

    /// <returns></returns>

    public static bool ValidteData(string validteString)

    {

        string pattern = "^[+]?\\d+$";

        return PublicMethod(pattern, validteString);

    }

    /// <summary>

    /// 验证正负整数

    /// </summary>

    /// <param name="validteString"></param>

    /// <returns></returns>

    public static bool ValidtePlusMinus(string validteString)

    {

        string pattern = "^([-+]?\\d+)(\\.\\d+)?$";

        return PublicMethod(pattern, validteString);

    }

    /// <summary>

    /// 验证字符和数字

    /// </summary>

    /// <param name="validteString"></param>

    /// <returns></returns>

    public static bool VadidateDataLetter(string validteString)

    {

        string pattern = "^[a-zA-Z0-9]+$";

        return PublicMethod(pattern, validteString);

    }

    /// <summary>

    /// 验证中文字符

    /// </summary>

    /// <param name="validteString"></param>

    /// <returns></returns>

    public static bool ValidateChineseChar(string validteString)

    {

        string pattern = "^[\u4e00-\u9fa5\b]+$";

        return PublicMethod(pattern, validteString);            

    }

    /// <summary>

    /// 验证时间,格式:H:mm:ss

    /// </summary>

    /// <param name="validteString"></param>

    /// <returns></returns>

    public static bool ValidateTime(string validteString)

    {

        string pattern = "^[0-9]{1,2}:[0-9]{2}(:[0-9]{2})?$";

        return PublicMethod(pattern, validteString);

    }

    /// <summary>

    /// 验证固定电话

    /// </summary>

    /// <param name="validteString"></param>

    /// <returns></returns>

    public static bool ValidateTel(string validteString)

    {

        string pattern = "^([0-9]{3,4}-)?[0-9]{7,8}$";

        return PublicMethod(pattern, validteString);

    }

    /// <summary>

    /// 验证手机号

    /// </summary>

    /// <param name="validteString"></param>

    /// <returns></returns>

    public static bool ValidatePhone(string validteString)

    {

        string pattern = "^(13|15|18|17)[0-9]{9}$";

        return PublicMethod(pattern, validteString);

    }

}

Customized TextBox control, the border has only one bottom horizontal line.
Insert image description here

public partial class UnderLineTextBox : TextBox

{

    public UnderLineTextBox()

    {

        this.Width = 180;//设置空间的宽度。

        this.Height = 150;//设置控件的高度

        this.BorderStyle = BorderStyle.None;//设置控件为无边框。

    }

    public const int WM_PAINT = 0x000F;//该变量表示绘制TextBox控件。

    public const int WM_CTLCOLOREDIT = 0x0133;//该变量表示开始编辑TextBox控件的颜色

    /// <summary>

    /// 说明:获取整个窗口的舍本场景

    /// 返回值:执行成功则为窗口设备场景,失败则为0

    /// 使用后,一定要用ReleaseDC释放

    /// </summary>

    /// <param name="hWnd">将获取其折本场景的窗口。</param>

    /// <returns></returns>

    [DllImport("user32.dll")]

    public static extern IntPtr GetWindowDC(IntPtr hWnd);

    /// <summary>

    /// 释放由调用GetDC或GetWindowDC函数获取的指定设备场景,它对类或稀有设备场景无效。

    /// 返回值:执行成功返回1,否则返回0;

    ///

    /// </summary>

    /// <param name="hWnd">要释放的设备场景相关的窗口句柄</param>

    /// <param name="hDc">要释放的设备场景的句柄</param>

    /// <returns></returns>

    [DllImport("user32.dll")]

    public static extern int ReleaseDC(IntPtr hWnd,IntPtr hDc);

    protected override void WndProc(ref Message m)

    {

        base.WndProc(ref m);//处理消息。

        switch (m.Msg)//截获有关TextBox控制的绘制消息。

        {

            case WM_CTLCOLOREDIT://当开始编辑TextBox控件的颜色是

            case WM_PAINT:

                IntPtr hDc = GetWindowDC(this.Handle);//获取当前窗口的设备场景。

                if (hDc.ToInt32() != 0)//当场景存在时

                {

                    using (Graphics g = Graphics.FromHdc(hDc))//声明一个GDI+绘图画类对象

                    {

                        DrawBottomLines(g);//绘制TextBox控件的低端横线

                        g.Dispose();//释放GDI+绘绘图类对象所占用的资源。

                    }

                }

                m.Result = IntPtr.Zero;//指定在当前条件下的返回值。

                ReleaseDC(m.HWnd, hDc);//释放指定设备的场景。

                break;

        }

    }

    public void DrawBottomLines(Graphics g)

    {//定义一个用于绘制直线和曲线的对象并设定它的颜色和宽度。

        Pen p = new Pen(this.BackColor, 2);

        g.DrawRectangle(p, 1, 1, this.Width - 1, this.Height - 2);//绘制由坐标对、宽和高指定的矩形。

        p = new Pen(Color.FromArgb(0, 0, 0), 1);//定义一个用于绘制的对象,并设定颜色和宽度。

        g.DrawLine(p, 0, this.Height - 1, this.Width, this.Height - 1);//绘制TextBox控件的低端横线。

        p.Dispose();//释放画笔p占用的资源。

    }

}
————————————————

Original link: https://blog.csdn.net/hhhhhhhhhhwwwwwwwwww/article/details/106207436

Guess you like

Origin blog.csdn.net/weixin_45499836/article/details/125644558