TextBox에 PlaceHolder 기능을 추가해야 해서 이것 저것 해보다가

 

OnPaint로 그릴 생각까지 했는데 분면 OnPaint를 오버라이드 했는데도 이벤트가 발생하지 않았습니다.

그럴때는 서브클래싱한 컨트롤에서 SetStyle을 설정('SetStyle(ControlStyles.userPaint, true)')해줘야 합니다.

 

SetStyle : http://msdn.microsoft.com/ko-kr/library/system.windows.forms.control.setstyle.aspx

 

그런데 구글링으로 찾은 소스중 보다 Win32 API를 이용해서 텍스트박스에 PlaceHolder 기능을 구현한게 있네요.

 

public class CueTextBox : TextBox
{  
    private static class NativeMethods
    {
        private  const uint ECM_FIRST       = 0x1500;
        internal const uint EM_SETCUEBANNER = ECM_FIRST + 1;
        [DllImport("user32.dll", EntryPoint = "SendMessageW")]
        public static extern IntPtr SendMessageW(IntPtr hWnd, UInt32 Msg, IntPtr wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
    }
    private string _cue;
    [
        Description("PlaceHolder로 사용될 텍스트"),
        Category("Appearance"),
        Browsable(true),
    ]        
    public string Cue
    {
        get
        {
            return _cue;
        }
        set
        {
            _cue = value;
            UpdateCue();
        }
    }
    public CueTextBox()
    {
        this.SetStyle(ControlStyles.UserPaint, false);
        this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
    }
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
    }
    private void UpdateCue()
    {
        if (IsHandleCreated && _cue != null)
        {
            NativeMethods.SendMessageW(Handle, NativeMethods.EM_SETCUEBANNER, (IntPtr)1, _cue);
        }
    }
    protected override void OnHandleCreated(EventArgs e)
    {
        base.OnHandleCreated(e);
        UpdateCue();
    }
}


'.Net > WinForm' 카테고리의 다른 글

[.Net] FolderbrowserDialog Custom Action  (0) 2014.02.08
[WinForm] OpenFileDialog  (0) 2013.03.13
posted by 뚱2