Search code examples
c#winformsstatic

How to set a WinForm text property using string values in a private static void function


I am trying to incorporate some third party C# example code into my program. The third party code is part of a WinForms NET 4.6.2 application that scans devices on a COM port.

In my case, I want to insert a line (or two) of code within a method private static void PortStatusCallback(). My added code is designed to populate some text boxes on my Form1 with some of the variable values in PortStatusCallback(). The method in full is below; my proposed addition is the single line myPortname.Text = portname;. This addition returns the error message An object reference is required for the non-static field, method, or property 'Form1.myPortname'

Please can anyone suggest a way to access fields from a static method? I am new to C# programming so I would be grateful if you could write out the code for me. Thank you.

private DLL.PortStatusCallbackFuncPtr _PortStatusInstance = new DLL.PortStatusCallbackFuncPtr(PortStatusCallback);  // Allocated to prevent garbage collection

private static void PortStatusCallback([MarshalAs(UnmanagedType.LPStr)] String portname, DLL.PortStatusTypes status, byte curScanAdr, byte maxScanAdr, byte foundType)
        {
            string statusMsg = "\r\nPortInfo Callback: " + portname + " status:" + status.ToString() + " curScanAdr:" + curScanAdr.ToString() + " maxScanAdr:" + maxScanAdr.ToString() + " foundType:" + foundType.ToString("X2");

            myPortname.Text = portname; // this line is added by me and throws up a CS0120 error.

            MyStatusBox.Invoke((MethodInvoker)delegate () { MyStatusBox.AppendText(statusMsg); });

            Console.Write(statusMsg);
        }

Solution

  • This answer assumes that your Form1 class represents the main form for your application; that one instance of the class is created in Program.cs, that no other instances are ever created, and when you close the form, the app goes away (i.e., a typical WinForms app).

    Create a semi-private property:

    public static Form1 CurrentForm { get; private set; }
    

    In the Form1 constructor (or in the Load handler), do the following:

    CurrentForm = this;
    

    Now, the expression Form1.CurrentForm will resolve to your main form (from anywhere in your application).

    Finally change the line that is erroring on you to:

    CurrentForm.myPortname.Text = portname;