File size: 132,073 Bytes
8c763fb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if !UNIX
// Implementation notes: In the functions that take ConsoleHandle parameters, we only assert that the handle is valid and not
// closed, as opposed to doing a check and throwing an exception. This is because the win32 APIs that those functions wrap will
// fail on invalid/closed handles, and the check for API failure will throw the exception.
//
// On the use of DangerousGetHandle: If the handle has been invalidated, then the API we pass it to will return an error. These
// handles should not be exposed to recycling attacks (because they are not exposed at all), but if they were, the worse they
// could do is diddle with the console buffer.
using System;
using System.Buffers;
using System.Text;
using System.Runtime.InteropServices;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Management.Automation.Internal;
using System.ComponentModel;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
using Microsoft.Win32.SafeHandles;
using ConsoleHandle = Microsoft.Win32.SafeHandles.SafeFileHandle;
using WORD = System.UInt16;
using ULONG = System.UInt32;
using DWORD = System.UInt32;
using NakedWin32Handle = System.IntPtr;
using HWND = System.IntPtr;
using HDC = System.IntPtr;
#endif
using System.Diagnostics.CodeAnalysis;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell
{
/// <summary>
/// Class ConsoleControl is used to wrap the various win32 console APIs 1:1 (i.e. at a low level, without attempting to be a
/// "true" object-oriented library.
/// </summary>
internal static class ConsoleControl
{
#if !UNIX
#region structs
internal enum InputRecordEventTypes : ushort
{
// from wincon.h. These look like bit flags, but of course they could not really be used that way, since it would
// not make sense to have more than one of the INPUT_RECORD union members "in effect" at any one time.
KEY_EVENT = 0x0001,
MOUSE_EVENT = 0x0002,
WINDOW_BUFFER_SIZE_EVENT = 0x0004,
MENU_EVENT = 0x0008,
FOCUS_EVENT = 0x0010
}
[StructLayout(LayoutKind.Sequential)]
internal struct INPUT_RECORD
{
internal WORD EventType;
internal KEY_EVENT_RECORD KeyEvent;
}
[Flags]
internal enum ControlKeyStates : uint
{
// From wincon.h.
RIGHT_ALT_PRESSED = 0x0001, // the right alt key is pressed.
LEFT_ALT_PRESSED = 0x0002, // the left alt key is pressed.
RIGHT_CTRL_PRESSED = 0x0004, // the right ctrl key is pressed.
LEFT_CTRL_PRESSED = 0x0008, // the left ctrl key is pressed.
SHIFT_PRESSED = 0x0010, // the shift key is pressed.
NUMLOCK_ON = 0x0020, // the numlock light is on.
SCROLLLOCK_ON = 0x0040, // the scrolllock light is on.
CAPSLOCK_ON = 0x0080, // the capslock light is on.
ENHANCED_KEY = 0x0100 // the key is enhanced.
}
// LayoutKind must be Explicit
[StructLayout(LayoutKind.Sequential)]
internal struct KEY_EVENT_RECORD
{
internal bool KeyDown;
internal WORD RepeatCount;
internal WORD VirtualKeyCode;
internal WORD VirtualScanCode;
internal char UnicodeChar;
internal DWORD ControlKeyState;
}
[StructLayout(LayoutKind.Sequential)]
internal struct COORD
{
internal short X;
internal short Y;
public override string ToString()
{
return string.Create(CultureInfo.InvariantCulture, $"{X},{Y}");
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct CONSOLE_READCONSOLE_CONTROL
{
// from public/internal/windows/inc/winconp.h
internal ULONG nLength;
internal ULONG nInitialChars;
internal ULONG dwCtrlWakeupMask;
internal /* out */ ULONG dwControlKeyState;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct CONSOLE_FONT_INFO_EX
{
internal int cbSize;
internal int nFont;
internal short FontWidth;
internal short FontHeight;
internal int FontFamily;
internal int FontWeight;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
internal string FontFace;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CHAR_INFO
{
internal ushort UnicodeChar;
internal WORD Attributes;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SMALL_RECT
{
internal short Left;
internal short Top;
internal short Right;
internal short Bottom;
public override string ToString()
{
return string.Create(CultureInfo.InvariantCulture, $"{Left},{Top},{Right},{Bottom}");
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct CONSOLE_SCREEN_BUFFER_INFO
{
internal COORD BufferSize;
internal COORD CursorPosition;
internal WORD Attributes;
internal SMALL_RECT WindowRect;
internal COORD MaxWindowSize;
// NTRAID#Windows Out Of Band Releases-938428-2006/07/17-jwh
// Bring the total size of the struct to 24 bytes.
internal DWORD Padding;
}
[StructLayout(LayoutKind.Sequential)]
internal struct CONSOLE_CURSOR_INFO
{
internal DWORD Size;
internal bool Visible;
public override string ToString()
{
return string.Create(CultureInfo.InvariantCulture, $"Size: {Size}, Visible: {Visible}");
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct FONTSIGNATURE
{
// From public\sdk\inc\wingdi.h
// fsUsb*: A 128-bit Unicode subset bitfield (USB) identifying up to 126 Unicode subranges
internal DWORD fsUsb0;
internal DWORD fsUsb1;
internal DWORD fsUsb2;
internal DWORD fsUsb3;
// fsCsb*: A 64-bit, code-page bitfield (CPB) that identifies a specific character set or code page.
internal DWORD fsCsb0;
internal DWORD fsCsb1;
}
#region SentInput Data Structures
[StructLayout(LayoutKind.Sequential)]
internal struct INPUT
{
internal DWORD Type;
internal MouseKeyboardHardwareInput Data;
}
[StructLayout(LayoutKind.Explicit)]
internal struct MouseKeyboardHardwareInput
{
[FieldOffset(0)]
internal MouseInput Mouse;
[FieldOffset(0)]
internal KeyboardInput Keyboard;
[FieldOffset(0)]
internal HardwareInput Hardware;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MouseInput
{
/// <summary>
/// The absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member.
/// Absolute data is specified as the x coordinate of the mouse; relative data is specified as the number of pixels moved.
/// </summary>
internal int X;
/// <summary>
/// The absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member.
/// Absolute data is specified as the y coordinate of the mouse; relative data is specified as the number of pixels moved.
/// </summary>
internal int Y;
/// <summary>
/// If dwFlags contains MOUSEEVENTF_WHEEL, then mouseData specifies the amount of wheel movement. A positive value indicates that the wheel was rotated forward, away from the user;
/// a negative value indicates that the wheel was rotated backward, toward the user. One wheel click is defined as WHEEL_DELTA, which is 120.
/// </summary>
internal DWORD MouseData;
/// <summary>
/// A set of bit flags that specify various aspects of mouse motion and button clicks.
/// See (https://msdn.microsoft.com/library/ms646273(VS.85).aspx)
/// </summary>
internal DWORD Flags;
/// <summary>
/// The time stamp for the event, in milliseconds. If this parameter is 0, the system will provide its own time stamp.
/// </summary>
internal DWORD Time;
/// <summary>
/// An additional value associated with the mouse event. An application calls GetMessageExtraInfo to obtain this extra information.
/// </summary>
internal IntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal struct KeyboardInput
{
/// <summary>
/// A virtual-key code. The code must be a value in the range 1 to 254.
/// If the dwFlags member specifies KEYEVENTF_UNICODE, wVk must be 0.
/// </summary>
internal WORD Vk;
/// <summary>
/// A hardware scan code for the key. If dwFlags specifies KEYEVENTF_UNICODE,
/// wScan specifies a Unicode character which is to be sent to the foreground application.
/// </summary>
internal WORD Scan;
/// <summary>
/// Specifies various aspects of a keystroke.
/// This member can be certain combinations of the following values.
/// </summary>
internal DWORD Flags;
/// <summary>
/// The time stamp for the event, in milliseconds.
/// If this parameter is zero, the system will provide its own time stamp.
/// </summary>
internal DWORD Time;
/// <summary>
/// An additional value associated with the keystroke.
/// Use the GetMessageExtraInfo function to obtain this information.
/// </summary>
internal IntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
internal struct HardwareInput
{
/// <summary>
/// The message generated by the input hardware.
/// </summary>
internal DWORD Msg;
/// <summary>
/// The low-order word of the lParam parameter for uMsg.
/// </summary>
internal WORD ParamL;
/// <summary>
/// The high-order word of the lParam parameter for uMsg.
/// </summary>
internal WORD ParamH;
}
internal enum VirtualKeyCode : ushort
{
/// <summary>
/// LEFT ARROW key.
/// </summary>
Left = 0x25,
/// <summary>
/// ENTER key.
/// </summary>
Return = 0x0D,
}
/// <summary>
/// Specify the type of the input.
/// </summary>
internal enum InputType : uint
{
/// <summary>
/// INPUT_MOUSE = 0x00.
/// </summary>
Mouse = 0,
/// <summary>
/// INPUT_KEYBOARD = 0x01.
/// </summary>
Keyboard = 1,
/// <summary>
/// INPUT_HARDWARE = 0x02.
/// </summary>
Hardware = 2,
}
internal enum KeyboardFlag : uint
{
/// <summary>
/// If specified, the scan code was preceded by a prefix byte that has the value 0xE0 (224).
/// </summary>
ExtendedKey = 0x0001,
/// <summary>
/// If specified, the key is being released. If not specified, the key is being pressed.
/// </summary>
KeyUp = 0x0002,
/// <summary>
/// If specified, wScan identifies the key and wVk is ignored.
/// </summary>
Unicode = 0x0004,
/// <summary>
/// If specified, the system synthesizes a VK_PACKET keystroke. The wVk parameter must be zero.
/// This flag can only be combined with the KEYEVENTF_KEYUP flag.
/// </summary>
ScanCode = 0x0008
}
#endregion SentInput Data Structures
#endregion structs
#region Window Visibility
[DllImport(PinvokeDllNames.GetConsoleWindowDllName)]
internal static extern IntPtr GetConsoleWindow();
internal const int SW_HIDE = 0;
internal const int SW_SHOWNORMAL = 1;
internal const int SW_NORMAL = 1;
internal const int SW_SHOWMINIMIZED = 2;
internal const int SW_SHOWMAXIMIZED = 3;
internal const int SW_MAXIMIZE = 3;
internal const int SW_SHOWNOACTIVATE = 4;
internal const int SW_SHOW = 5;
internal const int SW_MINIMIZE = 6;
internal const int SW_SHOWMINNOACTIVE = 7;
internal const int SW_SHOWNA = 8;
internal const int SW_RESTORE = 9;
internal const int SW_SHOWDEFAULT = 10;
internal const int SW_FORCEMINIMIZE = 11;
internal const int SW_MAX = 11;
#if !UNIX
/// <summary>
/// Code to control the display properties of the a window...
/// </summary>
/// <param name="hWnd">The window to show...</param>
/// <param name="nCmdShow">The command to do.</param>
/// <returns>True if it was successful.</returns>
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
internal static void SetConsoleMode(ProcessWindowStyle style)
{
IntPtr hwnd = GetConsoleWindow();
Dbg.Assert(hwnd != IntPtr.Zero, "Console handle should never be zero");
switch (style)
{
case ProcessWindowStyle.Hidden:
ShowWindow(hwnd, SW_HIDE);
break;
case ProcessWindowStyle.Maximized:
ShowWindow(hwnd, SW_MAXIMIZE);
break;
case ProcessWindowStyle.Minimized:
ShowWindow(hwnd, SW_MINIMIZE);
break;
case ProcessWindowStyle.Normal:
ShowWindow(hwnd, SW_NORMAL);
break;
}
}
#endif
#endregion
#region Input break handler (Ctrl-C, Ctrl-Break)
/// <summary>
/// Types of control ConsoleBreakSignals received by break Win32Handler delegates.
/// </summary>
internal enum ConsoleBreakSignal : uint
{
// These correspond to the CRTL_XXX_EVENT #defines in public/sdk/inc/wincon.h
CtrlC = 0,
CtrlBreak = 1,
Close = 2,
Logoff = 5,
// This only gets received by services
Shutdown = 6,
// None is not really a signal -- it's used to indicate that no signal exists.
None = 0xFF
}
// NOTE: this delegate will be executed in its own thread
internal delegate bool BreakHandler(ConsoleBreakSignal ConsoleBreakSignal);
/// <summary>
/// Set the console's break handler.
/// </summary>
/// <param name="handlerDelegate"></param>
/// <exception cref="HostException">
/// If Win32's SetConsoleCtrlHandler fails
/// </exception>
internal static void AddBreakHandler(BreakHandler handlerDelegate)
{
bool result = NativeMethods.SetConsoleCtrlHandler(handlerDelegate, true);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "AddBreakHandler",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.AddBreakHandlerExceptionMessage);
throw e;
}
}
/// <summary>
/// Set the console's break handler to null.
/// </summary>
/// <exception cref="HostException">
/// If Win32's SetConsoleCtrlHandler fails
/// </exception>
internal static void RemoveBreakHandler()
{
bool result = NativeMethods.SetConsoleCtrlHandler(null, false);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "RemoveBreakHandler",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.RemoveBreakHandlerExceptionTemplate);
throw e;
}
}
#endregion
#region Win32Handles
private static readonly Lazy<ConsoleHandle> _keyboardInputHandle = new Lazy<SafeFileHandle>(() =>
{
var handle = NativeMethods.CreateFile(
"CONIN$",
(UInt32)(NativeMethods.AccessQualifiers.GenericRead | NativeMethods.AccessQualifiers.GenericWrite),
(UInt32)NativeMethods.ShareModes.ShareRead,
(IntPtr)0,
(UInt32)NativeMethods.CreationDisposition.OpenExisting,
0,
(IntPtr)0);
if (handle == NativeMethods.INVALID_HANDLE_VALUE)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "RetreiveInputConsoleHandle",
ErrorCategory.ResourceUnavailable,
ConsoleControlStrings.GetInputModeExceptionTemplate);
throw e;
}
return new ConsoleHandle(handle, true);
}
);
/// <summary>
/// Returns a ConsoleHandle to the console (keyboard device)
/// </summary>
internal static ConsoleHandle GetConioDeviceHandle()
{
return _keyboardInputHandle.Value;
}
private static readonly Lazy<ConsoleHandle> _outputHandle = new Lazy<SafeFileHandle>(() =>
{
// We use CreateFile here instead of GetStdWin32Handle, as GetStdWin32Handle will return redirected handles
var handle = NativeMethods.CreateFile(
"CONOUT$",
(UInt32)(NativeMethods.AccessQualifiers.GenericRead | NativeMethods.AccessQualifiers.GenericWrite),
(UInt32)NativeMethods.ShareModes.ShareWrite,
(IntPtr)0,
(UInt32)NativeMethods.CreationDisposition.OpenExisting,
0,
(IntPtr)0);
if (handle == NativeMethods.INVALID_HANDLE_VALUE)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "RetreiveActiveScreenBufferConsoleHandle",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetActiveScreenBufferHandleExceptionTemplate);
throw e;
}
return new ConsoleHandle(handle, true);
}
);
/// <summary>
/// Returns a ConsoleHandle to the active screen buffer, even if that output has been redirected.
/// </summary>
/// <returns></returns>
/// <exception cref="HostException">
/// If Win32's CreateFile fails
/// </exception>
internal static ConsoleHandle GetActiveScreenBufferHandle()
{
return _outputHandle.Value;
}
#endregion
#region Mode
/// <summary>
/// Flags used by ConsoleControl.GetMode and ConsoleControl.SetMode.
/// </summary>
[Flags]
internal enum ConsoleModes : uint
{
// These values from wincon.h
// input modes
ProcessedInput = 0x001,
LineInput = 0x002,
EchoInput = 0x004,
WindowInput = 0x008,
MouseInput = 0x010,
Insert = 0x020,
QuickEdit = 0x040,
Extended = 0x080,
AutoPosition = 0x100,
// output modes
ProcessedOutput = 0x001, // yes, I know they are the same values as some flags defined above.
WrapEndOfLine = 0x002,
VirtualTerminal = 0x004,
// Error getting console mode
Unknown = 0xffffffff,
}
/// <summary>
/// Returns a mask of ConsoleModes flags describing the current modality of the console.
/// </summary>
/// <exception cref="HostException">
/// If Win32's GetConsoleMode fails
/// </exception>
internal static ConsoleModes GetMode(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
UInt32 m = 0;
bool result = NativeMethods.GetConsoleMode(consoleHandle.DangerousGetHandle(), out m);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "GetConsoleMode",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetModeExceptionTemplate);
throw e;
}
return (ConsoleModes)m;
}
/// <summary>
/// Sets the current mode of the console device.
/// </summary>
/// <param name="consoleHandle">
/// Handle to the console device returned by GetInputHandle
/// </param>
/// <param name="mode">
/// Mask of mode flags
/// </param>
/// <exception cref="HostException">
/// If Win32's SetConsoleMode fails
/// </exception>
internal static void SetMode(ConsoleHandle consoleHandle, ConsoleModes mode)
{
Dbg.Assert(!consoleHandle.IsInvalid, "consoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
bool result = NativeMethods.SetConsoleMode(consoleHandle.DangerousGetHandle(), (DWORD)mode);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "SetConsoleMode",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetModeExceptionTemplate);
throw e;
}
}
#endregion
#region Input
/// <summary>
/// Reads input from the console device according to the mode in effect (see GetMode, SetMode)
/// </summary>
/// <param name="consoleHandle"></param>
/// Handle to the console device returned by GetInputHandle
/// <param name="initialContentLength">
/// Length of initial content of the edit buffer. Zero if no initial content exists.
/// Must be less than editBuffer length.
/// </param>
/// <param name="editBuffer">
/// Edit buffer with optional initial content.
/// Caution! Last position in the edit buffer is for a null in native code.
/// </param>
/// <param name="charactersToRead">
/// Number of characters to read from the device.
/// Must be less than editBuffer length.
/// </param>
/// <param name="endOnTab">
/// True to allow the user to terminate input by hitting the tab or shift-tab key, in addition to the enter key
/// </param>
/// <param name="keyState">
/// Bit mask indicating the state of the control/shift keys at the point input was terminated.
/// </param>
/// </param>
/// <returns></returns>
/// <exception cref="HostException">
/// If Win32's ReadConsole fails
/// </exception>
internal static string ReadConsole(
ConsoleHandle consoleHandle,
int initialContentLength,
Span<char> editBuffer,
int charactersToRead,
bool endOnTab,
out uint keyState)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
Dbg.Assert(initialContentLength < editBuffer.Length, "initialContentLength must be less than editBuffer.Length");
Dbg.Assert(charactersToRead < editBuffer.Length, "charactersToRead must be less than editBuffer.Length");
keyState = 0;
CONSOLE_READCONSOLE_CONTROL control = new CONSOLE_READCONSOLE_CONTROL();
control.nLength = (ULONG)Marshal.SizeOf(control);
control.nInitialChars = (ULONG)initialContentLength;
control.dwControlKeyState = 0;
if (endOnTab)
{
const int TAB = 0x9;
control.dwCtrlWakeupMask = (1 << TAB);
}
DWORD charsReaded = 0;
bool result =
NativeMethods.ReadConsole(
consoleHandle.DangerousGetHandle(),
editBuffer,
(DWORD)charactersToRead,
out charsReaded,
ref control);
keyState = control.dwControlKeyState;
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(
err,
"ReadConsole",
ErrorCategory.ReadError,
ConsoleControlStrings.ReadConsoleExceptionTemplate);
throw e;
}
if (charsReaded > (uint)charactersToRead)
{
charsReaded = (uint)charactersToRead;
}
return editBuffer.Slice(0, (int)charsReaded).ToString();
}
/// <summary>
/// Wraps Win32 ReadConsoleInput.
/// Returns the number of records read in buffer.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where input is read
/// </param>
/// <param name="buffer">
/// array where data read are stored
/// </param>
/// <returns>
/// actual number of input records read
/// </returns>
/// <exception cref="HostException">
/// If Win32's ReadConsoleInput fails
/// </exception>
internal static int ReadConsoleInput(ConsoleHandle consoleHandle, ref INPUT_RECORD[] buffer)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
DWORD recordsRead = 0;
bool result =
NativeMethods.ReadConsoleInput(
consoleHandle.DangerousGetHandle(),
buffer,
(DWORD)buffer.Length,
out recordsRead);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "ReadConsoleInput",
ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleInputExceptionTemplate);
throw e;
}
return (int)recordsRead;
}
/// <summary>
/// Wraps Win32 PeekConsoleInput.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where input is peeked
/// </param>
/// <param name="buffer">
/// array where data read are stored
/// </param>
/// <returns>
/// actual number of input records peeked
/// </returns>
/// <exception cref="HostException">
/// If Win32's PeekConsoleInput fails
/// </exception>
internal static int PeekConsoleInput
(
ConsoleHandle consoleHandle,
ref INPUT_RECORD[] buffer
)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
DWORD recordsRead;
bool result =
NativeMethods.PeekConsoleInput(
consoleHandle.DangerousGetHandle(),
buffer,
(DWORD)buffer.Length,
out recordsRead);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "PeekConsoleInput",
ErrorCategory.ReadError, ConsoleControlStrings.PeekConsoleInputExceptionTemplate);
throw e;
}
return (int)recordsRead;
}
/// <summary>
/// Wraps Win32 GetNumberOfConsoleInputEvents.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where the number of console input events is obtained
/// </param>
/// <returns>
/// number of console input events
/// </returns>
/// <exception cref="HostException">
/// If Win32's GetNumberOfConsoleInputEvents fails
/// </exception>
internal static int GetNumberOfConsoleInputEvents(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
DWORD numEvents;
bool result = NativeMethods.GetNumberOfConsoleInputEvents(consoleHandle.DangerousGetHandle(), out numEvents);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "GetNumberOfConsoleInputEvents",
ErrorCategory.ReadError, ConsoleControlStrings.GetNumberOfConsoleInputEventsExceptionTemplate);
throw e;
}
return (int)numEvents;
}
/// <summary>
/// Wraps Win32 FlushConsoleInputBuffer.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where the input buffer is flushed
/// </param>
/// <exception cref="HostException">
/// If Win32's FlushConsoleInputBuffer fails
/// </exception>
internal static void FlushConsoleInputBuffer(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
bool result = false;
NakedWin32Handle h = consoleHandle.DangerousGetHandle();
result = NativeMethods.FlushConsoleInputBuffer(h);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "FlushConsoleInputBuffer",
ErrorCategory.ReadError, ConsoleControlStrings.FlushConsoleInputBufferExceptionTemplate);
throw e;
}
}
#endregion Input
#region Buffer
/// <summary>
/// Wraps Win32 GetConsoleScreenBufferInfo
/// Returns Console Screen Buffer Info.
/// </summary>
/// <param name="consoleHandle">
/// Handle for the console where the screen buffer info is obtained
/// </param>
/// <returns>
/// info about the screen buffer. See the definition of CONSOLE_SCREEN_BUFFER_INFO
/// </returns>
/// <exception cref="HostException">
/// If Win32's GetConsoleScreenBufferInfo fails
/// </exception>
internal static CONSOLE_SCREEN_BUFFER_INFO GetConsoleScreenBufferInfo(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
bool result = NativeMethods.GetConsoleScreenBufferInfo(consoleHandle.DangerousGetHandle(), out bufferInfo);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "GetConsoleScreenBufferInfo",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetConsoleScreenBufferInfoExceptionTemplate);
throw e;
}
return bufferInfo;
}
/// <summary>
/// Set the output buffer's size.
/// </summary>
/// <param name="consoleHandle"></param>
/// <param name="newSize"></param>
/// <exception cref="HostException">
/// If Win32's SetConsoleScreenBufferSize fails
/// </exception>
internal static void SetConsoleScreenBufferSize(ConsoleHandle consoleHandle, Size newSize)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
COORD s;
s.X = (short)newSize.Width;
s.Y = (short)newSize.Height;
bool result = NativeMethods.SetConsoleScreenBufferSize(consoleHandle.DangerousGetHandle(), s);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "SetConsoleScreenBufferSize",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleScreenBufferSizeExceptionTemplate);
throw e;
}
}
internal static bool IsConsoleColor(ConsoleColor c)
{
switch (c)
{
case ConsoleColor.Black:
case ConsoleColor.Blue:
case ConsoleColor.Cyan:
case ConsoleColor.DarkBlue:
case ConsoleColor.DarkCyan:
case ConsoleColor.DarkGray:
case ConsoleColor.DarkGreen:
case ConsoleColor.DarkMagenta:
case ConsoleColor.DarkRed:
case ConsoleColor.DarkYellow:
case ConsoleColor.Gray:
case ConsoleColor.Green:
case ConsoleColor.Magenta:
case ConsoleColor.Red:
case ConsoleColor.White:
case ConsoleColor.Yellow:
return true;
}
return false;
}
internal static void WORDToColor(WORD attribute, out ConsoleColor foreground, out ConsoleColor background)
{
// foreground color is the low-byte in the word, background color is the hi-byte.
foreground = (ConsoleColor)(attribute & 0x0f);
background = (ConsoleColor)((attribute & 0xf0) >> 4);
Dbg.Assert(IsConsoleColor(foreground), "unknown color");
Dbg.Assert(IsConsoleColor(background), "unknown color");
}
internal static WORD ColorToWORD(ConsoleColor foreground, ConsoleColor background)
{
WORD result = (WORD)(((int)background << 4) | (int)foreground);
return result;
}
/// <summary>
/// Wrap32 WriteConsoleOutput.
/// This wrapper is not limited to 64K or 8K CHAR_INFO to which Win32's WriteConsoleOutput
/// is constrained.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where output is written
/// </param>
/// <param name="origin">
/// location on screen buffer where writing starts
/// </param>
/// <param name="contents">
/// 2D array of cells. Caller needs to ensure that the array is 2D.
/// </param>
/// <exception cref="HostException">
/// If Win32's GetConsoleScreenBufferInfo fails
/// If there is not enough memory to complete calls to Win32's WriteConsoleOutput
/// </exception>
/// <exception cref="ArgumentNullException">
/// If <paramref name="contents"/> is null
/// </exception>
/// <exception cref="ArgumentException">
/// If it is illegal to write <paramref name="contents"/> to the output buffer
/// </exception>
internal static void WriteConsoleOutput(ConsoleHandle consoleHandle, Coordinates origin, BufferCell[,] contents)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
if (contents == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(contents));
}
uint codePage;
if (IsCJKOutputCodePage(out codePage))
{
// contentsRegion indicates the area in contents (declared below) in which
// the data read from ReadConsoleOutput is stored.
Rectangle contentsRegion = new Rectangle();
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo =
GetConsoleScreenBufferInfo(consoleHandle);
int bufferWidth = bufferInfo.BufferSize.X;
int bufferHeight = bufferInfo.BufferSize.Y;
Rectangle screenRegion = new Rectangle(
origin.X, origin.Y,
Math.Min(origin.X + contents.GetLength(1) - 1, bufferWidth - 1),
Math.Min(origin.Y + contents.GetLength(0) - 1, bufferHeight - 1));
contentsRegion.Left = contents.GetLowerBound(1);
contentsRegion.Top = contents.GetLowerBound(0);
contentsRegion.Right = contentsRegion.Left +
screenRegion.Right - screenRegion.Left;
contentsRegion.Bottom = contentsRegion.Top +
screenRegion.Bottom - screenRegion.Top;
#if DEBUG
// Check contents in contentsRegion
CheckWriteConsoleOutputContents(contents, contentsRegion);
#endif
// Identify edges and areas of identical contiguous edges in contentsRegion
List<BufferCellArrayRowTypeRange> sameEdgeAreas = new List<BufferCellArrayRowTypeRange>();
int firstLeftTrailingRow = -1, firstRightLeadingRow = -1;
BuildEdgeTypeInfo(contentsRegion, contents,
sameEdgeAreas, out firstLeftTrailingRow, out firstRightLeadingRow);
#if DEBUG
CheckWriteEdges(consoleHandle, codePage, origin, contents, contentsRegion,
bufferInfo, firstLeftTrailingRow, firstRightLeadingRow);
#endif
foreach (BufferCellArrayRowTypeRange area in sameEdgeAreas)
{
Coordinates o = new Coordinates(origin.X,
origin.Y + area.Start - contentsRegion.Top);
Rectangle contRegion = new Rectangle(
contentsRegion.Left, area.Start, contentsRegion.Right, area.End);
if ((area.Type & BufferCellArrayRowType.LeftTrailing) != 0)
{
contRegion.Left++;
o.X++;
if (o.X >= bufferWidth || contRegion.Right < contRegion.Left)
{
return;
}
}
WriteConsoleOutputCJK(consoleHandle, o, contRegion, contents, area.Type);
}
}
else
{
WriteConsoleOutputPlain(consoleHandle, origin, contents);
}
}
private static void BuildEdgeTypeInfo(
Rectangle contentsRegion,
BufferCell[,] contents,
List<BufferCellArrayRowTypeRange> sameEdgeAreas,
out int firstLeftTrailingRow,
out int firstRightLeadingRow)
{
firstLeftTrailingRow = -1;
firstRightLeadingRow = -1;
BufferCellArrayRowType edgeType =
GetEdgeType(contents[contentsRegion.Top, contentsRegion.Left],
contents[contentsRegion.Top, contentsRegion.Right]);
for (int r = contentsRegion.Top; r <= contentsRegion.Bottom;)
{
BufferCellArrayRowTypeRange range;
range.Start = r;
range.Type = edgeType;
if (firstLeftTrailingRow == -1 && ((range.Type & BufferCellArrayRowType.LeftTrailing) != 0))
{
firstLeftTrailingRow = r;
}
if (firstRightLeadingRow == -1 && ((range.Type & BufferCellArrayRowType.RightLeading) != 0))
{
firstRightLeadingRow = r;
}
while (true)
{
r++;
if (r > contentsRegion.Bottom)
{
range.End = r - 1;
sameEdgeAreas.Add(range);
return;
}
edgeType = GetEdgeType(contents[r, contentsRegion.Left], contents[r, contentsRegion.Right]);
if (edgeType != range.Type)
{
range.End = r - 1;
sameEdgeAreas.Add(range);
break;
}
}
}
}
private static BufferCellArrayRowType GetEdgeType(BufferCell left, BufferCell right)
{
BufferCellArrayRowType edgeType = 0;
if (left.BufferCellType == BufferCellType.Trailing)
{
edgeType |= BufferCellArrayRowType.LeftTrailing;
}
if (right.BufferCellType == BufferCellType.Leading)
{
edgeType |= BufferCellArrayRowType.RightLeading;
}
return edgeType;
}
private struct BufferCellArrayRowTypeRange
{
internal int Start;
internal int End;
internal BufferCellArrayRowType Type;
}
[Flags]
private enum BufferCellArrayRowType : uint
{
LeftTrailing = 0x1,
RightLeading = 0x2
}
/// <summary>
/// Check the existing screen columns left and right of areas to be written.
/// </summary>
/// <param name="consoleHandle"></param>
/// <param name="codePage"></param>
/// <param name="origin">Must be within the screen buffer.</param>
/// <param name="contents"></param>
/// <param name="contentsRegion"></param>
/// <param name="bufferInfo"></param>
/// <param name="firstLeftTrailingRow"></param>
/// <param name="firstRightLeadingRow"></param>
/// <exception cref="ArgumentException">
/// If it is illegal to write <paramref name="contents"/> at <paramref name="origin"/>
/// </exception>
/// <exception cref="HostException">
/// If there is not enough memory to complete calls to Win32's ReadConsoleOutput
/// </exception>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called in CHK builds")]
internal static void CheckWriteEdges(
ConsoleHandle consoleHandle,
uint codePage, Coordinates origin,
BufferCell[,] contents,
Rectangle contentsRegion,
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo,
int firstLeftTrailingRow,
int firstRightLeadingRow)
{
Rectangle existingRegion = new Rectangle(0, 0, 1, contentsRegion.Bottom - contentsRegion.Top);
if (origin.X == 0)
{
if (firstLeftTrailingRow >= 0)
{
throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{firstLeftTrailingRow}, {contentsRegion.Left}]"));
}
}
else
{
// use ReadConsoleOutputCJK because checking the left and right edges of the existing output
// is NOT needed
BufferCell[,] leftExisting = new BufferCell[existingRegion.Bottom + 1, 2];
ReadConsoleOutputCJK(consoleHandle, codePage,
new Coordinates(origin.X - 1, origin.Y), existingRegion, ref leftExisting);
for (int r = contentsRegion.Top, i = 0; r <= contentsRegion.Bottom; r++, i++)
{
if (leftExisting[r, 0].BufferCellType == BufferCellType.Leading ^
contents[r, contentsRegion.Left].BufferCellType == BufferCellType.Trailing)
{
throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {contentsRegion.Left}]"));
}
}
}
// Check right edge
if (origin.X + (contentsRegion.Right - contentsRegion.Left) + 1 >= bufferInfo.BufferSize.X)
{
if (firstRightLeadingRow >= 0)
{
throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{firstRightLeadingRow}, {contentsRegion.Right}]"));
}
}
else
{
// use ReadConsoleOutputCJK because checking the left and right edges of the existing output
// is NOT needed
BufferCell[,] rightExisting = new BufferCell[existingRegion.Bottom + 1, 2];
ReadConsoleOutputCJK(consoleHandle, codePage,
new Coordinates(origin.X + (contentsRegion.Right - contentsRegion.Left), origin.Y), existingRegion, ref rightExisting);
for (int r = contentsRegion.Top, i = 0; r <= contentsRegion.Bottom; r++, i++)
{
if (rightExisting[r, 0].BufferCellType == BufferCellType.Leading ^
contents[r, contentsRegion.Right].BufferCellType == BufferCellType.Leading)
{
throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {contentsRegion.Right}]"));
}
}
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Called in CHK builds")]
private static void CheckWriteConsoleOutputContents(BufferCell[,] contents, Rectangle contentsRegion)
{
for (int r = contentsRegion.Top; r <= contentsRegion.Bottom; r++)
{
for (int c = contentsRegion.Left; c <= contentsRegion.Right; c++)
{
// Changes have been made in the following code such that 2 cell characters
// (Chinese, Japanese or Korean) can be in a single BufferCell structure
// which is complete
if (contents[r, c].BufferCellType == BufferCellType.Trailing &&
contents[r, c].Character != 0)
{
// trailing character is not 0
throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {c}]"));
}
if (contents[r, c].BufferCellType == BufferCellType.Leading)
{
c++;
if (c > contentsRegion.Right)
{
break;
}
if (contents[r, c].Character != 0 || contents[r, c].BufferCellType != BufferCellType.Trailing)
{
// for a 2 cell character, either there is no trailing BufferCell or
// the trailing BufferCell's character is not 0
throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {c}]"));
}
}
}
}
}
private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinates origin, Rectangle contentsRegion, BufferCell[,] contents, BufferCellArrayRowType rowType)
{
Dbg.Assert(origin.X >= 0 && origin.Y >= 0,
"origin must be within the output buffer");
int rows = contentsRegion.Bottom - contentsRegion.Top + 1;
int cols = contentsRegion.Right - contentsRegion.Left + 1;
CONSOLE_FONT_INFO_EX fontInfo = GetConsoleFontInfo(consoleHandle);
int fontType = fontInfo.FontFamily & NativeMethods.FontTypeMask;
bool trueTypeInUse = (fontType & NativeMethods.TrueTypeFont) == NativeMethods.TrueTypeFont;
int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes
COORD bufferCoord;
bufferCoord.X = 0;
bufferCoord.Y = 0;
// keeps track of which screen area write
SMALL_RECT writeRegion;
writeRegion.Top = (short)origin.Y;
int rowsRemaining = rows;
while (rowsRemaining > 0)
{
// Iteration of columns is nested inside iteration of rows.
// If the size of contents exceeds the buffer limit, writing is
// done in blocks of size equal to the bufferlimit from left to right
// then top to bottom.
// For each iteration of rows,
// - writeRegion.Left and bufferSize.X are reset
// - rowsRemaining, writeRegion.Top, writeRegion.Bottom, and bufferSize.Y
// are updated
// For each iteration of columns,
// - writeRegion.Left, writeRegion.Right and bufferSize.X are updated
writeRegion.Left = (short)origin.X;
COORD bufferSize;
bufferSize.X = (short)Math.Min(cols, bufferLimit);
bufferSize.Y = (short)Math.Min
(
rowsRemaining,
bufferLimit / bufferSize.X
);
writeRegion.Bottom = (short)(writeRegion.Top + bufferSize.Y - 1);
// atRow is at which row of contents a particular iteration is operating
int atRow = rows - rowsRemaining + contentsRegion.Top;
// number of columns yet to be written
int colsRemaining = cols;
while (colsRemaining > 0)
{
writeRegion.Right = (short)(writeRegion.Left + bufferSize.X - 1);
// atCol is at which column of contents a particular iteration is operating
int atCol = cols - colsRemaining + contentsRegion.Left;
// if this is not the last column iteration &&
// the leftmost BufferCell is a leading cell, don't write that cell
if (colsRemaining > bufferSize.X &&
contents[atRow, atCol + bufferSize.X - 1].BufferCellType == BufferCellType.Leading)
{
bufferSize.X--;
writeRegion.Right--;
}
CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.Y * bufferSize.X];
// copy characterBuffer to contents;
int characterBufferIndex = 0;
bool lastCharIsLeading = false;
BufferCell lastLeadingCell = new BufferCell();
for (int r = atRow; r < bufferSize.Y + atRow; r++)
{
for (int c = atCol; c < bufferSize.X + atCol; c++, characterBufferIndex++)
{
if (contents[r, c].BufferCellType == BufferCellType.Complete)
{
characterBuffer[characterBufferIndex].UnicodeChar =
(ushort)contents[r, c].Character;
characterBuffer[characterBufferIndex].Attributes =
(ushort)(ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor));
lastCharIsLeading = false;
}
else if (contents[r, c].BufferCellType == BufferCellType.Leading)
{
characterBuffer[characterBufferIndex].UnicodeChar =
(ushort)contents[r, c].Character;
characterBuffer[characterBufferIndex].Attributes =
(ushort)(ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor)
| (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_LEADING_BYTE);
lastCharIsLeading = true;
lastLeadingCell = contents[r, c];
}
else if (contents[r, c].BufferCellType == BufferCellType.Trailing)
{
// The FontFamily is a 8-bit integer. The low-order bit (bit 0) specifies the pitch of the font.
// If it is 1, the font is variable pitch (or proportional). If it is 0, the font is fixed pitch
// (or monospace). Bits 1 and 2 specify the font type. If both bits are 0, the font is a raster font;
// if bit 1 is 1 and bit 2 is 0, the font is a vector font; if bit 1 is 0 and bit 2 is set, or if both
// bits are 1, the font is true type. Bit 3 is 1 if the font is a device font; otherwise, it is 0.
// We only care about the bit 1 and 2, which indicate the font type.
// There are only two font type defined for the Console, at
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\.
// Console\Nls --- national language supports
// Console\RasterFonts --- raster type font
// Console\TrueTypeFont --- true type font
// For CJK characters, if it's TrueType, we need to output the trailing character marked with "Trailing_byte"
// attribute. But if it's RasterFont, we ignore the trailing character, and the "Leading_byte"/"Trailing_byte"
// attributes are not effective at all when reading the character from the console buffer.
if (lastCharIsLeading && trueTypeInUse)
{
// For TrueType Font, we output the trailing byte with "Trailing_byte" attribute
characterBuffer[characterBufferIndex].UnicodeChar = lastLeadingCell.Character;
characterBuffer[characterBufferIndex].Attributes =
(ushort)(ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor)
| (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_TRAILING_BYTE);
}
else
{
// We don't output anything for this cell if Raster font is in use, or if the last cell is not a leading byte
characterBufferIndex--;
}
lastCharIsLeading = false;
}
}
}
// Now writeRegion, bufferSize and characterBuffer are updated.
// Call NativeMethods.WriteConsoleOutput
bool result;
if ((rowType & BufferCellArrayRowType.RightLeading) != 0 &&
colsRemaining == bufferSize.X)
{
COORD bSize = bufferSize;
bSize.X++;
SMALL_RECT wRegion = writeRegion;
wRegion.Right++;
result = NativeMethods.WriteConsoleOutput(
consoleHandle.DangerousGetHandle(),
characterBuffer,
bSize,
bufferCoord,
ref wRegion);
}
else
{
result = NativeMethods.WriteConsoleOutput(
consoleHandle.DangerousGetHandle(),
characterBuffer,
bufferSize,
bufferCoord,
ref writeRegion);
}
if (!result)
{
// When WriteConsoleOutput fails, half bufferLimit
if (bufferLimit < 2)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "WriteConsoleOutput",
ErrorCategory.WriteError, ConsoleControlStrings.WriteConsoleOutputExceptionTemplate);
throw e;
}
bufferLimit /= 2;
if (cols == colsRemaining)
{
// if cols == colsRemaining, nothing is guaranteed written in this pass and
// the unwritten area is still rectangular
bufferSize.Y = 0;
break;
}
else
{
// some areas have been written. This could only happen when the number of columns
// to write is larger than bufferLimit. In that case, the algorithm writes one row
// at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged
// to retry with a smaller bufferSize.X.
Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}"));
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
continue;
}
}
colsRemaining -= bufferSize.X;
writeRegion.Left += bufferSize.X;
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
} // column iteration
rowsRemaining -= bufferSize.Y;
writeRegion.Top += bufferSize.Y;
} // row iteration
}
private static void WriteConsoleOutputPlain(ConsoleHandle consoleHandle, Coordinates origin, BufferCell[,] contents)
{
int rows = contents.GetLength(0);
int cols = contents.GetLength(1);
if ((rows <= 0) || cols <= 0)
{
tracer.WriteLine("contents passed in has 0 rows and columns");
return;
}
int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes
COORD bufferCoord;
bufferCoord.X = 0;
bufferCoord.Y = 0;
// keeps track of which screen area write
SMALL_RECT writeRegion;
writeRegion.Top = (short)origin.Y;
int rowsRemaining = rows;
while (rowsRemaining > 0)
{
// Iteration of columns is nested inside iteration of rows.
// If the size of contents exceeds the buffer limit, writing is
// done in blocks of size equal to the bufferlimit from left to right
// then top to bottom.
// For each iteration of rows,
// - writeRegion.Left and bufferSize.X are reset
// - rowsRemaining, writeRegion.Top, writeRegion.Bottom, and bufferSize.Y
// are updated
// For each iteration of columns,
// - writeRegion.Left, writeRegion.Right and bufferSize.X are updated
writeRegion.Left = (short)origin.X;
COORD bufferSize;
bufferSize.X = (short)Math.Min(cols, bufferLimit);
bufferSize.Y = (short)Math.Min
(
rowsRemaining,
bufferLimit / bufferSize.X
);
writeRegion.Bottom = (short)(writeRegion.Top + bufferSize.Y - 1);
// atRow is at which row of contents a particular iteration is operating
int atRow = rows - rowsRemaining + contents.GetLowerBound(0);
// number of columns yet to be written
int colsRemaining = cols;
while (colsRemaining > 0)
{
writeRegion.Right = (short)(writeRegion.Left + bufferSize.X - 1);
// atCol is at which column of contents a particular iteration is operating
int atCol = cols - colsRemaining + contents.GetLowerBound(1);
CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.Y * bufferSize.X];
// copy characterBuffer to contents;
for (int r = atRow, characterBufferIndex = 0;
r < bufferSize.Y + atRow; r++)
{
for (int c = atCol; c < bufferSize.X + atCol; c++, characterBufferIndex++)
{
characterBuffer[characterBufferIndex].UnicodeChar =
(ushort)contents[r, c].Character;
characterBuffer[characterBufferIndex].Attributes =
ColorToWORD(contents[r, c].ForegroundColor, contents[r, c].BackgroundColor);
}
}
// Now writeRegion, bufferSize and characterBuffer are updated.
// Call NativeMethods.WriteConsoleOutput
bool result =
NativeMethods.WriteConsoleOutput(
consoleHandle.DangerousGetHandle(),
characterBuffer,
bufferSize,
bufferCoord,
ref writeRegion);
if (!result)
{
// When WriteConsoleOutput fails, half bufferLimit
if (bufferLimit < 2)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "WriteConsoleOutput",
ErrorCategory.WriteError, ConsoleControlStrings.WriteConsoleOutputExceptionTemplate);
throw e;
}
bufferLimit /= 2;
if (cols == colsRemaining)
{
// if cols == colsRemaining, nothing is guaranteed written in this pass and
// the unwritten area is still rectangular
bufferSize.Y = 0;
break;
}
else
{
// some areas have been written. This could only happen when the number of columns
// to write is larger than bufferLimit. In that case, the algorithm writes one row
// at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged
// to retry with a smaller bufferSize.X.
Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}"));
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
continue;
}
}
colsRemaining -= bufferSize.X;
writeRegion.Left += bufferSize.X;
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
} // column iteration
rowsRemaining -= bufferSize.Y;
writeRegion.Top += bufferSize.Y;
} // row iteration
}
/// <summary>
/// Wrap32 ReadConsoleOutput
/// This wrapper is not limited to 64K or 8K CHAR_INFO to which Win32's ReadConsoleOutput
/// is constrained.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where output is read
/// </param>
/// <param name="origin">
/// location on screen buffer where reading begins
/// </param>
/// <param name="contentsRegion">
/// indicates the area in <paramref name="contents"/> where the data read
/// is stored.
/// </param>
/// <param name="contents">
/// this is ref because the bounds and size of the array are needed.
/// </param>
/// <exception cref="HostException">
/// If there is not enough memory to complete calls to Win32's ReadConsoleOutput
/// </exception>
internal static void ReadConsoleOutput
(
ConsoleHandle consoleHandle,
Coordinates origin,
Rectangle contentsRegion,
ref BufferCell[,] contents
)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
uint codePage;
if (IsCJKOutputCodePage(out codePage))
{
ReadConsoleOutputCJK(consoleHandle, codePage, origin, contentsRegion, ref contents);
// check left edge
BufferCell[,] cellArray = null;
Coordinates checkOrigin;
Rectangle cellArrayRegion = new Rectangle(0, 0, 1, contentsRegion.Bottom - contentsRegion.Top);
if (origin.X > 0 && ShouldCheck(contentsRegion.Left, contents, contentsRegion))
{
cellArray = new BufferCell[cellArrayRegion.Bottom + 1, 2];
checkOrigin = new Coordinates(origin.X - 1, origin.Y);
ReadConsoleOutputCJK(consoleHandle, codePage, checkOrigin,
cellArrayRegion, ref cellArray);
for (int i = 0; i <= cellArrayRegion.Bottom; i++)
{
if (cellArray[i, 0].BufferCellType == BufferCellType.Leading)
{
contents[contentsRegion.Top + i, 0].Character = (char)0;
contents[contentsRegion.Top + i, 0].BufferCellType = BufferCellType.Trailing;
}
}
}
// check right edge
ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo =
GetConsoleScreenBufferInfo(consoleHandle);
if (origin.X + (contentsRegion.Right - contentsRegion.Left) + 1 < bufferInfo.BufferSize.X &&
ShouldCheck(contentsRegion.Right, contents, contentsRegion))
{
cellArray ??= new BufferCell[cellArrayRegion.Bottom + 1, 2];
checkOrigin = new Coordinates(origin.X +
(contentsRegion.Right - contentsRegion.Left), origin.Y);
ReadConsoleOutputCJK(consoleHandle, codePage, checkOrigin,
cellArrayRegion, ref cellArray);
for (int i = 0; i <= cellArrayRegion.Bottom; i++)
{
if (cellArray[i, 0].BufferCellType == BufferCellType.Leading)
{
contents[contentsRegion.Top + i, contentsRegion.Right] = cellArray[i, 0];
}
}
}
}
else
{
ReadConsoleOutputPlain(consoleHandle, origin, contentsRegion, ref contents);
}
}
#region ReadConsoleOutput CJK
/// <summary>
/// If an edge cell read is a blank, it is potentially part of a double width character. Hence,
/// at least one of the left and right edges should be checked.
/// </summary>
/// <param name="edge"></param>
/// <param name="contents"></param>
/// <param name="contentsRegion"></param>
/// <returns></returns>
private static bool ShouldCheck(int edge, BufferCell[,] contents, Rectangle contentsRegion)
{
for (int i = contentsRegion.Top; i <= contentsRegion.Bottom; i++)
{
if (contents[i, edge].Character == ' ')
{
return true;
}
}
return false;
}
private static bool ReadConsoleOutputCJKSmall
(
ConsoleHandle consoleHandle,
uint codePage,
Coordinates origin,
Rectangle contentsRegion,
ref BufferCell[,] contents
)
{
COORD bufferSize;
bufferSize.X = (short)(contentsRegion.Right - contentsRegion.Left + 1);
bufferSize.Y = (short)(contentsRegion.Bottom - contentsRegion.Top + 1);
COORD bufferCoord;
bufferCoord.X = 0;
bufferCoord.Y = 0;
CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.X * bufferSize.Y];
SMALL_RECT readRegion;
readRegion.Left = (short)origin.X;
readRegion.Top = (short)origin.Y;
readRegion.Right = (short)(origin.X + bufferSize.X - 1);
readRegion.Bottom = (short)(origin.Y + bufferSize.Y - 1);
bool result = NativeMethods.ReadConsoleOutput(
consoleHandle.DangerousGetHandle(),
characterBuffer,
bufferSize,
bufferCoord,
ref readRegion);
if (!result)
{
return false;
}
int characterBufferIndex = 0;
for (int r = contentsRegion.Top; r <= contentsRegion.Bottom; r++)
{
for (int c = contentsRegion.Left; c <= contentsRegion.Right; c++, characterBufferIndex++)
{
ConsoleColor fgColor, bgColor;
contents[r, c].Character = (char)characterBuffer[characterBufferIndex].UnicodeChar;
WORDToColor(characterBuffer[characterBufferIndex].Attributes,
out fgColor,
out bgColor);
contents[r, c].ForegroundColor = fgColor;
contents[r, c].BackgroundColor = bgColor;
// Set the attributes of the buffercells to be the same as that of the
// incoming CHAR_INFO. In case where the CHAR_INFO character is a
// trailing byte set the Character of BufferCell to 0. This is done
// because at a lot of places this check is being done. Having a trailing
// character to be 0 is by design.
if ((characterBuffer[characterBufferIndex].Attributes & (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_LEADING_BYTE)
== (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_LEADING_BYTE)
{
contents[r, c].BufferCellType = BufferCellType.Leading;
}
else if ((characterBuffer[characterBufferIndex].Attributes & (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_TRAILING_BYTE)
== (ushort)NativeMethods.CHAR_INFO_Attributes.COMMON_LVB_TRAILING_BYTE)
{
contents[r, c].Character = (char)0;
contents[r, c].BufferCellType = BufferCellType.Trailing;
}
else
{
int charLength = LengthInBufferCells(contents[r, c].Character);
if (charLength == 2)
{
// When it's RasterFont, the "Leading_byte"/"Trailing_byte" are not effective, we
// need to decide the leading byte by checking the char length.
contents[r, c].BufferCellType = BufferCellType.Leading;
c++;
contents[r, c].Character = (char)0;
contents[r, c].ForegroundColor = fgColor;
contents[r, c].BackgroundColor = bgColor;
contents[r, c].BufferCellType = BufferCellType.Trailing;
}
else
{
contents[r, c].BufferCellType = BufferCellType.Complete;
}
}
}
}
return true;
}
/// <summary>
/// Can handle reading CJK characters, but the left and right edges are not checked.
/// </summary>
/// <param name="consoleHandle"></param>
/// <param name="codePage"></param>
/// <param name="origin"></param>
/// <param name="contentsRegion"></param>
/// <param name="contents"></param>
/// <exception cref="HostException">
/// If there is not enough memory to complete calls to Win32's ReadConsoleOutput
/// </exception>
internal static void ReadConsoleOutputCJK
(
ConsoleHandle consoleHandle,
uint codePage,
Coordinates origin,
Rectangle contentsRegion,
ref BufferCell[,] contents
)
{
int rows = contentsRegion.Bottom - contentsRegion.Top + 1;
int cols = contentsRegion.Right - contentsRegion.Left + 1;
if ((rows <= 0) || cols <= 0)
{
tracer.WriteLine("invalid contents region");
return;
}
int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes
COORD bufferCoord;
bufferCoord.X = 0;
bufferCoord.Y = 0;
// keeps track of which screen area is read
SMALL_RECT readRegion;
readRegion.Top = (short)origin.Y;
int rowsRemaining = rows;
while (rowsRemaining > 0)
{
// Iteration of columns is nested inside iteration of rows.
// If the size of contents exceeds the buffer limit, reading is
// done in blocks of size equal to the bufferlimit from left to right
// then top to bottom.
// For each iteration of rows,
// - readRegion.Left and bufferSize.X are reset
// - rowsRemaining, readRegion.Top, readRegion.Bottom, and bufferSize.Y
// are updated
// For each iteration of columns,
// - readRegion.Left, readRegion.Right and bufferSize.X are updated
readRegion.Left = (short)origin.X;
COORD bufferSize;
bufferSize.X = (short)Math.Min(cols, bufferLimit);
bufferSize.Y = (short)Math.Min
(
rowsRemaining,
bufferLimit / bufferSize.X
);
readRegion.Bottom = (short)(readRegion.Top + bufferSize.Y - 1);
// atContentsRow is at which row of contents a particular iteration is operating
int atContentsRow = rows - rowsRemaining + contentsRegion.Top;
// number of columns yet to be read
int colsRemaining = cols;
while (colsRemaining > 0)
{
// atContentsCol is at which column of contents a particular iteration is operating
int atContentsCol = cols - colsRemaining + contentsRegion.Left;
readRegion.Right = (short)(readRegion.Left + bufferSize.X - 1);
// Now readRegion and bufferSize are updated.
Rectangle atContents = new Rectangle(atContentsCol, atContentsRow,
atContentsCol + bufferSize.X - 1, atContentsRow + bufferSize.Y - 1);
bool result =
ReadConsoleOutputCJKSmall(consoleHandle, codePage,
new Coordinates(readRegion.Left, readRegion.Top),
atContents,
ref contents);
if (!result)
{
// When WriteConsoleOutput fails, half bufferLimit
if (bufferLimit < 2)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "ReadConsoleOutput",
ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleOutputExceptionTemplate);
throw e;
}
else
{
// if cols == colsRemaining, nothing is guaranteed read in this pass and
// the unread area is still rectangular
bufferLimit /= 2;
if (cols == colsRemaining)
{
bufferSize.Y = 0;
break;
}
else
{
// some areas have been read. This could only happen when the number of columns
// to write is larger than bufferLimit. In that case, the algorithm reads one row
// at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged
// to retry with a smaller bufferSize.X.
Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}"));
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
continue;
}
}
}
colsRemaining -= bufferSize.X;
readRegion.Left += bufferSize.X;
if (colsRemaining > 0 && (bufferSize.Y == 1) &&
(contents[atContents.Bottom, atContents.Right].Character == ' '))
{
colsRemaining++;
readRegion.Left--;
}
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
} // column iteration
rowsRemaining -= bufferSize.Y;
readRegion.Top += bufferSize.Y;
} // row iteration
// The following nested loop set the value of the empty cells in contents:
// character to ' '
// foreground color to console's foreground color
// background color to console's background color
int rowIndex = contents.GetLowerBound(0);
int rowEnd = contents.GetUpperBound(0);
int colBegin = contents.GetLowerBound(1);
int colEnd = contents.GetUpperBound(1);
CONSOLE_SCREEN_BUFFER_INFO bufferInfo =
GetConsoleScreenBufferInfo(consoleHandle);
ConsoleColor foreground = 0;
ConsoleColor background = 0;
WORDToColor(
bufferInfo.Attributes,
out foreground,
out background
);
while (rowIndex <= rowEnd)
{
int colIndex = colBegin;
while (true)
{
// if contents[rowIndex,colIndex] is in contentsRegion, hence a non-empty cell,
// move colIndex to one past the right end of contentsRegion
if (contentsRegion.Top <= rowIndex && rowIndex <= contentsRegion.Bottom &&
contentsRegion.Left <= colIndex && colIndex <= contentsRegion.Right)
{
colIndex = contentsRegion.Right + 1;
}
// colIndex past contents last column
if (colIndex > colEnd)
{
break;
}
contents[rowIndex, colIndex] = new BufferCell(
' ', foreground, background, BufferCellType.Complete);
colIndex++;
}
rowIndex++;
}
}
#endregion ReadConsoleOutput CJK
private static void ReadConsoleOutputPlain
(
ConsoleHandle consoleHandle,
Coordinates origin,
Rectangle contentsRegion,
ref BufferCell[,] contents
)
{
int rows = contentsRegion.Bottom - contentsRegion.Top + 1;
int cols = contentsRegion.Right - contentsRegion.Left + 1;
if ((rows <= 0) || cols <= 0)
{
tracer.WriteLine("invalid contents region");
return;
}
int bufferLimit = 2 * 1024; // Limit is 8K bytes as each CHAR_INFO takes 4 bytes
COORD bufferCoord;
bufferCoord.X = 0;
bufferCoord.Y = 0;
// keeps track of which screen area read
SMALL_RECT readRegion;
readRegion.Top = (short)origin.Y;
int rowsRemaining = rows;
while (rowsRemaining > 0)
{
// Iteration of columns is nested inside iteration of rows.
// If the size of contents exceeds the buffer limit, reading is
// done in blocks of size equal to the bufferlimit from left to right
// then top to bottom.
// For each iteration of rows,
// - readRegion.Left and bufferSize.X are reset
// - rowsRemaining, readRegion.Top, readRegion.Bottom, and bufferSize.Y
// are updated
// For each iteration of columns,
// - readRegion.Left, readRegion.Right and bufferSize.X are updated
readRegion.Left = (short)origin.X;
COORD bufferSize;
bufferSize.X = (short)Math.Min(cols, bufferLimit);
bufferSize.Y = (short)Math.Min
(
rowsRemaining,
bufferLimit / bufferSize.X
);
readRegion.Bottom = (short)(readRegion.Top + bufferSize.Y - 1);
// atContentsRow is at which row of contents a particular iteration is operating
int atContentsRow = rows - rowsRemaining + contentsRegion.Top;
// number of columns yet to be read
int colsRemaining = cols;
while (colsRemaining > 0)
{
readRegion.Right = (short)(readRegion.Left + bufferSize.X - 1);
// Now readRegion and bufferSize are updated.
// Call NativeMethods.ReadConsoleOutput
CHAR_INFO[] characterBuffer = new CHAR_INFO[bufferSize.Y * bufferSize.X];
bool result = NativeMethods.ReadConsoleOutput(
consoleHandle.DangerousGetHandle(),
characterBuffer,
bufferSize,
bufferCoord,
ref readRegion);
if (!result)
{
// When WriteConsoleOutput fails, half bufferLimit
if (bufferLimit < 2)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "ReadConsoleOutput",
ErrorCategory.ReadError, ConsoleControlStrings.ReadConsoleOutputExceptionTemplate);
throw e;
}
// if cols == colsRemaining, nothing is guaranteed read in this pass and
// the unread area is still rectangular
bufferLimit /= 2;
if (cols == colsRemaining)
{
bufferSize.Y = 0;
break;
}
else
{
// some areas have been read. This could only happen when the number of columns
// to write is larger than bufferLimit. In that case, the algorithm reads one row
// at a time => bufferSize.Y == 1. Then, we can safely leave bufferSize.Y unchanged
// to retry with a smaller bufferSize.X.
Dbg.Assert(bufferSize.Y == 1, string.Create(CultureInfo.InvariantCulture, $"bufferSize.Y should be 1, but is {bufferSize.Y}"));
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
continue;
}
}
// atContentsCol is at which column of contents a particular iteration is operating
int atContentsCol = cols - colsRemaining + contentsRegion.Left;
// copy characterBuffer to contents;
int characterBufferIndex = 0;
for (int r = atContentsRow; r < bufferSize.Y + atContentsRow; r++)
{
for (int c = atContentsCol; c < bufferSize.X + atContentsCol; c++, characterBufferIndex++)
{
contents[r, c].Character = (char)characterBuffer[characterBufferIndex].UnicodeChar;
ConsoleColor fgColor, bgColor;
WORDToColor(characterBuffer[characterBufferIndex].Attributes,
out fgColor,
out bgColor);
contents[r, c].ForegroundColor = fgColor;
contents[r, c].BackgroundColor = bgColor;
}
}
colsRemaining -= bufferSize.X;
readRegion.Left += bufferSize.X;
bufferSize.X = (short)Math.Min(colsRemaining, bufferLimit);
} // column iteration
rowsRemaining -= bufferSize.Y;
readRegion.Top += bufferSize.Y;
} // row iteration
// The following nested loop set the value of the empty cells in contents:
// character to ' '
// foreground color to console's foreground color
// background color to console's background color
int rowIndex = contents.GetLowerBound(0);
int rowEnd = contents.GetUpperBound(0);
int colBegin = contents.GetLowerBound(1);
int colEnd = contents.GetUpperBound(1);
CONSOLE_SCREEN_BUFFER_INFO bufferInfo =
GetConsoleScreenBufferInfo(consoleHandle);
ConsoleColor foreground = 0;
ConsoleColor background = 0;
WORDToColor(
bufferInfo.Attributes,
out foreground,
out background
);
while (rowIndex <= rowEnd)
{
int colIndex = colBegin;
while (true)
{
// if contents[rowIndex,colIndex] is in contentsRegion, hence a non-empty cell,
// move colIndex to one past the right end of contentsRegion
if (contentsRegion.Top <= rowIndex && rowIndex <= contentsRegion.Bottom &&
contentsRegion.Left <= colIndex && colIndex <= contentsRegion.Right)
{
colIndex = contentsRegion.Right + 1;
}
// colIndex past contents last column
if (colIndex > colEnd)
{
break;
}
contents[rowIndex, colIndex].Character = ' ';
contents[rowIndex, colIndex].ForegroundColor = foreground;
contents[rowIndex, colIndex].BackgroundColor = background;
colIndex++;
}
rowIndex++;
}
}
/// <summary>
/// Wraps Win32 FillConsoleOutputCharacter.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where output is filled
/// </param>
/// <param name="character">
/// character to fill the console output
/// </param>
/// <param name="numberToWrite">
/// number of times to write character
/// </param>
/// <param name="origin">
/// location on screen buffer where writing starts
/// </param>
/// <exception cref="HostException">
/// If Win32's FillConsoleOutputCharacter fails
/// </exception>
internal static void FillConsoleOutputCharacter
(
ConsoleHandle consoleHandle,
char character,
int numberToWrite,
Coordinates origin
)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
COORD c;
c.X = (short)origin.X;
c.Y = (short)origin.Y;
bool result =
NativeMethods.FillConsoleOutputCharacter(
consoleHandle.DangerousGetHandle(),
character,
(DWORD)numberToWrite,
c,
out _);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "FillConsoleOutputCharacter",
ErrorCategory.WriteError, ConsoleControlStrings.FillConsoleOutputCharacterExceptionTemplate);
throw e;
}
// we don't assert that the number actually written matches the number we asked for, as the function may clip if
// the number of cells to write extends past the end of the screen buffer.
}
/// <summary>
/// Wraps Win32 FillConsoleOutputAttribute.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where output is filled
/// </param>
/// <param name="attribute">
/// attribute to fill the console output
/// </param>
/// <param name="numberToWrite">
/// number of times to write attribute
/// </param>
/// <param name="origin">
/// location on screen buffer where writing starts
/// </param>
/// <exception cref="HostException">
/// If Win32's FillConsoleOutputAttribute fails
/// </exception>
internal static void FillConsoleOutputAttribute
(
ConsoleHandle consoleHandle,
WORD attribute,
int numberToWrite,
Coordinates origin
)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
COORD c;
c.X = (short)origin.X;
c.Y = (short)origin.Y;
bool result =
NativeMethods.FillConsoleOutputAttribute(
consoleHandle.DangerousGetHandle(),
attribute,
(DWORD)numberToWrite,
c,
out _);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "FillConsoleOutputAttribute",
ErrorCategory.WriteError, ConsoleControlStrings.FillConsoleOutputAttributeExceptionTemplate);
throw e;
}
}
/// <summary>
/// Wrap Win32 ScrollConsoleScreenBuffer.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where screen buffer is scrolled
/// </param>
/// <param name="scrollRectangle">
/// area to be scrolled
/// </param>
/// <param name="clipRectangle">
/// area to be updated after scrolling
/// </param>
/// <param name="destOrigin">
/// location to which the top left corner of scrollRectangle move
/// </param>
/// <param name="fill">
/// character and attribute to fill the area vacated by the scroll
/// </param>
/// <exception cref="HostException">
/// If Win32's ScrollConsoleScreenBuffer fails
/// </exception>
internal static void ScrollConsoleScreenBuffer
(
ConsoleHandle consoleHandle,
SMALL_RECT scrollRectangle,
SMALL_RECT clipRectangle,
COORD destOrigin, CHAR_INFO fill
)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
bool result =
NativeMethods.ScrollConsoleScreenBuffer(
consoleHandle.DangerousGetHandle(),
ref scrollRectangle,
ref clipRectangle,
destOrigin,
ref fill);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "ScrollConsoleScreenBuffer",
ErrorCategory.WriteError, ConsoleControlStrings.ScrollConsoleScreenBufferExceptionTemplate);
throw e;
}
}
#endregion Buffer
#region Window
/// <summary>
/// Wraps Win32 SetConsoleWindowInfo.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where window info is set
/// </param>
/// <param name="absolute">
/// If this parameter is TRUE, the coordinates specify the new upper-left and
/// lower-right corners of the window. If it is false, the coordinates are offsets
/// to the current window-corner coordinates
/// </param>
/// <param name="windowInfo">
/// specify the size and position of the console screen buffer's window
/// </param>
/// <exception cref="HostException">
/// If Win32's SetConsoleWindowInfo fails
/// </exception>
internal static void SetConsoleWindowInfo(ConsoleHandle consoleHandle, bool absolute, SMALL_RECT windowInfo)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
bool result = NativeMethods.SetConsoleWindowInfo(consoleHandle.DangerousGetHandle(), absolute, ref windowInfo);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "SetConsoleWindowInfo",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleWindowInfoExceptionTemplate);
throw e;
}
}
/// <summary>
/// Wraps Win32 GetLargestConsoleWindowSize.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console for which the largest window size is obtained
/// </param>
/// <returns>
/// the largest window size
/// </returns>
/// <exception cref="HostException">
/// If Win32's GetLargestConsoleWindowSize fails
/// </exception>
internal static Size GetLargestConsoleWindowSize(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
COORD result = NativeMethods.GetLargestConsoleWindowSize(consoleHandle.DangerousGetHandle());
if ((result.X == 0) && (result.Y == 0))
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "GetLargestConsoleWindowSize",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetLargestConsoleWindowSizeExceptionTemplate);
throw e;
}
return new Size(result.X, result.Y);
}
/// <summary>
/// Wraps Win32 GetConsoleTitle. 1K is the safe limit experimentally. The 64K limit
/// found in the docs is disregarded because it is essentially meaningless.
/// </summary>
/// <returns>
/// a string for the title of the window
/// </returns>
/// <exception cref="HostException">
/// If Win32's GetConsoleTitle fails
/// </exception>
internal static string GetConsoleWindowTitle()
{
const int MaxWindowTitleLength = 1024;
const DWORD bufferSize = MaxWindowTitleLength;
DWORD result;
StringBuilder consoleTitle = new StringBuilder((int)bufferSize);
result = NativeMethods.GetConsoleTitle(consoleTitle, bufferSize);
// If the result is zero, it may mean and error but it may also mean
// that the window title has been set to null. Since we can't tell the
// the difference, we'll just return the empty string every time.
if (result == 0)
{
return string.Empty;
}
return consoleTitle.ToString();
}
private static bool s_dontsetConsoleWindowTitle;
/// <summary>
/// Wraps Win32 SetConsoleTitle.
/// </summary>
/// <param name="consoleTitle">
/// a string for the title of the window
/// </param>
/// <exception cref="HostException">
/// If Win32's SetConsoleTitle fails
/// </exception>
internal static void SetConsoleWindowTitle(string consoleTitle)
{
if (s_dontsetConsoleWindowTitle)
{
return;
}
bool result = NativeMethods.SetConsoleTitle(consoleTitle);
if (!result)
{
int err = Marshal.GetLastWin32Error();
// ERROR_GEN_FAILURE is returned if this api can't be used with the terminal
if (err == 0x1f)
{
tracer.WriteLine("Call to SetConsoleTitle failed: {0}", err);
s_dontsetConsoleWindowTitle = true;
// We ignore this specific error as the console can still continue to operate
return;
}
HostException e = CreateHostException(err, "SetConsoleWindowTitle",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleWindowTitleExceptionTemplate);
throw e;
}
}
#endregion Window
/// <summary>
/// Wrap Win32 WriteConsole.
/// </summary>
/// <param name="consoleHandle">
/// Handle for the console where the string is written.
/// </param>
/// <param name="output">
/// String that is written.
/// </param>
/// <param name="newLine">
/// New line is written.
/// </param>
/// <exception cref="HostException">
/// If the Win32's WriteConsole fails.
/// </exception>
internal static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan<char> output, bool newLine)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
if (output.Length == 0)
{
if (newLine)
{
WriteConsole(consoleHandle, Environment.NewLine);
}
return;
}
// Native WriteConsole doesn't support output buffer longer than 64K, so we need to chop the output string if it is too long.
// This records the chopping position in output string.
int cursor = 0;
// This is 64K/4 - 1 to account for possible width of each character.
const int MaxBufferSize = 16383;
const int MaxStackAllocSize = 512;
ReadOnlySpan<char> outBuffer;
// In case that a new line is required, we try to write out the last chunk and the new-line string together,
// to avoid one extra call to 'WriteConsole' just for a new line string.
while (cursor + MaxBufferSize < output.Length)
{
outBuffer = output.Slice(cursor, MaxBufferSize);
cursor += MaxBufferSize;
WriteConsole(consoleHandle, outBuffer);
}
outBuffer = output.Slice(cursor);
if (!newLine)
{
WriteConsole(consoleHandle, outBuffer);
return;
}
char[] rentedArray = null;
string lineEnding = Environment.NewLine;
int size = outBuffer.Length + lineEnding.Length;
// We expect the 'size' will often be small, and thus optimize that case with 'stackalloc'.
Span<char> buffer = size <= MaxStackAllocSize ? stackalloc char[size] : default;
try
{
if (buffer.IsEmpty)
{
rentedArray = ArrayPool<char>.Shared.Rent(size);
buffer = rentedArray.AsSpan().Slice(0, size);
}
outBuffer.CopyTo(buffer);
lineEnding.CopyTo(buffer.Slice(outBuffer.Length));
WriteConsole(consoleHandle, buffer);
}
finally
{
if (rentedArray is not null)
{
ArrayPool<char>.Shared.Return(rentedArray);
}
}
}
private static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan<char> buffer)
{
DWORD charsWritten;
bool result =
NativeMethods.WriteConsole(
consoleHandle.DangerousGetHandle(),
buffer,
(DWORD)buffer.Length,
out charsWritten,
IntPtr.Zero);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(
err,
"WriteConsole",
ErrorCategory.WriteError,
ConsoleControlStrings.WriteConsoleExceptionTemplate);
throw e;
}
}
/// <summary>
/// Wraps Win32 SetConsoleTextAttribute.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where text attribute is set
/// </param>
/// <param name="attribute">
/// text attribute to set the console
/// </param>
/// <exception cref="HostException">
/// if the Win32's SetConsoleTextAttribute fails
/// </exception>
internal static void SetConsoleTextAttribute(ConsoleHandle consoleHandle, WORD attribute)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
bool result = NativeMethods.SetConsoleTextAttribute(consoleHandle.DangerousGetHandle(), attribute);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "SetConsoleTextAttribute",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleTextAttributeExceptionTemplate);
throw e;
}
}
#endif
#region Dealing with CJK
// Return the length of a VT100 control sequence character in str starting
// at the given offset.
//
// This code only handles the following formatting sequences, corresponding to
// the patterns:
// CSI params? 'm' // SGR: Select Graphics Rendition
// CSI params? '#' [{}pq] // XTPUSHSGR ('{'), XTPOPSGR ('}'), or their aliases ('p' and 'q')
//
// Where:
// params: digit+ ((';' | ':') params)?
// CSI: C0_CSI | C1_CSI
// C0_CSI: \x001b '[' // ESC '['
// C1_CSI: \x009b
//
// There are many other VT100 escape sequences, but these text attribute sequences
// (color-related, underline, etc.) are sufficient for our formatting system. We
// won't handle cursor movements or other attempts at animation.
//
// Note that offset is adjusted past the escape sequence, or at least one
// character forward if there is no escape sequence at the specified position.
internal static int ControlSequenceLength(string str, ref int offset)
{
var start = offset;
// First, check for the CSI:
if ((str[offset] == (char)0x1b) && (str.Length > (offset + 1)) && (str[offset + 1] == '['))
{
// C0 CSI
offset += 2;
}
else if (str[offset] == (char)0x9b)
{
// C1 CSI
offset += 1;
}
else
{
// No CSI at the current location, so we are done looking, but we still
// need to advance offset.
offset += 1;
return 0;
}
if (offset >= str.Length)
{
return 0;
}
// Next, handle possible numeric arguments:
char c;
do
{
c = str[offset++];
}
while ((offset < str.Length) && (char.IsDigit(c) || (c == ';') || (c == ':')));
// Finally, handle the command characters for the specific sequences we
// handle:
if (c == 'm')
{
// SGR: Select Graphics Rendition
return offset - start;
}
// Maybe XTPUSHSGR or XTPOPSGR, but we need to read another char. Offset is
// already positioned on the next char (or past the end).
if (offset >= str.Length)
{
return 0;
}
if (c == '#')
{
// '{' : XTPUSHSGR
// '}' : XTPOPSGR
// 'p' : alias for XTPUSHSGR
// 'q' : alias for XTPOPSGR
c = str[offset++];
if ((c == '{') ||
(c == '}') ||
(c == 'p') ||
(c == 'q'))
{
return offset - start;
}
}
return 0;
}
/// <summary>
/// From IsConsoleFullWidth in \windows\core\ntcon\server\dbcs.c.
/// </summary>
/// <returns></returns>
[SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults",
MessageId = "Microsoft.PowerShell.ConsoleControl+NativeMethods.ReleaseDC(System.IntPtr,System.IntPtr)")]
internal static int LengthInBufferCells(string str, int offset, bool checkEscapeSequences)
{
Dbg.Assert(offset >= 0, "offset >= 0");
Dbg.Assert(string.IsNullOrEmpty(str) || (offset < str.Length), "offset < str.Length");
var escapeSequenceAdjustment = 0;
if (checkEscapeSequences)
{
int i = 0;
while (i < offset)
{
ControlSequenceLength(str, ref i);
}
// If offset != i, we're in the middle of a sequence, which the caller should avoid,
// but we'll tolerate.
while (i < str.Length)
{
escapeSequenceAdjustment += ControlSequenceLength(str, ref i);
}
}
int length = 0;
foreach (char c in str)
{
length += LengthInBufferCells(c);
}
return length - offset - escapeSequenceAdjustment;
}
internal static int LengthInBufferCells(char c)
{
// The following is based on http://www.cl.cam.ac.uk/~mgk25/c/wcwidth.c
// which is derived from https://www.unicode.org/Public/UCD/latest/ucd/EastAsianWidth.txt
bool isWide = c >= 0x1100 &&
(c <= 0x115f || /* Hangul Jamo init. consonants */
c == 0x2329 || c == 0x232a ||
((uint)(c - 0x2e80) <= (0xa4cf - 0x2e80) &&
c != 0x303f) || /* CJK ... Yi */
((uint)(c - 0xac00) <= (0xd7a3 - 0xac00)) || /* Hangul Syllables */
((uint)(c - 0xf900) <= (0xfaff - 0xf900)) || /* CJK Compatibility Ideographs */
((uint)(c - 0xfe10) <= (0xfe19 - 0xfe10)) || /* Vertical forms */
((uint)(c - 0xfe30) <= (0xfe6f - 0xfe30)) || /* CJK Compatibility Forms */
((uint)(c - 0xff00) <= (0xff60 - 0xff00)) || /* Fullwidth Forms */
((uint)(c - 0xffe0) <= (0xffe6 - 0xffe0)));
// We can ignore these ranges because .Net strings use surrogate pairs
// for this range and we do not handle surrogate pairs.
// (c >= 0x20000 && c <= 0x2fffd) ||
// (c >= 0x30000 && c <= 0x3fffd)
return 1 + (isWide ? 1 : 0);
}
#if !UNIX
/// <summary>
/// Check if the output buffer code page is Japanese, Simplified Chinese, Korean, or Traditional Chinese.
/// </summary>
/// <param name="codePage"></param>
/// <returns></returns>
internal static bool IsCJKOutputCodePage(out uint codePage)
{
codePage = NativeMethods.GetConsoleOutputCP();
return codePage == 932 || // Japanese
codePage == 936 || // Simplified Chinese
codePage == 949 || // Korean
codePage == 950; // Traditional Chinese
}
#endif
#endregion Dealing with CJK
#if !UNIX
#region Cursor
/// <summary>
/// Wraps Win32 GetConsoleCursorInfo.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where cursor info is obtained
/// </param>
/// <returns>
/// cursor info
/// </returns>
/// <exception cref="HostException">
/// If Win32's GetConsoleCursorInfo fails
/// </exception>
internal static CONSOLE_CURSOR_INFO GetConsoleCursorInfo(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
CONSOLE_CURSOR_INFO cursorInfo;
bool result = NativeMethods.GetConsoleCursorInfo(consoleHandle.DangerousGetHandle(), out cursorInfo);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "GetConsoleCursorInfo",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetConsoleCursorInfoExceptionTemplate);
throw e;
}
return cursorInfo;
}
internal static CONSOLE_FONT_INFO_EX GetConsoleFontInfo(ConsoleHandle consoleHandle)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
CONSOLE_FONT_INFO_EX fontInfo = new CONSOLE_FONT_INFO_EX();
fontInfo.cbSize = Marshal.SizeOf(fontInfo);
bool result = NativeMethods.GetCurrentConsoleFontEx(consoleHandle.DangerousGetHandle(), false, ref fontInfo);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "GetConsoleFontInfo",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetConsoleFontInfoExceptionTemplate);
throw e;
}
return fontInfo;
}
/// <summary>
/// Wraps Win32 SetConsoleCursorInfo.
/// </summary>
/// <param name="consoleHandle">
/// handle for the console where cursor info is set
/// </param>
/// <param name="cursorInfo">
/// cursor info to set the cursor
/// </param>
/// <exception cref="HostException">
/// If Win32's SetConsoleCursorInfo fails
/// </exception>
internal static void SetConsoleCursorInfo(ConsoleHandle consoleHandle, CONSOLE_CURSOR_INFO cursorInfo)
{
Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid");
Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed");
bool result = NativeMethods.SetConsoleCursorInfo(consoleHandle.DangerousGetHandle(), ref cursorInfo);
if (!result)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "SetConsoleCursorInfo",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleCursorInfoExceptionTemplate);
throw e;
}
}
#endregion Cursor
#region helper
/// <summary>
/// Helper function to create the proper HostException.
/// </summary>
/// <param name="win32Error"></param>
/// <param name="errorId"></param>
/// <param name="category"></param>
/// <param name="resourceStr"></param>
/// <returns></returns>
private static HostException CreateHostException(
int win32Error, string errorId, ErrorCategory category, string resourceStr)
{
Win32Exception innerException = new Win32Exception(win32Error);
string msg = StringUtil.Format(resourceStr, innerException.Message, win32Error);
HostException e = new HostException(msg, innerException, errorId, category);
return e;
}
#endregion helper
#region SendInput
internal static void MimicKeyPress(INPUT[] inputs)
{
Dbg.Assert(inputs != null && inputs.Length > 0, "inputs should not be null or empty");
var numberOfSuccessfulEvents = NativeMethods.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf<INPUT>());
if (numberOfSuccessfulEvents == 0)
{
int err = Marshal.GetLastWin32Error();
HostException e = CreateHostException(err, "SendKeyPressInput",
ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SendKeyPressInputExceptionTemplate);
throw e;
}
}
#endregion SendInput
/// <summary>
/// Class to hold the Native Methods used in this file enclosing class.
/// </summary>
internal static class NativeMethods
{
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h
internal const int FontTypeMask = 0x06;
internal const int TrueTypeFont = 0x04;
#region CreateFile
[Flags]
internal enum AccessQualifiers : uint
{
// From winnt.h
GenericRead = 0x80000000,
GenericWrite = 0x40000000
}
[Flags]
internal enum ShareModes : uint
{
// From winnt.h
ShareRead = 0x00000001,
ShareWrite = 0x00000002
}
internal enum CreationDisposition : uint
{
// From winbase.h
CreateNew = 1,
CreateAlways = 2,
OpenExisting = 3,
OpenAlways = 4,
TruncateExisting = 5
}
[DllImport(PinvokeDllNames.CreateFileDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern NakedWin32Handle CreateFile
(
string fileName,
DWORD desiredAccess,
DWORD ShareModes,
IntPtr securityAttributes,
DWORD creationDisposition,
DWORD flagsAndAttributes,
NakedWin32Handle templateFileWin32Handle
);
#endregion CreateFile
#region Code Page
[DllImport(PinvokeDllNames.GetConsoleOutputCPDllName, SetLastError = false, CharSet = CharSet.Unicode)]
internal static extern uint GetConsoleOutputCP();
#endregion Code Page
[DllImport(PinvokeDllNames.GetConsoleWindowDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern HWND GetConsoleWindow();
[DllImport(PinvokeDllNames.GetDCDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern HDC GetDC(HWND hwnd);
[DllImport(PinvokeDllNames.ReleaseDCDllName, SetLastError = false, CharSet = CharSet.Unicode)]
internal static extern int ReleaseDC(HWND hwnd, HDC hdc);
[DllImport(PinvokeDllNames.FlushConsoleInputBufferDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FlushConsoleInputBuffer(NakedWin32Handle consoleInput);
[DllImport(PinvokeDllNames.FillConsoleOutputAttributeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FillConsoleOutputAttribute
(
NakedWin32Handle consoleOutput,
WORD attribute,
DWORD length,
COORD writeCoord,
out DWORD numberOfAttrsWritten
);
[DllImport(PinvokeDllNames.FillConsoleOutputCharacterDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool FillConsoleOutputCharacter
(
NakedWin32Handle consoleOutput,
char character,
DWORD length,
COORD writeCoord,
out DWORD numberOfCharsWritten
);
[DllImport(PinvokeDllNames.WriteConsoleDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern unsafe bool WriteConsole
(
NakedWin32Handle consoleOutput,
char* buffer,
DWORD numberOfCharsToWrite,
out DWORD numberOfCharsWritten,
IntPtr reserved
);
internal static unsafe bool WriteConsole
(
NakedWin32Handle consoleOutput,
ReadOnlySpan<char> buffer,
DWORD numberOfCharsToWrite,
out DWORD numberOfCharsWritten,
IntPtr reserved
)
{
fixed (char* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
return WriteConsole(consoleOutput, bufferPtr, numberOfCharsToWrite, out numberOfCharsWritten, reserved);
}
}
[DllImport(PinvokeDllNames.GetConsoleTitleDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern DWORD GetConsoleTitle(StringBuilder consoleTitle, DWORD size);
[DllImport(PinvokeDllNames.SetConsoleTitleDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetConsoleTitle(string consoleTitle);
[DllImport(PinvokeDllNames.GetConsoleModeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetConsoleMode(NakedWin32Handle consoleHandle, out UInt32 mode);
[DllImport(PinvokeDllNames.GetConsoleScreenBufferInfoDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetConsoleScreenBufferInfo(NakedWin32Handle consoleHandle, out CONSOLE_SCREEN_BUFFER_INFO consoleScreenBufferInfo);
[DllImport(PinvokeDllNames.GetLargestConsoleWindowSizeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern COORD GetLargestConsoleWindowSize(NakedWin32Handle consoleOutput);
[DllImport(PinvokeDllNames.ReadConsoleDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern unsafe bool ReadConsole
(
NakedWin32Handle consoleInput,
char* lpBuffer,
DWORD numberOfCharsToRead,
out DWORD numberOfCharsRead,
ref CONSOLE_READCONSOLE_CONTROL controlData
);
internal static unsafe bool ReadConsole
(
NakedWin32Handle consoleInput,
Span<char> buffer,
DWORD numberOfCharsToRead,
out DWORD numberOfCharsRead,
ref CONSOLE_READCONSOLE_CONTROL controlData
)
{
fixed (char* bufferPtr = &MemoryMarshal.GetReference(buffer))
{
return ReadConsole(consoleInput, bufferPtr, numberOfCharsToRead, out numberOfCharsRead, ref controlData);
}
}
[DllImport(PinvokeDllNames.PeekConsoleInputDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool PeekConsoleInput
(
NakedWin32Handle consoleInput,
[Out] INPUT_RECORD[] buffer,
DWORD length,
out DWORD numberOfEventsRead
);
[DllImport(PinvokeDllNames.GetNumberOfConsoleInputEventsDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNumberOfConsoleInputEvents(NakedWin32Handle consoleInput, out DWORD numberOfEvents);
[DllImport(PinvokeDllNames.SetConsoleCtrlHandlerDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetConsoleCtrlHandler(BreakHandler handlerRoutine, bool add);
[DllImport(PinvokeDllNames.SetConsoleModeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetConsoleMode(NakedWin32Handle consoleHandle, DWORD mode);
[DllImport(PinvokeDllNames.SetConsoleScreenBufferSizeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetConsoleScreenBufferSize(NakedWin32Handle consoleOutput, COORD size);
[DllImport(PinvokeDllNames.SetConsoleTextAttributeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetConsoleTextAttribute(NakedWin32Handle consoleOutput, WORD attributes);
[DllImport(PinvokeDllNames.SetConsoleWindowInfoDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetConsoleWindowInfo(NakedWin32Handle consoleHandle, bool absolute, ref SMALL_RECT windowInfo);
[DllImport(PinvokeDllNames.WriteConsoleOutputDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WriteConsoleOutput
(
NakedWin32Handle consoleOutput,
CHAR_INFO[] buffer,
COORD bufferSize,
COORD bufferCoord,
ref SMALL_RECT writeRegion
);
[DllImport(PinvokeDllNames.ReadConsoleOutputDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ReadConsoleOutput
(
NakedWin32Handle consoleOutput,
[Out] CHAR_INFO[] buffer,
COORD bufferSize,
COORD bufferCoord,
ref SMALL_RECT readRegion
);
[DllImport(PinvokeDllNames.ScrollConsoleScreenBufferDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ScrollConsoleScreenBuffer
(
NakedWin32Handle consoleOutput,
ref SMALL_RECT scrollRectangle,
ref SMALL_RECT clipRectangle,
COORD destinationOrigin,
ref CHAR_INFO fill
);
[DllImport(PinvokeDllNames.SendInputDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern UInt32 SendInput(UInt32 inputNumbers, INPUT[] inputs, int sizeOfInput);
// There is no GetCurrentConsoleFontEx on Core
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetCurrentConsoleFontEx(NakedWin32Handle consoleOutput, bool bMaximumWindow, ref CONSOLE_FONT_INFO_EX consoleFontInfo);
[DllImport(PinvokeDllNames.GetConsoleCursorInfoDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetConsoleCursorInfo(NakedWin32Handle consoleOutput, out CONSOLE_CURSOR_INFO consoleCursorInfo);
[DllImport(PinvokeDllNames.SetConsoleCursorInfoDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetConsoleCursorInfo(NakedWin32Handle consoleOutput, ref CONSOLE_CURSOR_INFO consoleCursorInfo);
[DllImport(PinvokeDllNames.ReadConsoleInputDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ReadConsoleInput
(
NakedWin32Handle consoleInput,
[Out] INPUT_RECORD[] buffer,
DWORD length,
out DWORD numberOfEventsRead
);
internal enum CHAR_INFO_Attributes : uint
{
COMMON_LVB_LEADING_BYTE = 0x0100,
COMMON_LVB_TRAILING_BYTE = 0x0200
}
}
[TraceSourceAttribute("ConsoleControl", "Console control methods")]
private static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleControl", "Console control methods");
#endif
}
}
|