Search code examples
c#textstaticlabel

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

  • 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.