C# TextBoxに入力された文字を隠す

  • 作成日 2021.09.08
  • 更新日 2022.04.09
  • C#
C# TextBoxに入力された文字を隠す

C#で、PasswordCharを使用して、TextBoxに入力された文字を隠すサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Microsoft Visual Studio Community 2019 Version 16.7.1

PasswordChar使い方

PasswordCharに隠す際に利用する文字列を指定することで、入力された文字を隠すことが可能です。

textBox1.PasswordChar = '*';

サンプルコード

以下は、
「実行」ボタンをクリックすると、TextBoxに入力された文字を隠す
サンプルコードとなります。

using System;
using System.Windows.Forms;

namespace FormTestApp
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.PasswordChar == '\0')
            {
                textBox1.PasswordChar = '●';
            }
            else
            {
                // 解除
                textBox1.PasswordChar = '\0';
            }
        }
    }
}

入力された文字が隠されていることが確認できます。