1. 程式人生 > >Winform的TextBox控制元件顯示預設文字點選消失離開顯示

Winform的TextBox控制元件顯示預設文字點選消失離開顯示

設定TextBox控制元件的預設文字即在載入TextBox控制元件時為其Text文字賦值。點選文字消失,離開或者失去焦點顯示預設文字可以通過Enter和Leave事件或Mouse的事件來實現。具體程式碼如下。

private void txtPassword_Enter(object sender, EventArgs e)
        {
            pnlPassword.BackgroundImage = ImageHelper.GetImage("Login\\login_account_focus.png");
            pnlAccount.BackgroundImage = ImageHelper.GetImage("Login\\login_account_default.png");

            if (txtPassword.Text.Trim() == "請輸入密碼")
            {
                txtPassword.ForeColor = ColorTranslator.FromHtml("#333333");
                txtPassword.Text = "";
                txtPassword.PasswordChar = '*';
            }
        }

        private void txtPassword_Leave(object sender, EventArgs e)
        {
            pnlPassword.BackgroundImage = ImageHelper.GetImage("Login\\login_account_default.png");

            if (txtPassword.Text.Trim().Length == 0)
            {
                txtPassword.ForeColor = ColorTranslator.FromHtml("#999999");
                txtPassword.PasswordChar = '\0';
                txtPassword.Text = "  請輸入密碼";
            }
        }