How to access form controls from "static" methods?

J

Jon E. Scott

I'm a little confused with "static" methods and how to access other unstatic
methods. I'm a little new to C#.

I'm testing a callback routine within a DLL and the callback function
returns a string as one of the arguments. As shown below, I have no
problems showing the string in the Report() method in a messagebox or
console window, but how does one access a memo or label on a form from a
static method? I want to throw the strings from the callback function into
a memo control on the form.

namespace WindowsApplication1
{
public partial class Form1 : Form
{
private delegate void CallBack(int testInt, string testStr);

[DllImport("N:\\Temp\\Project1.dll")]
private static extern bool TestCallBack(CallBack x);

private void UpdateStatus(string status)
{
label1.Text = status;
}

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
CallBack myCallBack = new CallBack(Form1.Report);
TestCallBack(myCallBack);
}

private static void Report(int testInt, string testStr)
{
//Form1.UpdateStatus(testStr);
MessageBox.Show(string.Concat(testInt.ToString(), " - ",
testStr));
}
}
}
 
B

Brian Gideon

Jon,

Make the callback method an instance member instead of a static member.
When creating the callback delegate use the syntax this.Report instead
of Form1.Report.

Brian
 
D

DeveloperX

One option would be to have a static member variable which holds a
reference to the form, then you would just need to beginInvoke on the
control on the form.
 
B

Brian Gideon

DeveloperX said:
One option would be to have a static member variable which holds a
reference to the form, then you would just need to beginInvoke on the
control on the form.

If there is more than one of the same Form running then the callback
method would see the value of that variable as it was set by the last
created instance.

Also, it's not completely clear that BeginInvoke is needed. If
TestCallBack executes synchronously then the callback will be executing
on the UI thread as well. If TestCallBack executes asynchronously then
BeginInvoke would be needed.
 
D

DeveloperX

Very true, I could of fleshed that out an mentioned InvokeRequired, etc
but it looked asynchronous (don't make me justify that ;)). I did
consider mentioning schemes for handling multiple instances of the
form, but assumed it wasn't a requirement based on the snippet :)
 
J

Jon E. Scott

Make the callback method an instance member instead of a static member.
When creating the callback delegate use the syntax this.Report instead
of Form1.Report.

Knew it was something simple like that. Got it working. Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top