C# Winform | Watermark in a textbox | Placeholder | custom control
1. TextBox 상속 클래스 만들기
프로젝트 -> 새 항목 추가 -> 클래스
클래스 이름 : wmTextBox.cs
2. TextBox 상속 클래스 Code 작성
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public class wmTextBox : TextBox
{
public wmTextBox()
{
}
private string watermarkText;
private Color watermarkColor = Color.Gray;
private bool watermarkState;
private Color tempFontColor;
[Category("Watermark")]
[Description("WatermarkText text.")]
public string WatermarkText
{
get
{
return watermarkText;
}
set
{
this.watermarkText = value;
if(this.Text == "")
{
tempFontColor = this.ForeColor;
this.Text = this.watermarkText;
this.ForeColor = this.WatermarkColor;
watermarkState = true;
}
Invalidate();
}
}
[AmbientValue(typeof(Color), "Empty")]
[Category("Watermark")]
[DefaultValue(typeof(Color), "Gray")]
[Description("WatermarkColor text Color.")]
public Color WatermarkColor
{
get { return watermarkColor; }
set {
watermarkColor = value;
Invalidate();
}
}
protected override void OnCreateControl()
{
base.OnCreateControl();
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
}
protected override void OnEnter(EventArgs e)
{
if (watermarkState)
{
this.Text = "";
this.ForeColor = tempFontColor;
}
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
if (this.Text == "")
{
this.Text = this.WatermarkText;
this.ForeColor = WatermarkColor;
watermarkState = true;
}
else
{
watermarkState = false;
}
base.OnLeave(e);
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
e.Handled = true;
}
base.OnKeyPress(e);
}
}
|
cs |
3. 솔루션 빌드
클래스를 추가하고 [솔루션 빌드]를 진행하면 [도구 상자]에서 컨트롤을 추가할 수있다.
4. Custom Control 추가
[솔루션 빌드] 이후 [도구 상자]에서 생성된 wmTextBox를 Form에 추가한다.
5. Property 설정
wmTextBox의 Watermark 속성을 지정한다.
Result
'C# Winform' 카테고리의 다른 글
C# Winform | textbox vertical alignment | custom control (10) | 2020.12.04 |
---|---|
List Of Windows Messages | WndProc (0) | 2020.11.30 |
C# Winform | remove zero from decimal c# (0) | 2020.11.16 |
C# Winform | TabControl / Modern Design UI - #2 (0) | 2020.11.04 |
C# Winform | TabControl / Modern Design UI - #1 (2) | 2020.11.02 |