WindowsDriver.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777
  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 : ClipboardBase {
  1408. public override bool IsSupported => IsClipboardFormatAvailable (cfUnicodeText) ? true : false;
  1409. protected override string GetClipboardDataImpl ()
  1410. {
  1411. //if (!IsClipboardFormatAvailable (cfUnicodeText))
  1412. // return null;
  1413. try {
  1414. if (!OpenClipboard (IntPtr.Zero))
  1415. return null;
  1416. IntPtr handle = GetClipboardData (cfUnicodeText);
  1417. if (handle == IntPtr.Zero)
  1418. return null;
  1419. IntPtr pointer = IntPtr.Zero;
  1420. try {
  1421. pointer = GlobalLock (handle);
  1422. if (pointer == IntPtr.Zero)
  1423. return null;
  1424. int size = GlobalSize (handle);
  1425. byte [] buff = new byte [size];
  1426. Marshal.Copy (pointer, buff, 0, size);
  1427. return System.Text.Encoding.Unicode.GetString (buff)
  1428. .TrimEnd ('\0')
  1429. .Replace ("\r\n", "\n");
  1430. } finally {
  1431. if (pointer != IntPtr.Zero)
  1432. GlobalUnlock (handle);
  1433. }
  1434. } finally {
  1435. CloseClipboard ();
  1436. }
  1437. }
  1438. protected override void SetClipboardDataImpl (string text)
  1439. {
  1440. OpenClipboard ();
  1441. EmptyClipboard ();
  1442. IntPtr hGlobal = default;
  1443. try {
  1444. var bytes = (text.Length + 1) * 2;
  1445. hGlobal = Marshal.AllocHGlobal (bytes);
  1446. if (hGlobal == default) {
  1447. ThrowWin32 ();
  1448. }
  1449. var target = GlobalLock (hGlobal);
  1450. if (target == default) {
  1451. ThrowWin32 ();
  1452. }
  1453. try {
  1454. Marshal.Copy (text.ToCharArray (), 0, target, text.Length);
  1455. } finally {
  1456. GlobalUnlock (target);
  1457. }
  1458. if (SetClipboardData (cfUnicodeText, hGlobal) == default) {
  1459. ThrowWin32 ();
  1460. }
  1461. hGlobal = default;
  1462. } finally {
  1463. if (hGlobal != default) {
  1464. Marshal.FreeHGlobal (hGlobal);
  1465. }
  1466. CloseClipboard ();
  1467. }
  1468. }
  1469. void OpenClipboard ()
  1470. {
  1471. var num = 10;
  1472. while (true) {
  1473. if (OpenClipboard (default)) {
  1474. break;
  1475. }
  1476. if (--num == 0) {
  1477. ThrowWin32 ();
  1478. }
  1479. Thread.Sleep (100);
  1480. }
  1481. }
  1482. const uint cfUnicodeText = 13;
  1483. void ThrowWin32 ()
  1484. {
  1485. throw new Win32Exception (Marshal.GetLastWin32Error ());
  1486. }
  1487. [DllImport ("User32.dll", SetLastError = true)]
  1488. [return: MarshalAs (UnmanagedType.Bool)]
  1489. static extern bool IsClipboardFormatAvailable (uint format);
  1490. [DllImport ("kernel32.dll", SetLastError = true)]
  1491. static extern int GlobalSize (IntPtr handle);
  1492. [DllImport ("kernel32.dll", SetLastError = true)]
  1493. static extern IntPtr GlobalLock (IntPtr hMem);
  1494. [DllImport ("kernel32.dll", SetLastError = true)]
  1495. [return: MarshalAs (UnmanagedType.Bool)]
  1496. static extern bool GlobalUnlock (IntPtr hMem);
  1497. [DllImport ("user32.dll", SetLastError = true)]
  1498. [return: MarshalAs (UnmanagedType.Bool)]
  1499. static extern bool OpenClipboard (IntPtr hWndNewOwner);
  1500. [DllImport ("user32.dll", SetLastError = true)]
  1501. [return: MarshalAs (UnmanagedType.Bool)]
  1502. static extern bool CloseClipboard ();
  1503. [DllImport ("user32.dll", SetLastError = true)]
  1504. static extern IntPtr SetClipboardData (uint uFormat, IntPtr data);
  1505. [DllImport ("user32.dll")]
  1506. static extern bool EmptyClipboard ();
  1507. [DllImport ("user32.dll", SetLastError = true)]
  1508. static extern IntPtr GetClipboardData (uint uFormat);
  1509. }
  1510. }