如何:使 comboBox 輸入狀態變成 readonly 方式;TextBox 唯讀時的效果;

來源:互聯網
上載者:User

傳統型應用程式中的
comboBox 下拉框,輸入方式;
分為3種狀態
 Simple 文本部分可編輯。列表部分總可見。
 DropDown 文本部分可編輯。使用者必須單擊箭頭按鈕來顯示列表部分。這是預設樣式。
 DropDownList 使用者不能直接編輯文本部分。使用者必須單擊箭頭按鈕來顯示列表部分。

卻沒有 readonly 狀態;有些時候客戶要copy 下拉框裡的資料確實挺鬱悶的,為啥沒有?這個得問ms 了呵呵
不過 comboBox 其實是一個嵌套控制項(複合控制項)在 DropDownList  狀態時;他由 下拉式清單,和 comboBox  本身組成
DropDown 狀態時 comboBox  中多了一個 edit 就是 .net 下的 TextBox 那個輸入狀態是由 edit 控制的;
不過這個 edit 是無法在 .net 下取得的 this.comboBox1.Controls.Count 返回 0;

既然知道原理瞭解決問題也就相對簡單的(不用 Win API 看來是不行了)
現在我們需要知識
1) 如果取得子控制項;這個有多種方法可以實現我們選擇 GetWindow 這個 API 取xx視窗或控制項下的第一個子控制項比較方便也不用回調什麼的;
    比 EnumWindows API 容易用多了
2) 如何給 edit (TextBox) 設定唯讀狀態;
   這個就是發個訊息基本可以搞定(不過忘記是那個訊息了),看看 msdn 找 em_ 開頭的訊息,找到 EM_SETREADONLY 看名字就是他了;
  根據 SDK 規則,em_ 開頭的訊息都是對應 edit 的;

開啟代碼編輯器,幾行搞定;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
{
    
    public partial class Form1 : Form
    {

        //using System.Runtime.InteropServices;
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetWindow(IntPtr hWnd, int uCmd);
        int GW_CHILD = 5;
        
        
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
        public const int EM_SETREADONLY = 0xcf;

        public Form1()
        {
            InitializeComponent();
            
            IntPtr editHandle = GetWindow(comboBox1.Handle , GW_CHILD);
            SendMessage(editHandle,EM_SETREADONLY,1,0);
            
            
        }        
    }

    
}

好了結合我以前的一個blog
http://blog.csdn.net/FlashElf/archive/2004/10/31/161024.aspx

不但可以readonly 還可以限制輸入;
打完收工;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.