Modify label of a winform from console application

55 Views Asked by At

I have the following question. Let me put it in context: I have a winform in the .NET Framework, with a label. In a different project, which is a console application, I want to be able to access the label and modify its text with one provided by the console application. To note, the winform is opened first and the console application is executed on demand with the text as a parameter to update the form label I have tried many options that I have found in searches on the internet and here in the forum, but none of them have worked for me. I wonder if it is possible? Any suggestions, ideas or similar.

1

There are 1 best solutions below

2
dosung Yoon On
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, string lParam);

    [DllImport("user32.dll")]
    static extern bool UpdateWindow(IntPtr hWnd);

    [DllImport("user32")]
    static extern int GetDC(int hwnd);

    [DllImport("user32")]
    static extern int ReleaseDC(int hwnd, int hdc);

    [STAThread]
    static void Main()
    {
        const uint WM_SETTEXT = 0x000C;
        const uint WM_PAINT = 0x000F;

        Process p = Process.GetProcessesByName("TestApp1")[0];
        AutomationElement el = AutomationElement.FromHandle(p.MainWindowHandle);
        AutomationElementCollection aryel = el.FindAll(TreeScope.Descendants, new AndCondition(new PropertyCondition(AutomationElement.IsControlElementProperty, true), new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text))) ;
        if (aryel.Count > 0)
        {
            foreach (AutomationElement t in aryel)
            {
                switch (t.Current.AutomationId)
                {
                    case "label_a":
                        SendMessage(new IntPtr(t.Current.NativeWindowHandle), WM_SETTEXT, IntPtr.Zero, "KKKKK");
                        break;

                    default:
                        break;
                }
            }
        }
    }