How to show text in combobox when no item selected?

前端 未结 16 1379
太阳男子
太阳男子 2020-11-30 06:39

C# & .Net 2.0 question (WinForms)

I have set of items in ComboBox and non of them selected. I would like to show a string on combo \"Pl

16条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 07:02

    Here you can find solution created by pavlo_ua: If you have .Net > 2.0 and If you have .Net == 2.0 (search for pavlo_ua answer)

    Cheers, jbk

    edit: So to have clear answer not just link

    You can set Text of combobox when its style is set as DropDown (and it is editable). When you have .Net version < 3.0 there is no IsReadonly property so we need to use win api to set textbox of combobox as readonly:

    private bool m_readOnly = false;
    private const int EM_SETREADONLY = 0x00CF;
    
    internal delegate bool EnumChildWindowsCallBack( IntPtr hwnd, IntPtr lParam );
    
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    internal static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
    
    [ DllImport( "user32.dll" ) ]
    internal static extern int EnumChildWindows( IntPtr hWndParent, EnumChildWindowsCallBack lpEnumFunc, IntPtr lParam );
    
    
    private bool EnumChildWindowsCallBackFunction(IntPtr hWnd, IntPtr lparam)
    {
          if( hWnd != IntPtr.Zero )
           {
                  IntPtr readonlyValue = ( m_readOnly ) ? new IntPtr( 1 ) : IntPtr.Zero;
                 SendMessage( hWnd, EM_SETREADONLY, readonlyValue, IntPtr.Zero );
                 comboBox1.Invalidate();
                 return true;
           }
           return false;
    }
    
    private void MakeComboBoxReadOnly( bool readOnly )
    {
        m_readOnly = readOnly;
        EnumChildWindowsCallBack callBack = new EnumChildWindowsCallBack(this.EnumChildWindowsCallBackFunction );
        EnumChildWindows( comboBox1.Handle, callBack, IntPtr.Zero );
    }
    

提交回复
热议问题