Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从类与winform上的textbox控件交互?_C#_.net - Fatal编程技术网

C# 如何从类与winform上的textbox控件交互?

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

我试图从项目中的一个类中获取窗体textbox控件的句柄,类似于此方法:

我就是不能让它工作。在我的form类中,我有以下内容:

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();