ComboBox本身没有ReadOnly属性,通常使用Enable=False来控制控件是否可以被使用。
但Enable=False后,外观不是很好看,客户希望ComboBox在不可使用的时候,
外观能和TextBox的ReadOnly外观一样。
所以,我就做了自定义ComboBox控件,追加了ReadOnly属性,
主要代码如下: public bool ReadOnly
{
get
{
return this._ReadOnly;
}
set
{
this._ReadOnly = value;
this.TabStop = !value;
if (value)
this.BackColor = System.Drawing.SystemColors.Control;
else
this.BackColor = System.Drawing.SystemColors.Window;
}
} protected override void WndProc(ref Message m)
{
if (this._ReadOnly && (m.Msg == 0xa1 || m.Msg == 0x200 || m.Msg == 0x201 ||
m.Msg == 0x202 || m.Msg == 0x203 || m.Msg == 0x204 || m.Msg == 0x205 ||
m.Msg == 0x206 || m.Msg == 0x207 || m.Msg == 0x208 || m.Msg == 0x209 ||
m.Msg == 0x20A))
{
return;
}
base.WndProc(ref m);
} 因为程序里使用到的ComboBox都是DropDownList样式的,所以上面的代码完全能控制住,没有问题。
但今天新做了一个From,上面的一个ComboBox被要求是DropDown样式,就是说可选也可以直接输入文字,
这下就出问题了,ReadOnly的时候,是无法从下拉列表中选择,但是直接输入文字却没被屏蔽掉。
请问,有什么办法能解决这个问题?
但Enable=False后,外观不是很好看,客户希望ComboBox在不可使用的时候,
外观能和TextBox的ReadOnly外观一样。
所以,我就做了自定义ComboBox控件,追加了ReadOnly属性,
主要代码如下: public bool ReadOnly
{
get
{
return this._ReadOnly;
}
set
{
this._ReadOnly = value;
this.TabStop = !value;
if (value)
this.BackColor = System.Drawing.SystemColors.Control;
else
this.BackColor = System.Drawing.SystemColors.Window;
}
} protected override void WndProc(ref Message m)
{
if (this._ReadOnly && (m.Msg == 0xa1 || m.Msg == 0x200 || m.Msg == 0x201 ||
m.Msg == 0x202 || m.Msg == 0x203 || m.Msg == 0x204 || m.Msg == 0x205 ||
m.Msg == 0x206 || m.Msg == 0x207 || m.Msg == 0x208 || m.Msg == 0x209 ||
m.Msg == 0x20A))
{
return;
}
base.WndProc(ref m);
} 因为程序里使用到的ComboBox都是DropDownList样式的,所以上面的代码完全能控制住,没有问题。
但今天新做了一个From,上面的一个ComboBox被要求是DropDown样式,就是说可选也可以直接输入文字,
这下就出问题了,ReadOnly的时候,是无法从下拉列表中选择,但是直接输入文字却没被屏蔽掉。
请问,有什么办法能解决这个问题?
private void comboBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if ((int)e.KeyChar < 32) // 控制键
{
return;
}
e.Handled = true;
return;
}ProcessCmdKey可以过滤快捷键,参考:定制C# TextBox中只允许输入数字的解决方法
>>但今天新做了一个From,上面的一个ComboBox被要求是DropDown样式如果这个ComboBox可以设置成DropDowmList,我还用得着来发贴嘛,
客户要求这个必须是DropDowm!
直接输入的文字还是会被现实在ComboBox上的。
ComboBox的KeyPress事件怎么没有的KeyPressEventArgs e怎么没有Concel()方法?
{
e.Handled = true;
}
输入的文字还是会被写到ComboBox上的。
public class TestComboBox : ComboBox
{
private bool _readOnly = false;
[DefaultValue(false)]
public bool ReadOnly
{
get
{
return this._readOnly;
}
set
{
if (this._readOnly != value)
{
this._readOnly = value;
}
}
} protected override void OnKeyPress(KeyPressEventArgs e)
{
if (this.ReadOnly)
{
e.Handled = true;
}
base.OnKeyPress(e);
}
}public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
TestComboBox test = new TestComboBox();
test.ReadOnly = true;
this.Controls.Add(test);
}
}
public const int EM_SETREADONLY = 0x00CF;
SendMessage( itemHwnd, EM_SETREADONLY ,0, 0);
{
if (this.ReadOnly)
{
e.Handled = true;
return; // 这地方得直接return。
}
base.OnKeyPress(e);
}
{
if (this.ReadOnly)
{
e.Handled = true;
return; // 这地方得直接return。
}
base.OnKeyPress(e);
} 这么做不能屏蔽↑↓啦。我也正犯愁。(ToT)/~~~