HerrimanCoder
HerrimanCoder

Reputation: 7226

How to interact with textbox control on winform from class?

I am trying to get a handle to my form's textbox control from a class in the project, similar to this approach:

How to access Winform textbox control from another class?

I just cannot get it to work. Inside my form class I have this:

public Form1()
{
  InitializeComponent();
  id = new InputDevice(Handle, this);
  id.KeyPressed += new InputDevice.DeviceEventHandler(m_KeyPressed);
}

public void UpdateScanCode(string scanCode)
{
     txtScanCode.Text = scanCode;
}

Then inside my InputDevice class I have this:

Form mainForm;
public InputDevice( IntPtr hwnd, Form frmMain )
{
   ... stuff ...
   mainForm = frmMain;
}

...and finally, inside one of my functions:

mainForm.Update???

Intellisense cannot find the UpdateScanCode function, though it finds lots of other members of Form1. When I try mainForm.UpdateScanCode() it won't compile.

Why won't this work?

Upvotes: 1

Views: 121

Answers (1)

Grant Winney
Grant Winney

Reputation: 66511

Your InputDevice class is referencing the base Form class, not your Form1 class that's extending it. So your code compiles, and you can access anything available on the base Form class from InputDevice, but you can't access anything specific to Form1.

Modify your InputDevice class to reference Form1 instead of Form.

Form1 mainForm;
public InputDevice( IntPtr hwnd, Form1 frmMain )
{
   ... stuff ...
   mainForm = frmMain;
}

There may not even be a need to pass the instance of Form1 to InputDevice. If "ScanCode" were a public property on InputDevice (with a public "getter" at least), you could just use this code in Form1 instead:

id.KeyPressed += delegate { txtScanCode.Text = id.ScanCode; };

Or perhaps the scan code is passed back via the event arguments of that delegate?

id.KeyPressed += (s, e) => txtScanCode.Text = e.ScanCode;

Upvotes: 2

Related Questions