'Getting Label's Text From Static Method

I'm trying to take label1.Text how can i do it from static method (Windows Form)

public static IntPtr hookProc(int code, IntPtr wParam, IntPtr lParam)
{         
    if (code >= 0 && wParam == (IntPtr)WM_KEYUP)
    {
        int vkCode = Marshal.ReadInt32(lParam);

        if (vkCode.ToString() == "117") //F6
        {                    
            MessageBox.Show(**label1.Text**)
        }

    return (IntPtr)1;
}


Solution 1:[1]

Assuming that you use WinForms and label1 is Label control on MyForm you have to find the (right) instance of MyForm (which label1 should we use if we have, say, three opened MyForm instances?):

 using System.Linq;
 ...

 MessageBox.Show(Application
   .OpenForms
   .OfType<MyForm>()
   .Last()
  ?.label1
  ?.Text ?? "Some Default Value");

Here we use the last opened instance of MyForm and if it exists get label1; please, note that either label1 must be accessible from hookProc, i.e. hookProc is implemented within MyForm or label1 is declared as public.

Solution 2:[2]

Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

Assuming label1 is instance variable, you should pass its text as 1 of parameters to your function

public static IntPtr hookProc(int code, IntPtr wParam, IntPtr lParam, string labelText)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitry Bychenko
Solution 2 Dzianis Karpuk