1
0

WinFormsTestUtils.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. #if HAS_WINFORMS
  5. using System;
  6. using System.Threading;
  7. using System.Windows.Forms;
  8. namespace ReactiveTests.Tests
  9. {
  10. internal static class WinFormsTestUtils
  11. {
  12. private static readonly Semaphore s_oneWinForms = new(1, 1);
  13. public static IDisposable RunTest(out Label label)
  14. {
  15. s_oneWinForms.WaitOne();
  16. var loaded = new ManualResetEvent(false);
  17. var lbl = default(Label);
  18. var t = new Thread(() =>
  19. {
  20. lbl = new Label();
  21. var frm = new Form { Controls = { lbl }, Width = 0, Height = 0, FormBorderStyle = FormBorderStyle.None, ShowInTaskbar = false };
  22. frm.Load += (_, __) =>
  23. {
  24. loaded.Set();
  25. };
  26. Application.Run(frm);
  27. });
  28. t.SetApartmentState(ApartmentState.STA);
  29. t.Start();
  30. loaded.WaitOne();
  31. label = lbl;
  32. return new RunWinFormsTest(label, t);
  33. }
  34. private sealed class RunWinFormsTest : IDisposable
  35. {
  36. private readonly Label _lbl;
  37. private readonly Thread _t;
  38. public RunWinFormsTest(Label lbl, Thread t)
  39. {
  40. _lbl = lbl;
  41. _t = t;
  42. }
  43. public void Dispose()
  44. {
  45. _lbl.Invoke(new Action(() =>
  46. {
  47. Application.Exit();
  48. }));
  49. _t.Join();
  50. s_oneWinForms.Release();
  51. }
  52. }
  53. }
  54. }
  55. #endif