WindowsDriver.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775
  1. //
  2. // WindowsDriver.cs: Windows specific driver
  3. //
  4. // Authors:
  5. // Miguel de Icaza ([email protected])
  6. // Nick Van Dyck ([email protected])
  7. //
  8. // Copyright (c) 2018
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11. // of this software and associated documentation files (the "Software"), to deal
  12. // in the Software without restriction, including without limitation the rights
  13. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. // copies of the Software, and to permit persons to whom the Software is
  15. // furnished to do so, subject to the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be included in all
  18. // copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  26. // SOFTWARE.
  27. //
  28. using NStack;
  29. using System;
  30. using System.ComponentModel;
  31. using System.Runtime.InteropServices;
  32. using System.Threading;
  33. using System.Threading.Tasks;
  34. namespace Terminal.Gui {
  35. internal class WindowsConsole {
  36. public const int STD_OUTPUT_HANDLE = -11;
  37. public const int STD_INPUT_HANDLE = -10;
  38. public const int STD_ERROR_HANDLE = -12;
  39. internal IntPtr InputHandle, OutputHandle;
  40. IntPtr ScreenBuffer;
  41. uint originalConsoleMode;
  42. CursorVisibility? initialCursorVisibility = null;
  43. CursorVisibility? currentCursorVisibility = null;
  44. CursorVisibility? pendingCursorVisibility = null;
  45. public WindowsConsole ()
  46. {
  47. InputHandle = GetStdHandle (STD_INPUT_HANDLE);
  48. OutputHandle = GetStdHandle (STD_OUTPUT_HANDLE);
  49. originalConsoleMode = ConsoleMode;
  50. var newConsoleMode = originalConsoleMode;
  51. newConsoleMode |= (uint)(ConsoleModes.EnableMouseInput | ConsoleModes.EnableExtendedFlags);
  52. newConsoleMode &= ~(uint)ConsoleModes.EnableQuickEditMode;
  53. newConsoleMode &= ~(uint)ConsoleModes.EnableProcessedInput;
  54. ConsoleMode = newConsoleMode;
  55. }
  56. public CharInfo [] OriginalStdOutChars;
  57. public bool WriteToConsole (CharInfo [] charInfoBuffer, Coord coords, SmallRect window)
  58. {
  59. if (ScreenBuffer == IntPtr.Zero) {
  60. ReadFromConsoleOutput (new Size (Console.WindowWidth, Console.WindowHeight), coords, ref window);
  61. }
  62. return WriteConsoleOutput (ScreenBuffer, charInfoBuffer, coords, new Coord () { X = window.Left, Y = window.Top }, ref window);
  63. }
  64. public void ReadFromConsoleOutput (Size size, Coord coords, ref SmallRect window)
  65. {
  66. ScreenBuffer = CreateConsoleScreenBuffer (
  67. DesiredAccess.GenericRead | DesiredAccess.GenericWrite,
  68. ShareMode.FileShareRead | ShareMode.FileShareWrite,
  69. IntPtr.Zero,
  70. 1,
  71. IntPtr.Zero
  72. );
  73. if (ScreenBuffer == INVALID_HANDLE_VALUE) {
  74. var err = Marshal.GetLastWin32Error ();
  75. if (err != 0)
  76. throw new System.ComponentModel.Win32Exception (err);
  77. }
  78. if (!initialCursorVisibility.HasValue && GetCursorVisibility (out CursorVisibility visibility)) {
  79. initialCursorVisibility = visibility;
  80. }
  81. if (!SetConsoleActiveScreenBuffer (ScreenBuffer)) {
  82. var err = Marshal.GetLastWin32Error ();
  83. throw new System.ComponentModel.Win32Exception (err);
  84. }
  85. OriginalStdOutChars = new CharInfo [size.Height * size.Width];
  86. ReadConsoleOutput (OutputHandle, OriginalStdOutChars, coords, new Coord () { X = 0, Y = 0 }, ref window);
  87. }
  88. public bool SetCursorPosition (Coord position)
  89. {
  90. return SetConsoleCursorPosition (ScreenBuffer, position);
  91. }
  92. public void SetInitialCursorVisibility ()
  93. {
  94. if (initialCursorVisibility.HasValue == false && GetCursorVisibility (out CursorVisibility visibility)) {
  95. initialCursorVisibility = visibility;
  96. }
  97. }
  98. public bool GetCursorVisibility (out CursorVisibility visibility)
  99. {
  100. if (!GetConsoleCursorInfo (ScreenBuffer, out ConsoleCursorInfo info)) {
  101. var err = Marshal.GetLastWin32Error ();
  102. if (err != 0) {
  103. throw new System.ComponentModel.Win32Exception (err);
  104. }
  105. visibility = Gui.CursorVisibility.Default;
  106. return false;
  107. }
  108. if (!info.bVisible)
  109. visibility = CursorVisibility.Invisible;
  110. else if (info.dwSize > 50)
  111. visibility = CursorVisibility.Box;
  112. else
  113. visibility = CursorVisibility.Underline;
  114. return true;
  115. }
  116. public bool EnsureCursorVisibility ()
  117. {
  118. if (initialCursorVisibility.HasValue && pendingCursorVisibility.HasValue && SetCursorVisibility (pendingCursorVisibility.Value)) {
  119. pendingCursorVisibility = null;
  120. return true;
  121. }
  122. return false;
  123. }
  124. public void ForceRefreshCursorVisibility ()
  125. {
  126. if (currentCursorVisibility.HasValue) {
  127. pendingCursorVisibility = currentCursorVisibility;
  128. currentCursorVisibility = null;
  129. }
  130. }
  131. public bool SetCursorVisibility (CursorVisibility visibility)
  132. {
  133. if (initialCursorVisibility.HasValue == false) {
  134. pendingCursorVisibility = visibility;
  135. return false;
  136. }
  137. if (currentCursorVisibility.HasValue == false || currentCursorVisibility.Value != visibility) {
  138. ConsoleCursorInfo info = new ConsoleCursorInfo {
  139. dwSize = (uint)visibility & 0x00FF,
  140. bVisible = ((uint)visibility & 0xFF00) != 0
  141. };
  142. if (!SetConsoleCursorInfo (ScreenBuffer, ref info))
  143. return false;
  144. currentCursorVisibility = visibility;
  145. }
  146. return true;
  147. }
  148. public void Cleanup ()
  149. {
  150. if (initialCursorVisibility.HasValue) {
  151. SetCursorVisibility (initialCursorVisibility.Value);
  152. }
  153. ConsoleMode = originalConsoleMode;
  154. //ContinueListeningForConsoleEvents = false;
  155. if (!SetConsoleActiveScreenBuffer (OutputHandle)) {
  156. var err = Marshal.GetLastWin32Error ();
  157. Console.WriteLine ("Error: {0}", err);
  158. }
  159. if (ScreenBuffer != IntPtr.Zero)
  160. CloseHandle (ScreenBuffer);
  161. ScreenBuffer = IntPtr.Zero;
  162. }
  163. //bool ContinueListeningForConsoleEvents = true;
  164. public uint ConsoleMode {
  165. get {
  166. uint v;
  167. GetConsoleMode (InputHandle, out v);
  168. return v;
  169. }
  170. set {
  171. SetConsoleMode (InputHandle, value);
  172. }
  173. }
  174. public bool HeightAsBuffer { get; set; }
  175. [Flags]
  176. public enum ConsoleModes : uint {
  177. EnableProcessedInput = 1,
  178. EnableMouseInput = 16,
  179. EnableQuickEditMode = 64,
  180. EnableExtendedFlags = 128,
  181. }
  182. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  183. public struct KeyEventRecord {
  184. [FieldOffset (0), MarshalAs (UnmanagedType.Bool)]
  185. public bool bKeyDown;
  186. [FieldOffset (4), MarshalAs (UnmanagedType.U2)]
  187. public ushort wRepeatCount;
  188. [FieldOffset (6), MarshalAs (UnmanagedType.U2)]
  189. public ushort wVirtualKeyCode;
  190. [FieldOffset (8), MarshalAs (UnmanagedType.U2)]
  191. public ushort wVirtualScanCode;
  192. [FieldOffset (10)]
  193. public char UnicodeChar;
  194. [FieldOffset (12), MarshalAs (UnmanagedType.U4)]
  195. public ControlKeyState dwControlKeyState;
  196. }
  197. [Flags]
  198. public enum ButtonState {
  199. Button1Pressed = 1,
  200. Button2Pressed = 4,
  201. Button3Pressed = 8,
  202. Button4Pressed = 16,
  203. RightmostButtonPressed = 2,
  204. WheeledUp = unchecked((int)0x780000),
  205. WheeledDown = unchecked((int)0xFF880000),
  206. }
  207. [Flags]
  208. public enum ControlKeyState {
  209. RightAltPressed = 1,
  210. LeftAltPressed = 2,
  211. RightControlPressed = 4,
  212. LeftControlPressed = 8,
  213. ShiftPressed = 16,
  214. NumlockOn = 32,
  215. ScrolllockOn = 64,
  216. CapslockOn = 128,
  217. EnhancedKey = 256
  218. }
  219. [Flags]
  220. public enum EventFlags {
  221. MouseMoved = 1,
  222. DoubleClick = 2,
  223. MouseWheeled = 4,
  224. MouseHorizontalWheeled = 8
  225. }
  226. [StructLayout (LayoutKind.Explicit)]
  227. public struct MouseEventRecord {
  228. [FieldOffset (0)]
  229. public Coordinate MousePosition;
  230. [FieldOffset (4)]
  231. public ButtonState ButtonState;
  232. [FieldOffset (8)]
  233. public ControlKeyState ControlKeyState;
  234. [FieldOffset (12)]
  235. public EventFlags EventFlags;
  236. public override string ToString ()
  237. {
  238. return $"[Mouse({MousePosition},{ButtonState},{ControlKeyState},{EventFlags}";
  239. }
  240. }
  241. [StructLayout (LayoutKind.Sequential)]
  242. public struct Coordinate {
  243. public short X;
  244. public short Y;
  245. public Coordinate (short X, short Y)
  246. {
  247. this.X = X;
  248. this.Y = Y;
  249. }
  250. public override string ToString () => $"({X},{Y})";
  251. };
  252. public struct WindowBufferSizeRecord {
  253. public Coordinate size;
  254. public WindowBufferSizeRecord (short x, short y)
  255. {
  256. this.size = new Coordinate (x, y);
  257. }
  258. public override string ToString () => $"[WindowBufferSize{size}";
  259. }
  260. [StructLayout (LayoutKind.Sequential)]
  261. public struct MenuEventRecord {
  262. public uint dwCommandId;
  263. }
  264. [StructLayout (LayoutKind.Sequential)]
  265. public struct FocusEventRecord {
  266. public uint bSetFocus;
  267. }
  268. public enum EventType : ushort {
  269. Focus = 0x10,
  270. Key = 0x1,
  271. Menu = 0x8,
  272. Mouse = 2,
  273. WindowBufferSize = 4
  274. }
  275. [StructLayout (LayoutKind.Explicit)]
  276. public struct InputRecord {
  277. [FieldOffset (0)]
  278. public EventType EventType;
  279. [FieldOffset (4)]
  280. public KeyEventRecord KeyEvent;
  281. [FieldOffset (4)]
  282. public MouseEventRecord MouseEvent;
  283. [FieldOffset (4)]
  284. public WindowBufferSizeRecord WindowBufferSizeEvent;
  285. [FieldOffset (4)]
  286. public MenuEventRecord MenuEvent;
  287. [FieldOffset (4)]
  288. public FocusEventRecord FocusEvent;
  289. public override string ToString ()
  290. {
  291. switch (EventType) {
  292. case EventType.Focus:
  293. return FocusEvent.ToString ();
  294. case EventType.Key:
  295. return KeyEvent.ToString ();
  296. case EventType.Menu:
  297. return MenuEvent.ToString ();
  298. case EventType.Mouse:
  299. return MouseEvent.ToString ();
  300. case EventType.WindowBufferSize:
  301. return WindowBufferSizeEvent.ToString ();
  302. default:
  303. return "Unknown event type: " + EventType;
  304. }
  305. }
  306. };
  307. [Flags]
  308. enum ShareMode : uint {
  309. FileShareRead = 1,
  310. FileShareWrite = 2,
  311. }
  312. [Flags]
  313. enum DesiredAccess : uint {
  314. GenericRead = 2147483648,
  315. GenericWrite = 1073741824,
  316. }
  317. [StructLayout (LayoutKind.Sequential)]
  318. public struct ConsoleScreenBufferInfo {
  319. public Coord dwSize;
  320. public Coord dwCursorPosition;
  321. public ushort wAttributes;
  322. public SmallRect srWindow;
  323. public Coord dwMaximumWindowSize;
  324. }
  325. [StructLayout (LayoutKind.Sequential)]
  326. public struct Coord {
  327. public short X;
  328. public short Y;
  329. public Coord (short X, short Y)
  330. {
  331. this.X = X;
  332. this.Y = Y;
  333. }
  334. public override string ToString () => $"({X},{Y})";
  335. };
  336. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  337. public struct CharUnion {
  338. [FieldOffset (0)] public char UnicodeChar;
  339. [FieldOffset (0)] public byte AsciiChar;
  340. }
  341. [StructLayout (LayoutKind.Explicit, CharSet = CharSet.Unicode)]
  342. public struct CharInfo {
  343. [FieldOffset (0)] public CharUnion Char;
  344. [FieldOffset (2)] public ushort Attributes;
  345. }
  346. [StructLayout (LayoutKind.Sequential)]
  347. public struct SmallRect {
  348. public short Left;
  349. public short Top;
  350. public short Right;
  351. public short Bottom;
  352. public static void MakeEmpty (ref SmallRect rect)
  353. {
  354. rect.Left = -1;
  355. }
  356. public static void Update (ref SmallRect rect, short col, short row)
  357. {
  358. if (rect.Left == -1) {
  359. //System.Diagnostics.Debugger.Log (0, "debug", $"damager From Empty {col},{row}\n");
  360. rect.Left = rect.Right = col;
  361. rect.Bottom = rect.Top = row;
  362. return;
  363. }
  364. if (col >= rect.Left && col <= rect.Right && row >= rect.Top && row <= rect.Bottom)
  365. return;
  366. if (col < rect.Left)
  367. rect.Left = col;
  368. if (col > rect.Right)
  369. rect.Right = col;
  370. if (row < rect.Top)
  371. rect.Top = row;
  372. if (row > rect.Bottom)
  373. rect.Bottom = row;
  374. //System.Diagnostics.Debugger.Log (0, "debug", $"Expanding {rect.ToString ()}\n");
  375. }
  376. public override string ToString ()
  377. {
  378. return $"Left={Left},Top={Top},Right={Right},Bottom={Bottom}";
  379. }
  380. }
  381. [StructLayout (LayoutKind.Sequential)]
  382. public struct ConsoleKeyInfoEx {
  383. public ConsoleKeyInfo consoleKeyInfo;
  384. public bool CapsLock;
  385. public bool NumLock;
  386. public ConsoleKeyInfoEx (ConsoleKeyInfo consoleKeyInfo, bool capslock, bool numlock)
  387. {
  388. this.consoleKeyInfo = consoleKeyInfo;
  389. CapsLock = capslock;
  390. NumLock = numlock;
  391. }
  392. }
  393. [DllImport ("kernel32.dll", SetLastError = true)]
  394. static extern IntPtr GetStdHandle (int nStdHandle);
  395. [DllImport ("kernel32.dll", SetLastError = true)]
  396. static extern bool CloseHandle (IntPtr handle);
  397. [DllImport ("kernel32.dll", EntryPoint = "ReadConsoleInputW", CharSet = CharSet.Unicode)]
  398. public static extern bool ReadConsoleInput (
  399. IntPtr hConsoleInput,
  400. IntPtr lpBuffer,
  401. uint nLength,
  402. out uint lpNumberOfEventsRead);
  403. [DllImport ("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  404. static extern bool ReadConsoleOutput (
  405. IntPtr hConsoleOutput,
  406. [Out] CharInfo [] lpBuffer,
  407. Coord dwBufferSize,
  408. Coord dwBufferCoord,
  409. ref SmallRect lpReadRegion
  410. );
  411. [DllImport ("kernel32.dll", EntryPoint = "WriteConsoleOutput", SetLastError = true, CharSet = CharSet.Unicode)]
  412. static extern bool WriteConsoleOutput (
  413. IntPtr hConsoleOutput,
  414. CharInfo [] lpBuffer,
  415. Coord dwBufferSize,
  416. Coord dwBufferCoord,
  417. ref SmallRect lpWriteRegion
  418. );
  419. [DllImport ("kernel32.dll")]
  420. static extern bool SetConsoleCursorPosition (IntPtr hConsoleOutput, Coord dwCursorPosition);
  421. [StructLayout (LayoutKind.Sequential)]
  422. public struct ConsoleCursorInfo {
  423. public uint dwSize;
  424. public bool bVisible;
  425. }
  426. [DllImport ("kernel32.dll", SetLastError = true)]
  427. static extern bool SetConsoleCursorInfo (IntPtr hConsoleOutput, [In] ref ConsoleCursorInfo lpConsoleCursorInfo);
  428. [DllImport ("kernel32.dll", SetLastError = true)]
  429. static extern bool GetConsoleCursorInfo (IntPtr hConsoleOutput, out ConsoleCursorInfo lpConsoleCursorInfo);
  430. [DllImport ("kernel32.dll")]
  431. static extern bool GetConsoleMode (IntPtr hConsoleHandle, out uint lpMode);
  432. [DllImport ("kernel32.dll")]
  433. static extern bool SetConsoleMode (IntPtr hConsoleHandle, uint dwMode);
  434. [DllImport ("kernel32.dll", SetLastError = true)]
  435. static extern IntPtr CreateConsoleScreenBuffer (
  436. DesiredAccess dwDesiredAccess,
  437. ShareMode dwShareMode,
  438. IntPtr secutiryAttributes,
  439. UInt32 flags,
  440. IntPtr screenBufferData
  441. );
  442. internal static IntPtr INVALID_HANDLE_VALUE = new IntPtr (-1);
  443. [DllImport ("kernel32.dll", SetLastError = true)]
  444. static extern bool SetConsoleActiveScreenBuffer (IntPtr Handle);
  445. [DllImport ("kernel32.dll", SetLastError = true)]
  446. static extern bool GetNumberOfConsoleInputEvents (IntPtr handle, out uint lpcNumberOfEvents);
  447. public uint InputEventCount {
  448. get {
  449. uint v;
  450. GetNumberOfConsoleInputEvents (InputHandle, out v);
  451. return v;
  452. }
  453. }
  454. public InputRecord [] ReadConsoleInput ()
  455. {
  456. const int bufferSize = 1;
  457. var pRecord = Marshal.AllocHGlobal (Marshal.SizeOf<InputRecord> () * bufferSize);
  458. try {
  459. ReadConsoleInput (InputHandle, pRecord, bufferSize,
  460. out var numberEventsRead);
  461. return numberEventsRead == 0
  462. ? null
  463. : new [] { Marshal.PtrToStructure<InputRecord> (pRecord) };
  464. } catch (Exception) {
  465. return null;
  466. } finally {
  467. Marshal.FreeHGlobal (pRecord);
  468. }
  469. }
  470. #if false // Not needed on the constructor. Perhaps could be used on resizing. To study.
  471. [DllImport ("kernel32.dll", ExactSpelling = true)]
  472. static extern IntPtr GetConsoleWindow ();
  473. [DllImport ("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  474. static extern bool ShowWindow (IntPtr hWnd, int nCmdShow);
  475. public const int HIDE = 0;
  476. public const int MAXIMIZE = 3;
  477. public const int MINIMIZE = 6;
  478. public const int RESTORE = 9;
  479. internal void ShowWindow (int state)
  480. {
  481. IntPtr thisConsole = GetConsoleWindow ();
  482. ShowWindow (thisConsole, state);
  483. }
  484. #endif
  485. #if false // See: https://github.com/migueldeicaza/gui.cs/issues/357
  486. [StructLayout (LayoutKind.Sequential)]
  487. public struct SMALL_RECT {
  488. public short Left;
  489. public short Top;
  490. public short Right;
  491. public short Bottom;
  492. public SMALL_RECT (short Left, short Top, short Right, short Bottom)
  493. {
  494. this.Left = Left;
  495. this.Top = Top;
  496. this.Right = Right;
  497. this.Bottom = Bottom;
  498. }
  499. }
  500. [StructLayout (LayoutKind.Sequential)]
  501. public struct CONSOLE_SCREEN_BUFFER_INFO {
  502. public int dwSize;
  503. public int dwCursorPosition;
  504. public short wAttributes;
  505. public SMALL_RECT srWindow;
  506. public int dwMaximumWindowSize;
  507. }
  508. [DllImport ("kernel32.dll", SetLastError = true)]
  509. static extern bool GetConsoleScreenBufferInfo (IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO ConsoleScreenBufferInfo);
  510. // Theoretically GetConsoleScreenBuffer height should give the console Windoww size
  511. // It does not work, however, and always returns the size the window was initially created at
  512. internal Size GetWindowSize ()
  513. {
  514. var consoleScreenBufferInfo = new CONSOLE_SCREEN_BUFFER_INFO ();
  515. //consoleScreenBufferInfo.dwSize = Marshal.SizeOf (typeof (CONSOLE_SCREEN_BUFFER_INFO));
  516. GetConsoleScreenBufferInfo (OutputHandle, out consoleScreenBufferInfo);
  517. return new Size (consoleScreenBufferInfo.srWindow.Right - consoleScreenBufferInfo.srWindow.Left,
  518. consoleScreenBufferInfo.srWindow.Bottom - consoleScreenBufferInfo.srWindow.Top);
  519. }
  520. #endif
  521. }
  522. internal class WindowsDriver : ConsoleDriver {
  523. static bool sync = false;
  524. WindowsConsole.CharInfo [] OutputBuffer;
  525. int cols, rows, top;
  526. WindowsConsole winConsole;
  527. WindowsConsole.SmallRect damageRegion;
  528. IClipboard clipboard;
  529. public override int Cols => cols;
  530. public override int Rows => rows;
  531. public override int Left => 0;
  532. public override int Top => top;
  533. public override bool HeightAsBuffer { get; set; }
  534. public override IClipboard Clipboard => clipboard;
  535. public WindowsConsole WinConsole {
  536. get => winConsole;
  537. private set => winConsole = value;
  538. }
  539. Action<KeyEvent> keyHandler;
  540. Action<KeyEvent> keyDownHandler;
  541. Action<KeyEvent> keyUpHandler;
  542. Action<MouseEvent> mouseHandler;
  543. public WindowsDriver ()
  544. {
  545. winConsole = new WindowsConsole ();
  546. clipboard = new WindowsClipboard ();
  547. }
  548. bool winChanging;
  549. public override void PrepareToRun (MainLoop mainLoop, Action<KeyEvent> keyHandler, Action<KeyEvent> keyDownHandler, Action<KeyEvent> keyUpHandler, Action<MouseEvent> mouseHandler)
  550. {
  551. this.keyHandler = keyHandler;
  552. this.keyDownHandler = keyDownHandler;
  553. this.keyUpHandler = keyUpHandler;
  554. this.mouseHandler = mouseHandler;
  555. var mLoop = mainLoop.Driver as WindowsMainLoop;
  556. mLoop.ProcessInput = (e) => ProcessInput (e);
  557. mLoop.WinChanged = (e) => {
  558. ChangeWin (e);
  559. };
  560. }
  561. private void ChangeWin (Size e)
  562. {
  563. winChanging = true;
  564. if (!HeightAsBuffer) {
  565. top = 0;
  566. cols = e.Width;
  567. rows = e.Height;
  568. ResizeScreen ();
  569. UpdateOffScreen ();
  570. var bufferCoords = new WindowsConsole.Coord () {
  571. X = (short)Clip.Width,
  572. Y = (short)Clip.Height
  573. };
  574. winConsole.ReadFromConsoleOutput (e, bufferCoords, ref damageRegion);
  575. if (!winChanging) {
  576. TerminalResized.Invoke ();
  577. }
  578. }
  579. }
  580. void ProcessInput (WindowsConsole.InputRecord inputEvent)
  581. {
  582. switch (inputEvent.EventType) {
  583. case WindowsConsole.EventType.Key:
  584. var map = MapKey (ToConsoleKeyInfoEx (inputEvent.KeyEvent));
  585. if (map == (Key)0xffffffff) {
  586. KeyEvent key = new KeyEvent ();
  587. // Shift = VK_SHIFT = 0x10
  588. // Ctrl = VK_CONTROL = 0x11
  589. // Alt = VK_MENU = 0x12
  590. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.CapslockOn)) {
  591. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.CapslockOn;
  592. }
  593. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ScrolllockOn)) {
  594. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.ScrolllockOn;
  595. }
  596. if (inputEvent.KeyEvent.dwControlKeyState.HasFlag (WindowsConsole.ControlKeyState.NumlockOn)) {
  597. inputEvent.KeyEvent.dwControlKeyState &= ~WindowsConsole.ControlKeyState.NumlockOn;
  598. }
  599. switch (inputEvent.KeyEvent.dwControlKeyState) {
  600. case WindowsConsole.ControlKeyState.RightAltPressed:
  601. case WindowsConsole.ControlKeyState.RightAltPressed |
  602. WindowsConsole.ControlKeyState.LeftControlPressed |
  603. WindowsConsole.ControlKeyState.EnhancedKey:
  604. case WindowsConsole.ControlKeyState.EnhancedKey:
  605. key = new KeyEvent (Key.CtrlMask | Key.AltMask, keyModifiers);
  606. break;
  607. case WindowsConsole.ControlKeyState.LeftAltPressed:
  608. key = new KeyEvent (Key.AltMask, keyModifiers);
  609. break;
  610. case WindowsConsole.ControlKeyState.RightControlPressed:
  611. case WindowsConsole.ControlKeyState.LeftControlPressed:
  612. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  613. break;
  614. case WindowsConsole.ControlKeyState.ShiftPressed:
  615. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  616. break;
  617. case WindowsConsole.ControlKeyState.NumlockOn:
  618. break;
  619. case WindowsConsole.ControlKeyState.ScrolllockOn:
  620. break;
  621. case WindowsConsole.ControlKeyState.CapslockOn:
  622. break;
  623. default:
  624. switch (inputEvent.KeyEvent.wVirtualKeyCode) {
  625. case 0x10:
  626. key = new KeyEvent (Key.ShiftMask, keyModifiers);
  627. break;
  628. case 0x11:
  629. key = new KeyEvent (Key.CtrlMask, keyModifiers);
  630. break;
  631. case 0x12:
  632. key = new KeyEvent (Key.AltMask, keyModifiers);
  633. break;
  634. default:
  635. key = new KeyEvent (Key.Unknown, keyModifiers);
  636. break;
  637. }
  638. break;
  639. }
  640. if (inputEvent.KeyEvent.bKeyDown)
  641. keyDownHandler (key);
  642. else
  643. keyUpHandler (key);
  644. } else {
  645. if (inputEvent.KeyEvent.bKeyDown) {
  646. // Key Down - Fire KeyDown Event and KeyStroke (ProcessKey) Event
  647. keyDownHandler (new KeyEvent (map, keyModifiers));
  648. keyHandler (new KeyEvent (map, keyModifiers));
  649. } else {
  650. keyUpHandler (new KeyEvent (map, keyModifiers));
  651. }
  652. }
  653. if (!inputEvent.KeyEvent.bKeyDown) {
  654. keyModifiers = null;
  655. }
  656. break;
  657. case WindowsConsole.EventType.Mouse:
  658. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  659. if (IsButtonReleased)
  660. mouseHandler (ToDriverMouse (inputEvent.MouseEvent));
  661. break;
  662. case WindowsConsole.EventType.WindowBufferSize:
  663. cols = inputEvent.WindowBufferSizeEvent.size.X;
  664. rows = inputEvent.WindowBufferSizeEvent.size.Y;
  665. ResizeScreen ();
  666. UpdateOffScreen ();
  667. TerminalResized?.Invoke ();
  668. break;
  669. case WindowsConsole.EventType.Focus:
  670. break;
  671. }
  672. }
  673. WindowsConsole.ButtonState? LastMouseButtonPressed = null;
  674. bool IsButtonPressed = false;
  675. bool IsButtonReleased = false;
  676. bool IsButtonDoubleClicked = false;
  677. Point point;
  678. MouseEvent ToDriverMouse (WindowsConsole.MouseEventRecord mouseEvent)
  679. {
  680. MouseFlags mouseFlag = MouseFlags.AllEvents;
  681. if (IsButtonDoubleClicked) {
  682. Application.MainLoop.AddIdle (() => {
  683. ProcessButtonDoubleClickedAsync ().ConfigureAwait (false);
  684. return false;
  685. });
  686. }
  687. // The ButtonState member of the MouseEvent structure has bit corresponding to each mouse button.
  688. // This will tell when a mouse button is pressed. When the button is released this event will
  689. // be fired with it's bit set to 0. So when the button is up ButtonState will be 0.
  690. // To map to the correct driver events we save the last pressed mouse button so we can
  691. // map to the correct clicked event.
  692. if ((LastMouseButtonPressed != null || IsButtonReleased) && mouseEvent.ButtonState != 0) {
  693. LastMouseButtonPressed = null;
  694. IsButtonPressed = false;
  695. IsButtonReleased = false;
  696. }
  697. var p = new Point () {
  698. X = mouseEvent.MousePosition.X,
  699. Y = mouseEvent.MousePosition.Y
  700. };
  701. if ((mouseEvent.ButtonState != 0 && mouseEvent.EventFlags == 0 && LastMouseButtonPressed == null && !IsButtonDoubleClicked) ||
  702. (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved &&
  703. mouseEvent.ButtonState != 0 && !IsButtonReleased && !IsButtonDoubleClicked)) {
  704. switch (mouseEvent.ButtonState) {
  705. case WindowsConsole.ButtonState.Button1Pressed:
  706. mouseFlag = MouseFlags.Button1Pressed;
  707. break;
  708. case WindowsConsole.ButtonState.Button2Pressed:
  709. mouseFlag = MouseFlags.Button2Pressed;
  710. break;
  711. case WindowsConsole.ButtonState.RightmostButtonPressed:
  712. mouseFlag = MouseFlags.Button3Pressed;
  713. break;
  714. }
  715. if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  716. mouseFlag |= MouseFlags.ReportMousePosition;
  717. point = new Point ();
  718. IsButtonReleased = false;
  719. } else {
  720. point = new Point () {
  721. X = mouseEvent.MousePosition.X,
  722. Y = mouseEvent.MousePosition.Y
  723. };
  724. }
  725. LastMouseButtonPressed = mouseEvent.ButtonState;
  726. IsButtonPressed = true;
  727. if ((mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  728. Application.MainLoop.AddIdle (() => {
  729. ProcessContinuousButtonPressedAsync (mouseEvent, mouseFlag).ConfigureAwait (false);
  730. return false;
  731. });
  732. }
  733. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  734. LastMouseButtonPressed != null && !IsButtonReleased && !IsButtonDoubleClicked) {
  735. switch (LastMouseButtonPressed) {
  736. case WindowsConsole.ButtonState.Button1Pressed:
  737. mouseFlag = MouseFlags.Button1Released;
  738. break;
  739. case WindowsConsole.ButtonState.Button2Pressed:
  740. mouseFlag = MouseFlags.Button2Released;
  741. break;
  742. case WindowsConsole.ButtonState.RightmostButtonPressed:
  743. mouseFlag = MouseFlags.Button3Released;
  744. break;
  745. }
  746. IsButtonPressed = false;
  747. IsButtonReleased = true;
  748. } else if ((mouseEvent.EventFlags == 0 || mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) &&
  749. IsButtonReleased && p == point) {
  750. switch (LastMouseButtonPressed) {
  751. case WindowsConsole.ButtonState.Button1Pressed:
  752. mouseFlag = MouseFlags.Button1Clicked;
  753. break;
  754. case WindowsConsole.ButtonState.Button2Pressed:
  755. mouseFlag = MouseFlags.Button2Clicked;
  756. break;
  757. case WindowsConsole.ButtonState.RightmostButtonPressed:
  758. mouseFlag = MouseFlags.Button3Clicked;
  759. break;
  760. }
  761. point = new Point () {
  762. X = mouseEvent.MousePosition.X,
  763. Y = mouseEvent.MousePosition.Y
  764. };
  765. LastMouseButtonPressed = null;
  766. IsButtonReleased = false;
  767. } else if (mouseEvent.EventFlags.HasFlag (WindowsConsole.EventFlags.DoubleClick)) {
  768. switch (mouseEvent.ButtonState) {
  769. case WindowsConsole.ButtonState.Button1Pressed:
  770. mouseFlag = MouseFlags.Button1DoubleClicked;
  771. break;
  772. case WindowsConsole.ButtonState.Button2Pressed:
  773. mouseFlag = MouseFlags.Button2DoubleClicked;
  774. break;
  775. case WindowsConsole.ButtonState.RightmostButtonPressed:
  776. mouseFlag = MouseFlags.Button3DoubleClicked;
  777. break;
  778. }
  779. IsButtonDoubleClicked = true;
  780. } else if (mouseEvent.EventFlags == 0 && mouseEvent.ButtonState != 0 && IsButtonDoubleClicked) {
  781. switch (mouseEvent.ButtonState) {
  782. case WindowsConsole.ButtonState.Button1Pressed:
  783. mouseFlag = MouseFlags.Button1TripleClicked;
  784. break;
  785. case WindowsConsole.ButtonState.Button2Pressed:
  786. mouseFlag = MouseFlags.Button2TripleClicked;
  787. break;
  788. case WindowsConsole.ButtonState.RightmostButtonPressed:
  789. mouseFlag = MouseFlags.Button3TripleClicked;
  790. break;
  791. }
  792. IsButtonDoubleClicked = false;
  793. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled) {
  794. switch (mouseEvent.ButtonState) {
  795. case WindowsConsole.ButtonState.WheeledUp:
  796. mouseFlag = MouseFlags.WheeledUp;
  797. break;
  798. case WindowsConsole.ButtonState.WheeledDown:
  799. mouseFlag = MouseFlags.WheeledDown;
  800. break;
  801. }
  802. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseWheeled &&
  803. mouseEvent.ControlKeyState == WindowsConsole.ControlKeyState.ShiftPressed) {
  804. switch (mouseEvent.ButtonState) {
  805. case WindowsConsole.ButtonState.WheeledUp:
  806. mouseFlag = MouseFlags.WheeledLeft;
  807. break;
  808. case WindowsConsole.ButtonState.WheeledDown:
  809. mouseFlag = MouseFlags.WheeledRight;
  810. break;
  811. }
  812. } else if (mouseEvent.EventFlags == WindowsConsole.EventFlags.MouseMoved) {
  813. if (mouseEvent.MousePosition.X != point.X || mouseEvent.MousePosition.Y != point.Y) {
  814. mouseFlag = MouseFlags.ReportMousePosition;
  815. point = new Point ();
  816. } else {
  817. mouseFlag = 0;
  818. }
  819. } else if (mouseEvent.ButtonState == 0 && mouseEvent.EventFlags == 0) {
  820. mouseFlag = 0;
  821. }
  822. mouseFlag = SetControlKeyStates (mouseEvent, mouseFlag);
  823. return new MouseEvent () {
  824. X = mouseEvent.MousePosition.X,
  825. Y = mouseEvent.MousePosition.Y,
  826. Flags = mouseFlag
  827. };
  828. }
  829. async Task ProcessButtonDoubleClickedAsync ()
  830. {
  831. await Task.Delay (200);
  832. IsButtonDoubleClicked = false;
  833. }
  834. async Task ProcessContinuousButtonPressedAsync (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  835. {
  836. while (IsButtonPressed) {
  837. await Task.Delay (100);
  838. var me = new MouseEvent () {
  839. X = mouseEvent.MousePosition.X,
  840. Y = mouseEvent.MousePosition.Y,
  841. Flags = mouseFlag
  842. };
  843. var view = Application.wantContinuousButtonPressedView;
  844. if (view == null) {
  845. break;
  846. }
  847. if (IsButtonPressed && (mouseFlag & MouseFlags.ReportMousePosition) == 0) {
  848. mouseHandler (me);
  849. }
  850. }
  851. }
  852. static MouseFlags SetControlKeyStates (WindowsConsole.MouseEventRecord mouseEvent, MouseFlags mouseFlag)
  853. {
  854. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightControlPressed) ||
  855. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftControlPressed))
  856. mouseFlag |= MouseFlags.ButtonCtrl;
  857. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.ShiftPressed))
  858. mouseFlag |= MouseFlags.ButtonShift;
  859. if (mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.RightAltPressed) ||
  860. mouseEvent.ControlKeyState.HasFlag (WindowsConsole.ControlKeyState.LeftAltPressed))
  861. mouseFlag |= MouseFlags.ButtonAlt;
  862. return mouseFlag;
  863. }
  864. KeyModifiers keyModifiers;
  865. public WindowsConsole.ConsoleKeyInfoEx ToConsoleKeyInfoEx (WindowsConsole.KeyEventRecord keyEvent)
  866. {
  867. var state = keyEvent.dwControlKeyState;
  868. bool shift = (state & WindowsConsole.ControlKeyState.ShiftPressed) != 0;
  869. bool alt = (state & (WindowsConsole.ControlKeyState.LeftAltPressed | WindowsConsole.ControlKeyState.RightAltPressed)) != 0;
  870. bool control = (state & (WindowsConsole.ControlKeyState.LeftControlPressed | WindowsConsole.ControlKeyState.RightControlPressed)) != 0;
  871. bool capslock = (state & (WindowsConsole.ControlKeyState.CapslockOn)) != 0;
  872. bool numlock = (state & (WindowsConsole.ControlKeyState.NumlockOn)) != 0;
  873. bool scrolllock = (state & (WindowsConsole.ControlKeyState.ScrolllockOn)) != 0;
  874. if (keyModifiers == null)
  875. keyModifiers = new KeyModifiers ();
  876. if (shift)
  877. keyModifiers.Shift = shift;
  878. if (alt)
  879. keyModifiers.Alt = alt;
  880. if (control)
  881. keyModifiers.Ctrl = control;
  882. if (capslock)
  883. keyModifiers.Capslock = capslock;
  884. if (numlock)
  885. keyModifiers.Numlock = numlock;
  886. if (scrolllock)
  887. keyModifiers.Scrolllock = scrolllock;
  888. var ConsoleKeyInfo = new ConsoleKeyInfo (keyEvent.UnicodeChar, (ConsoleKey)keyEvent.wVirtualKeyCode, shift, alt, control);
  889. return new WindowsConsole.ConsoleKeyInfoEx (ConsoleKeyInfo, capslock, numlock);
  890. }
  891. public Key MapKey (WindowsConsole.ConsoleKeyInfoEx keyInfoEx)
  892. {
  893. var keyInfo = keyInfoEx.consoleKeyInfo;
  894. switch (keyInfo.Key) {
  895. case ConsoleKey.Escape:
  896. return MapKeyModifiers (keyInfo, Key.Esc);
  897. case ConsoleKey.Tab:
  898. return keyInfo.Modifiers == ConsoleModifiers.Shift ? Key.BackTab : Key.Tab;
  899. case ConsoleKey.Home:
  900. return MapKeyModifiers (keyInfo, Key.Home);
  901. case ConsoleKey.End:
  902. return MapKeyModifiers (keyInfo, Key.End);
  903. case ConsoleKey.LeftArrow:
  904. return MapKeyModifiers (keyInfo, Key.CursorLeft);
  905. case ConsoleKey.RightArrow:
  906. return MapKeyModifiers (keyInfo, Key.CursorRight);
  907. case ConsoleKey.UpArrow:
  908. return MapKeyModifiers (keyInfo, Key.CursorUp);
  909. case ConsoleKey.DownArrow:
  910. return MapKeyModifiers (keyInfo, Key.CursorDown);
  911. case ConsoleKey.PageUp:
  912. return MapKeyModifiers (keyInfo, Key.PageUp);
  913. case ConsoleKey.PageDown:
  914. return MapKeyModifiers (keyInfo, Key.PageDown);
  915. case ConsoleKey.Enter:
  916. return MapKeyModifiers (keyInfo, Key.Enter);
  917. case ConsoleKey.Spacebar:
  918. return MapKeyModifiers (keyInfo, keyInfo.KeyChar == 0 ? Key.Space : (Key)keyInfo.KeyChar);
  919. case ConsoleKey.Backspace:
  920. return MapKeyModifiers (keyInfo, Key.Backspace);
  921. case ConsoleKey.Delete:
  922. return MapKeyModifiers (keyInfo, Key.DeleteChar);
  923. case ConsoleKey.Insert:
  924. return MapKeyModifiers (keyInfo, Key.InsertChar);
  925. case ConsoleKey.NumPad0:
  926. return keyInfoEx.NumLock ? Key.D0 : Key.InsertChar;
  927. case ConsoleKey.NumPad1:
  928. return keyInfoEx.NumLock ? Key.D1 : Key.End;
  929. case ConsoleKey.NumPad2:
  930. return keyInfoEx.NumLock ? Key.D2 : Key.CursorDown;
  931. case ConsoleKey.NumPad3:
  932. return keyInfoEx.NumLock ? Key.D3 : Key.PageDown;
  933. case ConsoleKey.NumPad4:
  934. return keyInfoEx.NumLock ? Key.D4 : Key.CursorLeft;
  935. case ConsoleKey.NumPad5:
  936. return keyInfoEx.NumLock ? Key.D5 : (Key)((uint)keyInfo.KeyChar);
  937. case ConsoleKey.NumPad6:
  938. return keyInfoEx.NumLock ? Key.D6 : Key.CursorRight;
  939. case ConsoleKey.NumPad7:
  940. return keyInfoEx.NumLock ? Key.D7 : Key.Home;
  941. case ConsoleKey.NumPad8:
  942. return keyInfoEx.NumLock ? Key.D8 : Key.CursorUp;
  943. case ConsoleKey.NumPad9:
  944. return keyInfoEx.NumLock ? Key.D9 : Key.PageUp;
  945. case ConsoleKey.Oem1:
  946. case ConsoleKey.Oem2:
  947. case ConsoleKey.Oem3:
  948. case ConsoleKey.Oem4:
  949. case ConsoleKey.Oem5:
  950. case ConsoleKey.Oem6:
  951. case ConsoleKey.Oem7:
  952. case ConsoleKey.Oem8:
  953. case ConsoleKey.Oem102:
  954. case ConsoleKey.OemPeriod:
  955. case ConsoleKey.OemComma:
  956. case ConsoleKey.OemPlus:
  957. case ConsoleKey.OemMinus:
  958. if (keyInfo.KeyChar == 0)
  959. return Key.Unknown;
  960. return (Key)((uint)keyInfo.KeyChar);
  961. }
  962. var key = keyInfo.Key;
  963. //var alphaBase = ((keyInfo.Modifiers == ConsoleModifiers.Shift) ^ (keyInfoEx.CapsLock)) ? 'A' : 'a';
  964. if (key >= ConsoleKey.A && key <= ConsoleKey.Z) {
  965. var delta = key - ConsoleKey.A;
  966. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  967. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.A + delta));
  968. }
  969. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  970. return (Key)(((uint)Key.AltMask) | ((uint)Key.A + delta));
  971. }
  972. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  973. if (keyInfo.KeyChar == 0 || (keyInfo.KeyChar != 0 && keyInfo.KeyChar >= 1 && keyInfo.KeyChar <= 26)) {
  974. return MapKeyModifiers (keyInfo, (Key)((uint)Key.A + delta));
  975. }
  976. }
  977. //return (Key)((uint)alphaBase + delta);
  978. return (Key)((uint)keyInfo.KeyChar);
  979. }
  980. if (key >= ConsoleKey.D0 && key <= ConsoleKey.D9) {
  981. var delta = key - ConsoleKey.D0;
  982. if (keyInfo.Modifiers == ConsoleModifiers.Alt) {
  983. return (Key)(((uint)Key.AltMask) | ((uint)Key.D0 + delta));
  984. }
  985. if (keyInfo.Modifiers == ConsoleModifiers.Control) {
  986. return (Key)(((uint)Key.CtrlMask) | ((uint)Key.D0 + delta));
  987. }
  988. if ((keyInfo.Modifiers & (ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  989. if (keyInfo.KeyChar == 0 || keyInfo.KeyChar == 30) {
  990. return MapKeyModifiers (keyInfo, (Key)((uint)Key.D0 + delta));
  991. }
  992. }
  993. return (Key)((uint)keyInfo.KeyChar);
  994. }
  995. if (key >= ConsoleKey.F1 && key <= ConsoleKey.F12) {
  996. var delta = key - ConsoleKey.F1;
  997. if ((keyInfo.Modifiers & (ConsoleModifiers.Shift | ConsoleModifiers.Alt | ConsoleModifiers.Control)) != 0) {
  998. return MapKeyModifiers (keyInfo, (Key)((uint)Key.F1 + delta));
  999. }
  1000. return (Key)((uint)Key.F1 + delta);
  1001. }
  1002. if (keyInfo.KeyChar != 0) {
  1003. return MapKeyModifiers (keyInfo, (Key)((uint)keyInfo.KeyChar));
  1004. }
  1005. return (Key)(0xffffffff);
  1006. }
  1007. Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key)
  1008. {
  1009. Key keyMod = new Key ();
  1010. if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0)
  1011. keyMod = Key.ShiftMask;
  1012. if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0)
  1013. keyMod |= Key.CtrlMask;
  1014. if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0)
  1015. keyMod |= Key.AltMask;
  1016. return keyMod != Key.Null ? keyMod | key : key;
  1017. }
  1018. public override void Init (Action terminalResized)
  1019. {
  1020. TerminalResized = terminalResized;
  1021. cols = Console.WindowWidth;
  1022. rows = Console.WindowHeight;
  1023. #if false
  1024. winConsole.ShowWindow (WindowsConsole.RESTORE);
  1025. #endif
  1026. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1027. ResizeScreen ();
  1028. UpdateOffScreen ();
  1029. Colors.TopLevel = new ColorScheme ();
  1030. Colors.Base = new ColorScheme ();
  1031. Colors.Dialog = new ColorScheme ();
  1032. Colors.Menu = new ColorScheme ();
  1033. Colors.Error = new ColorScheme ();
  1034. Colors.TopLevel.Normal = MakeColor (ConsoleColor.Green, ConsoleColor.Black);
  1035. Colors.TopLevel.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkCyan);
  1036. Colors.TopLevel.HotNormal = MakeColor (ConsoleColor.DarkYellow, ConsoleColor.Black);
  1037. Colors.TopLevel.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkCyan);
  1038. Colors.Base.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkBlue);
  1039. Colors.Base.Focus = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  1040. Colors.Base.HotNormal = MakeColor (ConsoleColor.DarkCyan, ConsoleColor.DarkBlue);
  1041. Colors.Base.HotFocus = MakeColor (ConsoleColor.Blue, ConsoleColor.Gray);
  1042. Colors.Menu.Normal = MakeColor (ConsoleColor.White, ConsoleColor.DarkGray);
  1043. Colors.Menu.Focus = MakeColor (ConsoleColor.White, ConsoleColor.Black);
  1044. Colors.Menu.HotNormal = MakeColor (ConsoleColor.Yellow, ConsoleColor.DarkGray);
  1045. Colors.Menu.HotFocus = MakeColor (ConsoleColor.Yellow, ConsoleColor.Black);
  1046. Colors.Menu.Disabled = MakeColor (ConsoleColor.Gray, ConsoleColor.DarkGray);
  1047. Colors.Dialog.Normal = MakeColor (ConsoleColor.Black, ConsoleColor.Gray);
  1048. Colors.Dialog.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkGray);
  1049. Colors.Dialog.HotNormal = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.Gray);
  1050. Colors.Dialog.HotFocus = MakeColor (ConsoleColor.DarkBlue, ConsoleColor.DarkGray);
  1051. Colors.Error.Normal = MakeColor (ConsoleColor.DarkRed, ConsoleColor.White);
  1052. Colors.Error.Focus = MakeColor (ConsoleColor.White, ConsoleColor.DarkRed);
  1053. Colors.Error.HotNormal = MakeColor (ConsoleColor.Black, ConsoleColor.White);
  1054. Colors.Error.HotFocus = MakeColor (ConsoleColor.Black, ConsoleColor.DarkRed);
  1055. }
  1056. void ResizeScreen ()
  1057. {
  1058. OutputBuffer = new WindowsConsole.CharInfo [Rows * Cols];
  1059. Clip = new Rect (0, 0, Cols, Rows);
  1060. damageRegion = new WindowsConsole.SmallRect () {
  1061. Top = 0,
  1062. Left = 0,
  1063. Bottom = (short)Rows,
  1064. Right = (short)Cols
  1065. };
  1066. winConsole.ForceRefreshCursorVisibility ();
  1067. }
  1068. void UpdateOffScreen ()
  1069. {
  1070. for (int row = 0; row < rows; row++) {
  1071. for (int col = 0; col < cols; col++) {
  1072. int position = row * cols + col;
  1073. OutputBuffer [position].Attributes = (ushort)Colors.TopLevel.Normal;
  1074. OutputBuffer [position].Char.UnicodeChar = ' ';
  1075. }
  1076. }
  1077. winChanging = false;
  1078. }
  1079. int ccol, crow;
  1080. public override void Move (int col, int row)
  1081. {
  1082. ccol = col;
  1083. crow = row;
  1084. }
  1085. public override void AddRune (Rune rune)
  1086. {
  1087. rune = MakePrintable (rune);
  1088. var position = crow * Cols + ccol;
  1089. if (Clip.Contains (ccol, crow)) {
  1090. OutputBuffer [position].Attributes = (ushort)currentAttribute;
  1091. OutputBuffer [position].Char.UnicodeChar = (char)rune;
  1092. WindowsConsole.SmallRect.Update (ref damageRegion, (short)ccol, (short)crow);
  1093. }
  1094. ccol++;
  1095. var runeWidth = Rune.ColumnWidth (rune);
  1096. if (runeWidth > 1) {
  1097. for (int i = 1; i < runeWidth; i++) {
  1098. AddStr (" ");
  1099. }
  1100. }
  1101. //if (ccol == Cols) {
  1102. // ccol = 0;
  1103. // if (crow + 1 < Rows)
  1104. // crow++;
  1105. //}
  1106. if (sync)
  1107. UpdateScreen ();
  1108. }
  1109. public override void AddStr (ustring str)
  1110. {
  1111. foreach (var rune in str)
  1112. AddRune (rune);
  1113. }
  1114. int currentAttribute;
  1115. public override void SetAttribute (Attribute c)
  1116. {
  1117. currentAttribute = c.Value;
  1118. }
  1119. Attribute MakeColor (ConsoleColor f, ConsoleColor b)
  1120. {
  1121. // Encode the colors into the int value.
  1122. return new Attribute (
  1123. value: ((int)f | (int)b << 4),
  1124. foreground: (Color)f,
  1125. background: (Color)b
  1126. );
  1127. }
  1128. public override Attribute MakeAttribute (Color fore, Color back)
  1129. {
  1130. return MakeColor ((ConsoleColor)fore, (ConsoleColor)back);
  1131. }
  1132. public override void Refresh ()
  1133. {
  1134. UpdateScreen ();
  1135. winConsole.SetInitialCursorVisibility ();
  1136. #if false
  1137. var bufferCoords = new WindowsConsole.Coord (){
  1138. X = (short)Clip.Width,
  1139. Y = (short)Clip.Height
  1140. };
  1141. var window = new WindowsConsole.SmallRect (){
  1142. Top = 0,
  1143. Left = 0,
  1144. Right = (short)Clip.Right,
  1145. Bottom = (short)Clip.Bottom
  1146. };
  1147. UpdateCursor();
  1148. winConsole.WriteToConsole (OutputBuffer, bufferCoords, window);
  1149. #endif
  1150. }
  1151. public override void UpdateScreen ()
  1152. {
  1153. if (damageRegion.Left == -1)
  1154. return;
  1155. var bufferCoords = new WindowsConsole.Coord () {
  1156. X = (short)Clip.Width,
  1157. Y = (short)Clip.Height
  1158. };
  1159. //var window = new WindowsConsole.SmallRect () {
  1160. // Top = 0,
  1161. // Left = 0,
  1162. // Right = (short)Clip.Right,
  1163. // Bottom = (short)Clip.Bottom
  1164. //};
  1165. UpdateCursor ();
  1166. winConsole.WriteToConsole (OutputBuffer, bufferCoords, damageRegion);
  1167. // System.Diagnostics.Debugger.Log(0, "debug", $"Region={damageRegion.Right - damageRegion.Left},{damageRegion.Bottom - damageRegion.Top}\n");
  1168. WindowsConsole.SmallRect.MakeEmpty (ref damageRegion);
  1169. }
  1170. public override void UpdateCursor ()
  1171. {
  1172. var position = new WindowsConsole.Coord () {
  1173. X = (short)ccol,
  1174. Y = (short)crow
  1175. };
  1176. winConsole.SetCursorPosition (position);
  1177. }
  1178. public override void End ()
  1179. {
  1180. winConsole.Cleanup ();
  1181. }
  1182. public override Attribute GetAttribute ()
  1183. {
  1184. return currentAttribute;
  1185. }
  1186. /// <inheritdoc/>
  1187. public override bool GetCursorVisibility (out CursorVisibility visibility)
  1188. {
  1189. return winConsole.GetCursorVisibility (out visibility);
  1190. }
  1191. /// <inheritdoc/>
  1192. public override bool SetCursorVisibility (CursorVisibility visibility)
  1193. {
  1194. return winConsole.SetCursorVisibility (visibility);
  1195. }
  1196. /// <inheritdoc/>
  1197. public override bool EnsureCursorVisibility ()
  1198. {
  1199. return winConsole.EnsureCursorVisibility ();
  1200. }
  1201. #region Unused
  1202. public override void SetColors (ConsoleColor foreground, ConsoleColor background)
  1203. {
  1204. }
  1205. public override void SetColors (short foregroundColorId, short backgroundColorId)
  1206. {
  1207. }
  1208. public override void Suspend ()
  1209. {
  1210. }
  1211. public override void StartReportingMouseMoves ()
  1212. {
  1213. }
  1214. public override void StopReportingMouseMoves ()
  1215. {
  1216. }
  1217. public override void UncookMouse ()
  1218. {
  1219. }
  1220. public override void CookMouse ()
  1221. {
  1222. }
  1223. public override void SendKeys (char keyChar, ConsoleKey key, bool shift, bool alt, bool control)
  1224. {
  1225. WindowsConsole.InputRecord input = new WindowsConsole.InputRecord ();
  1226. input.EventType = WindowsConsole.EventType.Key;
  1227. WindowsConsole.KeyEventRecord keyEvent = new WindowsConsole.KeyEventRecord ();
  1228. keyEvent.bKeyDown = true;
  1229. WindowsConsole.ControlKeyState controlKey = new WindowsConsole.ControlKeyState ();
  1230. if (shift) {
  1231. controlKey |= WindowsConsole.ControlKeyState.ShiftPressed;
  1232. keyEvent.UnicodeChar = '\0';
  1233. keyEvent.wVirtualKeyCode = 16;
  1234. }
  1235. if (alt) {
  1236. controlKey |= WindowsConsole.ControlKeyState.LeftAltPressed;
  1237. controlKey |= WindowsConsole.ControlKeyState.RightAltPressed;
  1238. keyEvent.UnicodeChar = '\0';
  1239. keyEvent.wVirtualKeyCode = 18;
  1240. }
  1241. if (control) {
  1242. controlKey |= WindowsConsole.ControlKeyState.LeftControlPressed;
  1243. controlKey |= WindowsConsole.ControlKeyState.RightControlPressed;
  1244. keyEvent.UnicodeChar = '\0';
  1245. keyEvent.wVirtualKeyCode = 17;
  1246. }
  1247. keyEvent.dwControlKeyState = controlKey;
  1248. input.KeyEvent = keyEvent;
  1249. if (shift || alt || control) {
  1250. ProcessInput (input);
  1251. }
  1252. keyEvent.UnicodeChar = keyChar;
  1253. if ((shift || alt || control)
  1254. && (key >= ConsoleKey.A && key <= ConsoleKey.Z
  1255. || key >= ConsoleKey.D0 && key <= ConsoleKey.D9)) {
  1256. keyEvent.wVirtualKeyCode = (ushort)key;
  1257. } else {
  1258. keyEvent.wVirtualKeyCode = '\0';
  1259. }
  1260. input.KeyEvent = keyEvent;
  1261. try {
  1262. ProcessInput (input);
  1263. } catch (OverflowException) { }
  1264. finally {
  1265. keyEvent.bKeyDown = false;
  1266. input.KeyEvent = keyEvent;
  1267. ProcessInput (input);
  1268. }
  1269. }
  1270. #endregion
  1271. }
  1272. /// <summary>
  1273. /// Mainloop intended to be used with the <see cref="WindowsDriver"/>, and can
  1274. /// only be used on Windows.
  1275. /// </summary>
  1276. /// <remarks>
  1277. /// This implementation is used for WindowsDriver.
  1278. /// </remarks>
  1279. internal class WindowsMainLoop : IMainLoopDriver {
  1280. ManualResetEventSlim eventReady = new ManualResetEventSlim (false);
  1281. ManualResetEventSlim waitForProbe = new ManualResetEventSlim (false);
  1282. //ManualResetEventSlim winChange = new ManualResetEventSlim (false);
  1283. MainLoop mainLoop;
  1284. ConsoleDriver consoleDriver;
  1285. WindowsConsole winConsole;
  1286. //bool winChanged;
  1287. //Size windowSize;
  1288. CancellationTokenSource tokenSource = new CancellationTokenSource ();
  1289. // The records that we keep fetching
  1290. WindowsConsole.InputRecord [] result = new WindowsConsole.InputRecord [1];
  1291. /// <summary>
  1292. /// Invoked when a Key is pressed or released.
  1293. /// </summary>
  1294. public Action<WindowsConsole.InputRecord> ProcessInput;
  1295. /// <summary>
  1296. /// Invoked when the window is changed.
  1297. /// </summary>
  1298. public Action<Size> WinChanged;
  1299. public WindowsMainLoop (ConsoleDriver consoleDriver = null)
  1300. {
  1301. if (consoleDriver == null) {
  1302. throw new ArgumentNullException ("Console driver instance must be provided.");
  1303. }
  1304. this.consoleDriver = consoleDriver;
  1305. winConsole = ((WindowsDriver)consoleDriver).WinConsole;
  1306. }
  1307. void IMainLoopDriver.Setup (MainLoop mainLoop)
  1308. {
  1309. this.mainLoop = mainLoop;
  1310. Task.Run (WindowsInputHandler);
  1311. // Nor working yet.
  1312. //Task.Run (CheckWinChange);
  1313. }
  1314. void WindowsInputHandler ()
  1315. {
  1316. while (true) {
  1317. waitForProbe.Wait ();
  1318. waitForProbe.Reset ();
  1319. result = winConsole.ReadConsoleInput ();
  1320. eventReady.Set ();
  1321. }
  1322. }
  1323. //void CheckWinChange ()
  1324. //{
  1325. // while (true) {
  1326. // winChange.Wait ();
  1327. // winChange.Reset ();
  1328. // WaitWinChange ();
  1329. // winChanged = true;
  1330. // eventReady.Set ();
  1331. // }
  1332. //}
  1333. //void WaitWinChange ()
  1334. //{
  1335. // while (true) {
  1336. // if (!consoleDriver.HeightAsBuffer) {
  1337. // windowSize = new Size (Console.WindowWidth, Console.WindowHeight);
  1338. // if (windowSize.Height < consoleDriver.Rows) {
  1339. // // I still haven't been able to find a way to capture the shrinking in height.
  1340. // //return;
  1341. // }
  1342. // }
  1343. // }
  1344. //}
  1345. void IMainLoopDriver.Wakeup ()
  1346. {
  1347. //tokenSource.Cancel ();
  1348. eventReady.Set ();
  1349. }
  1350. bool IMainLoopDriver.EventsPending (bool wait)
  1351. {
  1352. if (CheckTimers (wait, out var waitTimeout)) {
  1353. return true;
  1354. }
  1355. result = null;
  1356. waitForProbe.Set ();
  1357. // Nor working yet.
  1358. //winChange.Set ();
  1359. try {
  1360. if (!tokenSource.IsCancellationRequested) {
  1361. eventReady.Wait (waitTimeout, tokenSource.Token);
  1362. }
  1363. } catch (OperationCanceledException) {
  1364. return true;
  1365. } finally {
  1366. eventReady.Reset ();
  1367. }
  1368. if (!tokenSource.IsCancellationRequested) {
  1369. //return result != null || CheckTimers (wait, out _) || winChanged;
  1370. return result != null || CheckTimers (wait, out _);
  1371. }
  1372. tokenSource.Dispose ();
  1373. tokenSource = new CancellationTokenSource ();
  1374. return true;
  1375. }
  1376. bool CheckTimers (bool wait, out int waitTimeout)
  1377. {
  1378. long now = DateTime.UtcNow.Ticks;
  1379. if (mainLoop.timeouts.Count > 0) {
  1380. waitTimeout = (int)((mainLoop.timeouts.Keys [0] - now) / TimeSpan.TicksPerMillisecond);
  1381. if (waitTimeout < 0)
  1382. return true;
  1383. } else {
  1384. waitTimeout = -1;
  1385. }
  1386. if (!wait)
  1387. waitTimeout = 0;
  1388. int ic;
  1389. lock (mainLoop.idleHandlers) {
  1390. ic = mainLoop.idleHandlers.Count;
  1391. }
  1392. return ic > 0;
  1393. }
  1394. void IMainLoopDriver.MainIteration ()
  1395. {
  1396. if (result != null) {
  1397. var inputEvent = result [0];
  1398. result = null;
  1399. ProcessInput?.Invoke (inputEvent);
  1400. }
  1401. //if (winChanged) {
  1402. // winChanged = false;
  1403. // WinChanged?.Invoke (windowSize);
  1404. //}
  1405. }
  1406. }
  1407. class WindowsClipboard : IClipboard {
  1408. public string GetClipboardData ()
  1409. {
  1410. if (!IsClipboardFormatAvailable (cfUnicodeText))
  1411. return null;
  1412. try {
  1413. if (!OpenClipboard (IntPtr.Zero))
  1414. return null;
  1415. IntPtr handle = GetClipboardData (cfUnicodeText);
  1416. if (handle == IntPtr.Zero)
  1417. return null;
  1418. IntPtr pointer = IntPtr.Zero;
  1419. try {
  1420. pointer = GlobalLock (handle);
  1421. if (pointer == IntPtr.Zero)
  1422. return null;
  1423. int size = GlobalSize (handle);
  1424. byte [] buff = new byte [size];
  1425. Marshal.Copy (pointer, buff, 0, size);
  1426. return System.Text.Encoding.Unicode.GetString (buff)
  1427. .TrimEnd ('\0')
  1428. .Replace ("\r\n", "\n");
  1429. } finally {
  1430. if (pointer != IntPtr.Zero)
  1431. GlobalUnlock (handle);
  1432. }
  1433. } finally {
  1434. CloseClipboard ();
  1435. }
  1436. }
  1437. public void SetClipboardData (string text)
  1438. {
  1439. OpenClipboard ();
  1440. EmptyClipboard ();
  1441. IntPtr hGlobal = default;
  1442. try {
  1443. var bytes = (text.Length + 1) * 2;
  1444. hGlobal = Marshal.AllocHGlobal (bytes);
  1445. if (hGlobal == default) {
  1446. ThrowWin32 ();
  1447. }
  1448. var target = GlobalLock (hGlobal);
  1449. if (target == default) {
  1450. ThrowWin32 ();
  1451. }
  1452. try {
  1453. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1454. } finally {
  1455. GlobalUnlock (target);
  1456. }
  1457. if (SetClipboardData (cfUnicodeText, hGlobal) == default) {
  1458. ThrowWin32 ();
  1459. }
  1460. hGlobal = default;
  1461. } finally {
  1462. if (hGlobal != default) {
  1463. Marshal.FreeHGlobal (hGlobal);
  1464. }
  1465. CloseClipboard ();
  1466. }
  1467. }
  1468. void OpenClipboard ()
  1469. {
  1470. var num = 10;
  1471. while (true) {
  1472. if (OpenClipboard (default)) {
  1473. break;
  1474. }
  1475. if (--num == 0) {
  1476. ThrowWin32 ();
  1477. }
  1478. Thread.Sleep (100);
  1479. }
  1480. }
  1481. const uint cfUnicodeText = 13;
  1482. void ThrowWin32 ()
  1483. {
  1484. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1485. }
  1486. [DllImport ("User32.dll", SetLastError = true)]
  1487. [return: MarshalAs (UnmanagedType.Bool)]
  1488. static extern bool IsClipboardFormatAvailable (uint format);
  1489. [DllImport ("kernel32.dll", SetLastError = true)]
  1490. static extern int GlobalSize (IntPtr handle);
  1491. [DllImport ("kernel32.dll", SetLastError = true)]
  1492. static extern IntPtr GlobalLock (IntPtr hMem);
  1493. [DllImport ("kernel32.dll", SetLastError = true)]
  1494. [return: MarshalAs (UnmanagedType.Bool)]
  1495. static extern bool GlobalUnlock (IntPtr hMem);
  1496. [DllImport ("user32.dll", SetLastError = true)]
  1497. [return: MarshalAs (UnmanagedType.Bool)]
  1498. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1499. [DllImport ("user32.dll", SetLastError = true)]
  1500. [return: MarshalAs (UnmanagedType.Bool)]
  1501. static extern bool CloseClipboard ();
  1502. [DllImport ("user32.dll", SetLastError = true)]
  1503. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1504. [DllImport ("user32.dll")]
  1505. static extern bool EmptyClipboard ();
  1506. [DllImport ("user32.dll", SetLastError = true)]
  1507. static extern IntPtr GetClipboardData (uint uFormat);
  1508. }
  1509. }