C# 如何从类与winform上的textbox控件交互?
我试图从项目中的一个类中获取窗体textbox控件的句柄,类似于此方法: 我就是不能让它工作。在我的form类中,我有以下内容:C# 如何从类与winform上的textbox控件交互?,c#,.net,C#,.net,我试图从项目中的一个类中获取窗体textbox控件的句柄,类似于此方法: 我就是不能让它工作。在我的form类中,我有以下内容: public Form1() { InitializeComponent(); id = new InputDevice(Handle, this); id.KeyPressed += new InputDevice.DeviceEventHandler(m_KeyPressed); } public void UpdateScanCode(strin
public Form1()
{
InitializeComponent();
id = new InputDevice(Handle, this);
id.KeyPressed += new InputDevice.DeviceEventHandler(m_KeyPressed);
}
public void UpdateScanCode(string scanCode)
{
txtScanCode.Text = scanCode;
}
Form mainForm;
public InputDevice( IntPtr hwnd, Form frmMain )
{
... stuff ...
mainForm = frmMain;
}
在我的InputDevice类中,我有:
public Form1()
{
InitializeComponent();
id = new InputDevice(Handle, this);
id.KeyPressed += new InputDevice.DeviceEventHandler(m_KeyPressed);
}
public void UpdateScanCode(string scanCode)
{
txtScanCode.Text = scanCode;
}
Form mainForm;
public InputDevice( IntPtr hwnd, Form frmMain )
{
... stuff ...
mainForm = frmMain;
}
…最后,在我的一个函数中:
mainForm.Update???
Intellisense无法找到UpdateScanCode函数,尽管它可以找到Form1的许多其他成员。当我尝试mainForm.UpdateScanCode()时,它不会编译
为什么这不起作用呢?您的
InputDevice
类引用的是基本表单
类,而不是扩展它的表单1
类。因此,您的代码可以编译,并且您可以从InputDevice
访问基本Form
类上可用的任何内容,但是您不能访问特定于Form1
的任何内容
将InputDevice
类修改为引用Form1
而不是Form
Form1 mainForm;
public InputDevice( IntPtr hwnd, Form1 frmMain )
{
... stuff ...
mainForm = frmMain;
}
甚至可能不需要将Form1
的实例传递给InputDevice
。如果“ScanCode”是InputDevice
上的公共属性(至少有一个公共的“getter”),您可以在Form1
中使用此代码:
id.KeyPressed += delegate { txtScanCode.Text = id.ScanCode; };
或者,扫描代码可能是通过该委托的事件参数传回的
id.KeyPressed += (s, e) => txtScanCode.Text = e.ScanCode;
尝试创建form1的对象,然后尝试访问。Like Form1 frmM=新Form1();frmM.UpdateScanCode();