How to use while(true) in my case? The idea is this: to display text from another program's textbox , into one's form. On click, everything works, but I would like to monitor this textbox with an interval of 1s ...

  void Button2Click(object sender, EventArgs e) { var hWndParent = FindWindow(null, "Test(GetLbl)"); Thread thread = new Thread(() => FindChild(hWndParent)); thread.Start(); thread.IsBackground = true; } public void FindChild(IntPtr hWndParent){ while(true){ EnumChildWindows(hWndParent, new EnumWindowsProc(( hWnd, lParam ) => { if (GetParent(hWnd) != hWndParent){ return true; } FindChild(hWnd); if(GetText(hWnd).StartsWith("This is my Rich")){ if(label1.InvokeRequired){ label1.Invoke(new MethodInvoker(delegate { label1.Text = GetText(hWnd); })); } } return true; }), IntPtr.Zero); Thread.Sleep(1000); } 
  • standard WinForms-timer than not happy? and monitor yourself at any intervals. And there is no need to bother with the streams, everything is done right out of the box. - rdorn

2 answers 2

You can do without a separate stream:

  void Button2Click(object sender, EventArgs e) { var hWndParent = FindWindow(null, "Test(GetLbl)"); FindChild(hWndParent); } public async Task FindChild(IntPtr hWndParent) { while (true) { EnumChildWindows(hWndParent, new EnumWindowsProc((hWnd, lParam) => { if (GetParent(hWnd) != hWndParent) { return true; } FindChild(hWnd); if (GetText(hWnd).StartsWith("This is my Rich")) { /* поток тот же, так что Invoke() не нужен */ label1.Text = GetText(hWnd); } return true; }), IntPtr.Zero); await Task.Delay(1000); } } 
  • works, but the window hangs ... - Little Fox
  • It would be necessary to make a search out of the loop. It should not hang. - Qwertiy

"the window hangs up" precisely because the "same thread". In the @Surfin Bird answer, try adding .ConfigureAwait (false) to await Task.Delay (1000) - then after the first delay, the execution should go to another thread. Well, label1, depending on depending on if (label1.InvokeRequired) On the other hand, what does your own option not do if everything works? If you don’t like the "on click" launch, then you can probably hang this code on the form opening event.