Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. using System;
  2. using System.Drawing;
  3. using System.Threading;
  4. using System.Windows.Forms;
  5.  
  6. internal sealed class TestCursorController : IDisposable
  7. {
  8. private static int hasMutex;
  9. private static readonly Mutex CrossProcessMutex = new Mutex(initiallyOwned: false, "Cursor");
  10.  
  11. private readonly Point originalPosition;
  12. private readonly Rectangle originalClip;
  13. private int isDisposed;
  14.  
  15. public static TestCursorController AssertControl() => new TestCursorController();
  16.  
  17. private TestCursorController()
  18. {
  19. if (Interlocked.Exchange(ref hasMutex, 1) != 0)
  20. throw new InvalidOperationException($"Tests that use {nameof(TestCursorController)} must be set to not run in parallel with one another.");
  21.  
  22. if (!CrossProcessMutex.WaitOne(TimeSpan.FromSeconds(10)))
  23. throw new TimeoutException("Another process is using the cursor.");
  24.  
  25. originalPosition = Cursor.Position;
  26. originalClip = Cursor.Clip;
  27. }
  28.  
  29. public void Dispose()
  30. {
  31. CrossProcessMutex.ReleaseMutex();
  32.  
  33. if (Interlocked.Exchange(ref isDisposed, 1) != 0) return;
  34.  
  35. Cursor.Clip = originalClip;
  36. Cursor.Position = originalPosition;
  37.  
  38. Volatile.Write(ref hasMutex, 0);
  39. }
  40.  
  41. public void SetPosition(Control control, Point relativePosition)
  42. {
  43. if (control is null) throw new ArgumentNullException(nameof(control));
  44.  
  45. SetPosition(control.PointToScreen(relativePosition));
  46. }
  47.  
  48. private static void SetPosition(Point screenPosition)
  49. {
  50. Cursor.Clip = new Rectangle(screenPosition, new Size(1, 1));
  51. }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement