Pinvoke。加速 Console.Write();

Pinvoke. Speed up Console.Write();

我正在编写一个 C# 控制台俄罗斯方块游戏。一旦我到达应用程序准备就绪的部分。我到了必须解决滞后问题的部分。我是这样写的:

static void writeCol(string a, ConsoleColor b)
        {
            ConsoleColor c = Console.ForegroundColor;
            Console.ForegroundColor = b;
            Console.Write(a);
            Console.ForegroundColor = c;
        }

所以当一个新块comes/i想要移动一些东西时:

writeCol(blokk, ConsoleColor.Magenta);

blokk 在哪里:

private const string blokk = "█";

我找到了一种方法 "write" 到控制台的速度更快:

using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;

namespace ConsoleApplication1
{
  class Program
  {

    [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern SafeFileHandle CreateFile(
        string fileName,
        [MarshalAs(UnmanagedType.U4)] uint fileAccess,
        [MarshalAs(UnmanagedType.U4)] uint fileShare,
        IntPtr securityAttributes,
        [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
        [MarshalAs(UnmanagedType.U4)] int flags,
        IntPtr template);

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool WriteConsoleOutput(
      SafeFileHandle hConsoleOutput, 
      CharInfo[] lpBuffer, 
      Coord dwBufferSize, 
      Coord dwBufferCoord, 
      ref SmallRect lpWriteRegion);

    [StructLayout(LayoutKind.Sequential)]
    public struct Coord
    {
      public short X;
      public short Y;

      public Coord(short X, short Y)
      {
        this.X = X;
        this.Y = Y;
      }
    };

    [StructLayout(LayoutKind.Explicit)]
    public struct CharUnion
    {
      [FieldOffset(0)] public char UnicodeChar;
      [FieldOffset(0)] public byte AsciiChar;
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct CharInfo
    {
      [FieldOffset(0)] public CharUnion Char;
      [FieldOffset(2)] public short Attributes;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct SmallRect
    {
      public short Left;
      public short Top;
      public short Right;
      public short Bottom;
    }


    [STAThread]
    static void Main(string[] args)
    {
      SafeFileHandle h = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);

      if (!h.IsInvalid)
      {
        CharInfo[] buf = new CharInfo[80 * 25];
        SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = 80, Bottom = 25 };

        for (byte character = 65; character < 65 + 26; ++character)
        {
          for (short attribute = 0; attribute < 15; ++attribute)
          {
            for (int i = 0; i < buf.Length; ++i)
            {
              buf[i].Attributes = attribute;
              buf[i].Char.AsciiChar = character;
            }

            bool b = WriteConsoleOutput(h, buf,
              new Coord() { X = 80, Y = 25 },
              new Coord() { X = 0, Y = 0 },
              ref rect);
          }
        }
      }
      Console.ReadKey();
    }
  }
}

(此代码打印出 A-Z 中的所有字符)。 所以最后的问题是: 我如何修改此代码以利用它?

提前致谢。祝你有个愉快的一天。

编辑: 我找到了一种方法,但它给了我错误的文字。有什么想法吗?

 public static void Writetocol(string s)
            {
               var kiir = s;
            byte[] barr;
            kiir = Convert.ToString(kiir);
            barr = Encoding.ASCII.GetBytes(kiir);
            SafeFileHandle h = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, FileMode.Open, 0, IntPtr.Zero);

            if (!h.IsInvalid)
            {
                CharInfo[] buf = new CharInfo[80 * 25];
                SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = 80, Bottom = 25 };
                for (short attribute = 0; attribute < 15; ++attribute)
                {
                    for (int i = 0; i < barr.Length; ++i)
                    {
                        buf[i].Attributes = attribute;
                        buf[i].Char.AsciiChar = barr[i];
                    }

                    bool b = WriteConsoleOutput(h, buf,
                      new Coord() { X = 80, Y = 25 },
                      new Coord() { X = 0, Y = 0 },
                      ref rect);
                }
            }
         }

它给了我这个: 什么时候应该给我这个:

(如果有人想知道,它是匈牙利语)

您可以通过处理您自己的换行符和位置来解析您提供的用于填充缓冲区的字符串,如下所示:

    static void writeCol(string a, ConsoleColor b)
    {
        byte x = 0, y = 0;
        // parsing to make it  fly
        // fill the buffer with the string 
        for(int ci=0; ci<a.Length;ci++)
        {
            switch (a[ci])
            {
                case '\n': // newline char, move to next line, aka y=y+1
                    y++;
                    break;
                case '\r': // carriage return, aka back to start of line
                    x = 0;
                    break;
                case ' ': // a space, move the cursor to the right
                    x++;
                    break;
                default:
                    // calculate where we should be in the buffer
                    int i = y * 80 + x;
                    // color
                    buf[i].Attributes= (short) b;
                    // put the current char from the string in the buffer
                    buf[i].Char.AsciiChar = (byte) a[ci];
                    x++;
                    break;
            }
        }
        // we handled our string, let's write the whole screen at once
        bool success = WriteConsoleOutput(h, buf,
                     new Coord() { X = 80, Y = 25 },
                     new Coord() { X = 0, Y = 0 },
                     ref rect);
    }

请注意,我已经将安全句柄 h 和本机缓冲区 buf 重构为静态,因此我们在应用程序中只有一次:

static IntPtr h= GetStdHandle(STD_OUTPUT_HANDLE); 
static CharInfo[] buf = new CharInfo[80 * 25];
static SmallRect rect = new SmallRect() { Left = 0, Top = 0, Right = 80, Bottom = 25 };

我添加了GetStdHandle

    //http://www.pinvoke.net/default.aspx/kernel32/GetStdHandle.html
    const int STD_OUTPUT_HANDLE = -11;
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern IntPtr GetStdHandle(int nStdHandle);

在这种情况下,您需要更改 WriteConsoleOutput 上的方法签名以接受 IntPtr 而不是 SafeFileHandle

我通过以下测试调用测试了此方法:

writeCol(@"

     TEST
     ======
     1 test

     FuBar", ConsoleColor.Blue);

结果如下:

所以请记住先在正确的位置填充缓冲区buf,然后立即调用WriteConsoleOutput将缓冲区复制到屏幕。如果你经常调用它,你就回到了原点...

请注意,您不需要书写整个屏幕。通过使用不同的矩形,您可以只写屏幕的一部分。

对于这个演示,我省略了所有错误检查。就看你的了。

您可能想阅读 the msdn documentation

中使用的本机调用