1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WinFormsのComboBoxにReadOnlyを無理矢理設定する

1
Posted at

結論。金があるならComponentOneとかInputManとか買いなさい。

資金がなくて要望を断りきれないときの苦肉の策。

やってることはComboBoxの上にReadOnlyのTextBoxを重ねて置いているだけ。
デザイナで配置するとエラー吐かれるのでParentが設定されてから動作するように組んだ。

public class ComboBoxEx : ComboBox
{
    public ComboBoxEx()
    {
        this.DropDownStyle = ComboBoxStyle.DropDownList;
    }

    private TextBox _txt = null; // 代替表示用
    private bool _readOnly = false;
    public bool ReadOnly
    {
        get { return _readOnly; }
        set
        {
            _readOnly = value;
            if (_readOnly)
            {
                if (_txt == null && this.Parent != null)
                {
                    _txt = new TextBox();
                    this.Parent.Controls.Add(_txt);
                }
                if (_txt != null)
                {
                    _txt.BringToFront(); // 先頭表示
                    _txt.Multiline = true;
                    _txt.Left = this.Left;
                    _txt.Top = this.Top;
                    _txt.Width = this.Width - SystemInformation.MenuButtonSize.Width;
                    _txt.Height = this.Height;
                    _txt.TabIndex = this.TabIndex;
                    _txt.ReadOnly = true;
                    _txt.Visible = false;
                    _txt.Text = this.Text;
                    _txt.Visible = _readOnly;
                    this.Enabled = !_readOnly;
                }
            }
            else
            {
                if (_txt != null)
                {
                    this.Enabled = !_readOnly;
                    _txt.Visible = _readOnly;
                }
            }
        }
    }
}

DropDownButtonの幅をSystemInformation.MenuButtonSizeに依存してるので
フォントサイズ変えたらたぶん変になる。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?