我正在尝试使用kernel32.dll
在控制台上编写符号(因为当写入最后一行的最后一个符号时,标准Console.Write
正在扩展控制台窗口)
问题是WriteConsoleOutput
返回0x06
女巫是INVALID_HANDLE_VALUE
。但是当我使用SetWindowText
时(即使用它,因为它使用窗口的句柄来设置文本)它改变了控制台标题。
我试图通过GetStdHandle(STD_OUTPUT_HANDLE)
,WriteConsoleOutput
处理,然后返回0x02女巫ERROR_FILE_NOT_FOUND
我做错了什么?如有任何帮助,我将不胜感激
这是进口:
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("kernel32.dll")]
static extern uint GetLastError();
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteConsoleOutput( IntPtr consoleHandle, CharInfo[,] buffer, Coord bufSize, Coord bufZero, ref Rect drawRect );
// This is for test
[DllImport("user32.dll")]
static extern bool SetWindowText(IntPtr hWnd, string text);
的Structs
[StructLayout(LayoutKind.Explicit)]
public struct CharInfo
{
[FieldOffset(0)]
internal char UnicodeChar;
[FieldOffset(0)]
internal char AsciiChar;
[FieldOffset(2)]
internal ushort Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct Coord
{
public short X; public short Y;
public Coord(short x, short y) { X = x; Y = y; }
};
[StructLayout(LayoutKind.Sequential)]
public struct Rect
{
public short Left;
public short Top;
public short Right;
public short Bottom;
}
我使用的代码
Console.Clear();
IntPtr h = GetConsoleWindow();
SetWindowText(h, "we have found console");
var rect = new Rect() { Left = 10, Top = 0, Right = 11, Bottom = 1 };
var bufsz = new Coord(2, 2);
var buf = new CharInfo[2, 2];
buf[0, 0] = new CharInfo() { AsciiChar = '+' };
var bufpos = new Coord(0, 0);
WriteConsoleOutput(h, buf, bufsz, bufpos, ref rect);
var err = GetLastError();
if (err != 0) Console.WriteLine("Write fail: " + err);
编辑:
没工作
Process.GetCurrentProcess().MainWindowHandle;
// same error
这也是
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nHandle);
...
IntPtr h = GetStdHandle(-11);
// Error 1400 - wrong handle while accessing from email (or something like that)