[Yugong Series] Detailed explanation of MaskedTextBox control on Winform control topic in September 2023


Preface

Winform controls are user interface elements in Windows Forms. They can be used to create various visual and interactive components of Windows applications, such as buttons, labels, text boxes, drop-down list boxes, check boxes, radio boxes, progress bars, etc. . Developers can use Winform controls to build user interfaces and respond to user actions to create powerful desktop applications.

1. Detailed explanation of MaskedTextBox control

The MaskedTextBox control is a text box control in Winform, used to limit the format of user input. It allows you to specify the input format and automatically format the input. For example, you can use it to restrict the format of date input or the format of phone numbers, etc.

The MaskedTextBox control has a Mask property in which you can set input restrictions. Here are some commonly used input formats:

  1. Date format: Set the Mask property to "00/00/0000" to limit the text box to the date format, such as "01/01/2000".

  2. Time format: Set the Mask property to "00:00" and limit the text box to the time format, such as "12:30".

  3. Phone number format: Set the Mask property to "(999) 000-0000" and limit the text box to the phone number format, such as "(123) 456-7890".

  4. Zip code format: Set the Mask property to "00000" and limit the text box to the zip code format, such as "12345".

  5. Custom format: You can use a single character (such as "0", "9", "a", etc.) to indicate that any character can be entered; or use "#" to indicate that numbers can be entered; or use "@" to indicate that Enter letters.

By setting the PromptChar property, you can set the characters that appear in the text box when no characters are entered. For example, if you set the PromptChar property to " ", " " will be displayed when no characters are entered in the text box.

In addition to the Mask and PromptChar properties, the MaskedTextBox control has some other useful properties, such as the InsertKeyMode property and the HidePromptOnLeave property, which can help you control the behavior of the control.

1. Introduction to attributes

1.1 AllowPromptAsInput

The AllowPromptAsInput property is a property of the MaskedTextBox control and is used to specify whether the PromptChar character is considered an input character. By default, if the user attempts to enter a PromptChar character, the control ignores it and skips to the next valid character.

When AllowPromptAsInput is set to true, PromptChar characters will be treated as inputable characters, which means that the user can enter any character, including PromptChar characters. This may be useful for certain input formats, such as allowing the user to enter symbols such as brackets or dashes in a phone number.

The following is an example of usage of the AllowPromptAsInput attribute:

private void Form1_Load(object sender, EventArgs e)
{
    
    
    maskedTextBox1.Mask = "(999) 000-0000";
    maskedTextBox1.PromptChar = '_';
    maskedTextBox1.AllowPromptAsInput = true;
}

Insert image description here

In the code above, we specify a phone number format and set the PromptChar property to "_". We also set the AllowPromptAsInput property to true to allow the user to enter PromptChar characters. This way, if the user wants to enter symbols such as brackets or dashes in their phone number, they can enter them directly without being ignored.

Please note that enabling the AllowPromptAsInput property may cause the control to accept some invalid input and may break the specified input format if used incorrectly. Therefore, this property needs to be used with caution.

1.2 AsciiOnly

The AsciiOnly property of the MaskedTextBox control is used to restrict the characters entered by the user in the input box to ASCII characters. This attribute is not suitable for situations where non-ASCII characters need to be entered.

If you want the user to enter only ASCII characters, you can use the AsciiOnly attribute by following these steps:

  1. Add a MaskedTextBox control to your form.

  2. Find the AsciiOnly property in the properties window and set its value to True.

  3. Run the program and enter any non-ASCII characters into the MaskedTextBox. You will find that the input is invalid and no non-ASCII characters will be displayed in the text box.

1.3 BeepOnError

The MaskedTextBox control is an input control in Winform that can format and verify input content. The BeepOnError property is a property of the MaskedTextBox control that beeps when an input error occurs.

When the BeepOnError property is set to True, if the content entered by the user does not conform to the specified format, MaskedTextBox will beep to prompt the user for an input error. If set to False, no prompt sound will be emitted.

Here's an example:

// 创建一个MaskedTextBox控件
MaskedTextBox maskedTextBox1 = new MaskedTextBox();

// 设置掩码格式
maskedTextBox1.Mask = "0000-00-00";

// 设置BeepOnError属性
maskedTextBox1.BeepOnError = true;

Insert image description here

In the above example, the mask format of the MaskedTextBox is set to "0000-00-00", that is, the user can only enter 4 digits, a hyphen, 2 digits, another hyphen, and 2 digits. If the content entered by the user does not conform to this format, MaskedTextBox will beep to prompt the user for an input error.

1.4 CutCopyMaskFormat

The CutCopyMaskFormat property of the MaskedTextBox control is used to specify the text format used when copying or cutting operations.

This attribute has three optional values:

  1. MaskFormat: The copy or cut operation will use the mask format. That is, only the actual text in the input control is copied or cut, excluding mask characters.

  2. IncludeLiterals: A copy or cut operation will use a mask format that contains literals, including mask characters.

  3. ExcludePromptAndLiterals: The copy or cut operation will use a mask format that does not include prompts and literals. Only the actual text in the input control will be copied or cut, excluding mask characters and prompts.

Usage example:

Assume that the Mask property of the MaskedTextBox control is set to "(999) 000-0000", which is the phone number format. but:

  1. If the CutCopyMaskFormat property is set to MaskFormat, copying the text "1234567890" will get the copy result "(123) 456-7890", excluding the mask character.

  2. If the CutCopyMaskFormat property is set to IncludeLiterals, copying the text "1234567890" will get the copy result "(999) 123-4567", including the mask character.

  3. If the CutCopyMaskFormat property is set to ExcludePromptAndLiterals, copying the text "1234567890" will get the copy result "1234567890", excluding mask characters and prompts.

1.5 HidePromptOnLeave

The HidePromptOnLeave property is a property of the MaskedTextBox control. When it is set to true, when the focus leaves the control, the mask prompt character will be hidden and only the entered text will be displayed. When set to false, the mask prompt characters will remain when focus leaves the control.

For example, when the mask input is a mobile phone number, if the HidePromptOnLeave property is set to true, after the user enters the 11-digit mobile phone number and leaves the control, the control will only display the entered 11-digit number, and the mask prompt characters will not be displayed. Display again. If set to false, the mask prompt character will continue to display when the user leaves the control so that the user knows the position of the currently entered number.

How to use it:

  1. Add a MaskedTextBox control to the Winform form.

  2. Find the HidePromptOnLeave property in the properties window and set it to true or false.

  3. When using this control in code, you can control the display of mask prompt characters through the control's HidePromptOnLeave property.

1.6 HideSelection

The HideSelection property of the MaskedTextBox control is used to set whether the selected content is hidden when the control loses focus or is no longer the active control.

When the HideSelection property is set to true, it means that the selection will be hidden when the control loses focus or is no longer the active control.

When the HideSelection property is set to false, which means that when the control loses focus or is no longer the active control, the selection will remain selected and highlighted with an inverse color.

Sample code:

//设置HideSelection属性为true
maskedTextBox1.HideSelection = true;

//设置HideSelection属性为false
maskedTextBox1.HideSelection = false;

Note: When the MaskedTextBox control's ReadOnly property is set to true, the selection will remain selected and highlighted with an inverse color regardless of whether the HideSelection property is set to true or false.

1.7 Miracle Mode

The ImeMode property of the MaskedTextBox control is used to set the input method mode of the control. Input method mode affects how the input method is displayed in the control.

The values ​​of the ImeMode attribute are as follows:

  • Alpha: Ordinary input method mode, suitable for inputting letters, numbers, symbols, etc.
  • Kana: Japanese input method only, used for inputting Hiragana and Katakana.
  • Hangul: Only applicable to Korean input method, used to input Korean.
  • Hiragana: Only applicable to Japanese input method, used to enter Hiragana.
  • Katakana: Only applicable to Japanese input method, used to enter katakana.
  • NoControl: Disable input method.
  • Off: The input method is not available.
  • On: The default input method mode, suitable for inputting any characters.

For example, if you want to only allow Chinese characters to be entered in the MaskedTextBox control, you can set the ImeMode property to ImeMode.Hangul.

At design time, you can set the ImeMode property directly in the properties window; at run time, you can set the ImeMode property through code, as shown below:

maskedTextBox1.ImeMode = ImeMode.Hangul;

1.8 InsertKeyMode

The InsertKeyMode property of the MaskedTextBox control is used to set the mode of inserting keys, which determines the behavior of inserting keys.

The InsertKeyMode property has two optional values:

  1. InsertMode: When the insert key is pressed, the current cursor position will cover characters backward starting from this position.

  2. OverwriteMode: When the insert key is pressed, the current cursor position will overwrite the character under the cursor.

To use the InsertKeyMode property, it can be set at design time or in code. At design time, you can find the InsertKeyMode property in the properties window and select the desired mode. In code, this can be set via:

maskedTextBox1.InsertKeyMode = InsertKeyMode.OverwriteMode;

It should be noted that if the Mask property of the MaskedTextBox control contains any placeholders, the InsertKeyMode property will be invalid and input can only be performed in overlay mode.

1.9 Mask

The MaskedTextBox control is a text box control in Winform. It has special functions using the Mask property. The Mask property allows you to set a specific format for input, which can help users enter data faster and ensure that the data is formatted correctly.

Here are some examples of using the MaskedTextBox control:

1.Date format

The MaskedTextBox control can use a date format mask, such as "00/00/0000", which can force users to maintain a certain format when entering dates. If the user attempts to enter a value that does not match the format, the control automatically rejects the input.

2. Phone number format

You can use a format mask to create a phone number format, such as "(000) 000-0000." This will make it easier for users to enter phone numbers and automatically format phone numbers into a specified format.

3. Postal code format

The MaskedTexBox control can also use postal code format masks, such as "00000-0000". This ensures users enter the correct zip code while maintaining consistent formatting.

By using masks, the MaskedTextBox control makes it easier for users to enter data and ensures that the input data is formatted correctly.

1.10 PasswordChar

The MaskedTextBox control is a text box control in Windows Forms that can provide masks, such as date, time, phone number, etc. The PasswordChar property is the character used in the mask text box to mask user-entered text.

When you need to enter a password, you can set the PasswordChar property of the MaskedTextBox control to any character to mask the entered text, for example:

// 设置掩码文本框的PasswordChar属性为'*'
maskedTextBox1.PasswordChar = '*';

In the above code example, by setting the PasswordChar property to the asterisk (*) character, user-entered text will be masked.

It should be noted that setting the PasswordChar property will not automatically convert the text entered in the MaskedTextBox control into a password, and the developer will still need to manually encrypt the password text.

1.11 PromptChar

The MaskedTextBox control is a control used to enter formatted strings. The PromptChar attribute is a placeholder used to set unentered characters in the mask. Normally, the default is the underscore "_".

For example, if you set a phone number mask of "(000) 000-0000" and the PromptChar property is set to "X", then if the user only enters the first three digits "123" it will automatically fill in as " (123) XXX-XXXX”.

You can set the PromptChar property to any character as needed, such as " ", "#", etc. For example, if you want untyped characters in the mask to be represented by an asterisk " ", you can set the PromptChar property to "*".

Here's a simple example:

// 设置掩码
maskedTextBox1.Mask = "000-000-0000";
// 设置PromptChar
maskedTextBox1.PromptChar = '*';

Insert image description here

1.12 RejectInputOnFirstFailure

The RejectInputOnFirstFailure property of the MaskedTextBox control is used to control whether user input is rejected. When this property is set to true, if the characters entered by the user do not comply with the mask rules, the control will reject the input and display the previous legal input value, even if the user has not completed the input. When this property is set to false, the user can continue typing until the entire mask rule is entered or clear the input manually. By default, this property is true.

The following code demonstrates how to use the RejectInputOnFirstFailure property:

MaskedTextBox maskedTextBox = new MaskedTextBox();
maskedTextBox.Mask = "00/00/0000";
maskedTextBox.RejectInputOnFirstFailure = true;

In the above example, a MaskedTextBox control with a mask of "00/00/0000" is created and its RejectInputOnFirstFailure property is set to true. In this way, if the characters entered by the user do not comply with the mask rules, they will be rejected and the previous legal input value will be displayed.

1.13 ResetOnPrompt、ResetOnSpace

The MaskedTextBox control is a control used to enter text in a specific format in Windows Forms. ResetOnPrompt and ResetOnSpace are its two important properties. Let me introduce the usage of these two properties:

  1. ResetOnPromptProperty

When the ResetOnPrompt property is set to true, after valid characters in the input control, if the user types the mask prompt character, the input is automatically cleared. For example, when you set the MaskedTextBox mask to "000-00-0000" (Social Security Number) and the ResetOnPrompt property is true, if the user enters "123-45" and then enters a mask after "-" Code prompt character "_", all input will be cleared, because this does not conform to the expected input.

  1. ResetOnSpaceProperty

When the ResetOnSpace property is set to true, the input is automatically cleared if the user types a space after a valid character in the input control. For example, when you set the MaskedTextBox mask to "00/00/0000" (date) and the ResetOnSpace property is true, if the user enters a space after the first "00", all entered content will be is cleared because this does not conform to the expected input.

In general, the ResetOnPrompt and ResetOnSpace properties can help you ensure the correctness of the format specified by the user input mask and improve the accuracy of data entry.

1.14 ShortcutsEnabled

The ShortcutsEnabled property of the MaskedTextBox control is used to control whether system shortcut keys are enabled. By default, the value of this property is true, which means the system shortcut keys are enabled.

When this property value is true, the following system shortcut keys will be available:

  • Ctrl+C: copy
  • Ctrl+X: Cut
  • Ctrl+V: Paste
  • Ctrl+A: Select all
  • Ctrl+Z: Undo
  • Ctrl+Y: Redo

If you need to disable these system shortcut keys, you can set this property to false. In this way, users will not be able to use shortcut keys to operate the content in the text box.

1.15 SkipLiterals

The SkipLiterals property of the MaskedTextBox control indicates whether to skip literals in the mask. Literal values ​​are the non-space characters in the mask that represent the fixed text that must be contained in the text box. For example, if the mask is "000-00-0000", then "-" is a literal value.

If the SkipLiterals property is set to true, only the portion of the mask that is not marked as literal will be displayed in the text box. In the above example, entering "123456789" will be displayed as "123-45-6789".

If the SkipLiterals property is set to false (the default), the text box will display the full mask and the literals will appear as they appear in the mask. In the above example, entering "123456789" will be displayed as "123-456-789".

It should be noted that the SkipLiterals property only affects the display of the text box and does not affect the actual value saved in the text box. Regardless of the value of the SkipLiterals property, the value in the text box will be in the format specified in the mask, including literal values ​​and spaces.

1.16 TextMaskFormat

The MaskedTextBox control is a Windows Forms control used for entering formatted text. It allows you to format input text such as phone numbers, zip codes, dates, etc.

The TextMaskFormat property is a property of the MaskedTextBox control, which determines whether the text entered in the control includes mask characters.

This property has two enumeration values:

  1. Mask: The input text includes mask characters. For example, when entering a phone number, the mask characters are brackets and dashes.

  2. ExcludePromptAndLiterals: The input text does not include mask characters. For example, when entering a phone number, only numeric characters are included.

The default value is Mask.

Here is a simple example demonstrating how to use the TextMaskFormat property:

//设置掩码格式
maskedTextBox1.Mask = "(999) 000-0000";

//设置TextMaskFormat属性为ExcludePromptAndLiterals(输入的文本不包括掩码字符)
maskedTextBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;

In the above example, we set the mask format of the MaskedTextBox control to "(999) 000-0000", and then set the TextMaskFormat property to ExcludePromptAndLiterals, which means that the entered text does not contain mask characters.

1.17 UseSystemPasswordChar

The MaskedTextBox control is a commonly used control in Winform and is used to enter masked text. Among them, the UseSystemPasswordChar attribute is used to display whether the entered characters are password characters. If set to true, the control will use the system's default password characters to hide the input content, otherwise the control will use custom password characters to hide the input content.

By default, the UseSystemPasswordChar property of the MaskedTextBox control is false, which uses a custom password character to hide the input content. This custom password character can be set through the PasswordChar property of the control. Normally we will set it to "*".

If we want to use the system's default password characters to hide the input content, we need to set the UseSystemPasswordChar property to true. At this time, the control will automatically use the system default password characters to hide the input content, without setting the PasswordChar property.

It should be noted that different operating systems may use different password characters, so cross-platform compatibility needs to be considered when setting the UseSystemPasswordChar property.

2. Common scenarios

The MaskedTextBox control is often used in scenarios where input text format needs to be restricted and controlled, such as:

  1. Date and time input: You can limit the date and time format input by users by setting the date format, etc.

  2. Phone number input: You can limit the phone number format entered by users by setting the phone number format (such as (999)999-9999).

  3. Postal code input: You can also limit the postal code format entered by users by setting the format.

  4. ID number input: You can limit the format of the ID number input by the user by setting the ID number format.

  5. Numeric input: You can restrict users to only enter numbers by setting the number format.

  6. Other specific format input: such as IP address, MAC address, etc.

3. Specific cases

Suppose we need to allow the user to enter a valid date, we can use the MaskedTextBox control to restrict the user to only enter dates that conform to the specified format.

First, create a Winform application in Visual Studio and add a MaskedTextBox control and a button control to the form.

Next, in the properties window of MaskedTextBox, set the Mask property to "00/00/0000", the TextMaskFormat property to "IncludeLiterals", and the SkipLiterals property to "False", indicating that mask characters are included and literal characters are ignored.

Add the following code to the button's Click event:

private void btnSubmit_Click(object sender, EventArgs e)
{
    
    
    DateTime inputDate;
    if (DateTime.TryParseExact(maskedTextBox1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out inputDate))
    {
    
    
        MessageBox.Show("输入的日期为:" + inputDate.ToString("dd/MM/yyyy"));
    }
    else
    {
    
    
        MessageBox.Show("请输入有效的日期");
    }
}

The above code will convert the date string entered by the user into the DateTime type. If the conversion can be successful, a message box will pop up to display the converted date. Otherwise, the user will be prompted to enter a valid date.

Finally, run the program, enter a valid date (such as 01/01/2021), click the submit button, and you will see the converted date information.

The complete code is as follows:

using System;
using System.Globalization;
using System.Windows.Forms;

namespace MaskedTextBoxDemo
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
    
    
            DateTime inputDate;
            if (DateTime.TryParseExact(maskedTextBox1.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out inputDate))
            {
    
    
                MessageBox.Show("输入的日期为:" + inputDate.ToString("dd/MM/yyyy"));
            }
            else
            {
    
    
                MessageBox.Show("请输入有效的日期");
            }
        }
    }
}

Insert image description here

Guess you like

Origin blog.csdn.net/aa2528877987/article/details/132869197