PInvoke的。加速Console.Write();

时间:2015-02-08 19:53:44

标签: c# performance console-application pinvoke tetris

我正在写一个c#console tetris游戏。一旦我到达应用程序准备好的部分。我到了必须解决滞后的部分。我写的是这样的:

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

所以当一个新的块来/我想移动某些东西时:

writeCol(blokk, ConsoleColor.Magenta);

blokk在哪里:

private const string blokk = "█";

我找到了一种方法来#34;写"更快地到控制台:

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);
                }
            }
         }

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

(如果有人想的话,这是匈牙利人写的)

1 个答案:

答案 0 :(得分:1)

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

    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);

给出了这个结果:

enter image description here

因此,请记住先将缓冲区buf填入正确的位置,然后再调用WriteConsoleOutput将缓冲区复制到屏幕上。如果你经常打电话,你就会回到原点......

请注意,您无需编写整个屏幕。通过使用不同的矩形,您只能编写部分屏幕。

对于这个演示,我省略了所有错误检查。这取决于你检查。

您可能希望了解the msdn documentation

使用的原生调用