我试图在启动应用程序时在表单上的 ALL 控件上强制执行CreateHandles。
之所以这样做,是因为我使用invoke方法将数据添加到UI控件,并且收到错误消息,提示该控件未创建任何Handle。因此,我正在考虑在运行任何其他代码之前启动应用程序和CreateHandles时进行安全检查。
但是我确实从下面的代码中收到此错误消息。在某种程度上,我理解错误消息的概念,但不知道如何为此更改/添加任何代码,以便我可以访问控件?
control.CreateHandle();
无法通过类型'Control'的限定符访问受保护的成员控件.CreateHandle();限定符的类型必须为“ Form1”(从中排序)
完整代码:
public Form1()
{
InitializeComponent();
Thread thread = new Thread(() => EnumerateChildren(this)); thread.IsBackground = true; thread.Start();
}
public void EnumerateChildren(Control root)
{
foreach (Control control in root.Controls)
{
if (control.IsHandleCreated)
{
//Handle is already created
}
else
{
//Force to Create a handle but gives this error:
//Cannot access a protected member control.CreateHandle() via a qualifier of type 'Control'; the qualifier must be of type 'Form1' (orderived from it)
control.CreateHandle();
}
if (control.Controls != null)
{
EnumerateChildren(control);
}
}
}
我测试过将以下代码添加到“ else”语句中,其中第二个消息框应显示“ True”,但这并不总是发生?
else
{
//Force to Create a handle but gives this error:
//Cannot access a protected member control.CreateHandle() via a qualifier of type 'Control'; the qualifier must be of type 'Form1' (orderived from it)
MessageBox.Show("Handle is not created: " + control.IsHandleCreated.ToString());
control.CreateControl();
MessageBox.Show("Handle should be created?: " + control.IsHandleCreated.ToString());
}
答案 0 :(得分:0)
如果CreateControl()无法成功创建句柄,我确实添加了逻辑。我直接执行createHandle(),所有控件现在都显示为true,这意味着它似乎可以正常工作。
所有控件都在这里得到处理。请告诉您这是否是错误的方法?
public void EnumerateChildren(Control root)
{
foreach (Control control in root.Controls)
{
if (control.IsHandleCreated)
{
//Handle is already created
}
else
{
control.CreateControl();
if (control.IsHandleCreated == false)
{
//The access the handle directly
MethodInfo ch = control.GetType().GetMethod("CreateHandle", BindingFlags.NonPublic | BindingFlags.Instance);
Invoke((System.Windows.Forms.MethodInvoker)delegate { ch.Invoke(control, new object[0]); });
}
}
if (control.Controls != null)
{
EnumerateChildren(control);
}
}
}