c# -复选框的高度从它设置的位置偏移1个像素
本文关键字:位置 设置 1个 像素 复选框 高度 | 更新日期: 2023-09-27 18:02:29
使用SetPropertyBulk
方法将CheckBox的高度设置为16,其实际高度最终会额外增加1像素(17)。
public IEnumerable<Control> GetAllControls(Control parentControl, Type type = null)
{
var controls = parentControl.Controls.Cast<Control>();
if (type != null)
{
return
controls.SelectMany(ctrl => GetAllControls(ctrl, type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
return controls.SelectMany(ctrl => GetAllControls(ctrl)).Concat(controls);
}
public void SetPropertyBulk(string propertyS, object val, Type t = null,
Control parentControl = null)
{
Control parent = parentControl ?? _f;
foreach (Control c in GetAllControls(parent, t))
{
PropertyInfo p;
try
{
p = c.GetType().GetProperty(propertyS,
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.FlattenHierarchy);
}
catch (AmbiguousMatchException)
{
p = c.GetType().GetProperty(propertyS,
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.DeclaredOnly);
Debug.Print($"Ambiguous match for property {propertyS} " +
$"in control {c}");
}
if (p != null && p.CanWrite)
{
try
{
p.SetValue(c, val, null);
Debug.Print($"================'n" +
$"Set property'n" +
$"Type: {c}'n" +
$"Property: {p.Name}'n" +
$"Value: {val}'n" +
$"Check: {p.GetValue(c)}");
}
catch (ArgumentException)
{
Debug.Print(
$"The given value {val} is not valid for the " +
$"given property {propertyS} in control {c}.");
}
}
else
{
Debug.Print($"The given property {propertyS} does not " +
$"exist for control {c}.");
}
}
}
public void SetPropertyBulk(string propertyS, object val, ICollection<Type> t,
Control parentControl = null)
{
foreach (Type type in t)
{
SetPropertyBulk(propertyS, val, type);
}
}
我在form load事件中调用方法,像这样:
const int cHeight = 16;
SetPropertyBulk("Height", cHeight,
new List<Type>
{
typeof(Label),
typeof(CheckBox),
typeof(TextBox),
typeof(NumericUpDown)
});
SetPropertyBulk("MinimumSize", new Size(0, cHeight),
new List<Type> {typeof(Label), typeof(CheckBox)});
SetPropertyBulk("AutoSize", true,
new List<Type> {typeof(Label), typeof(CheckBox)});
我正在检查height属性的值,如下所示:
Debug.Print($"Check Top: {GenChkScreen.Top}");
Debug.Print($"Check Bottom: {GenChkScreen.Bottom}");
Debug.Print($"Check Height: {GenChkScreen.Height}");
返回:
Check Top: 15
Check Bottom: 32
检查高度:17
我在SetPropertyBulk
中也有一个Debug.Print
,对于CheckBox返回:
================
集属性
类型:System.Windows.Forms。CheckBox, CheckState: 0
属性:高度
值:16
检查:16
前一个调试输出返回的高度是17,而后一个调试输出中的PropertyInfo.GetValue()
返回的高度是16。通过将CheckBox的BackColor
属性设置为与窗体不同的颜色并计算像素,CheckBox的实际大小为17。
为什么高度没有被设置为16?为什么PropertyInfo.GetValue()
返回错误的高度(或者,我不知道,高度在SetPropertyBulk
中设置后再次更改)
我没有将MaximumSize
设置为16,以防止AutoSize
越过。