Win32 API 控制台光标在 WriteConsole 后不移动

Win32 API console cursor not moving after WriteConsole

本文关键字:移动 WriteConsole API 控制台 光标 Win32      更新时间:2023-10-16

所以,当我尝试使用此代码从控制台读取 std::wstring 时

std::wstring string;
wchar_t c;
DWORD u;
do {
ReadConsole(GetStdHandle(STD_INPUT_HANDLE), &c, 1, &u, NULL);
} while (u && (c == L' ' || c == L'n'));
do {
string.append(1, c);
ReadConsole(GetStdHandle(STD_INPUT_HANDLE), &c, 1, &u, NULL);
} while (u && c != L' ' && c != L'n');
WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), string.data(), string.length(), &u, NULL);

写入字符串后,光标位置不会移动,因此如果我再次调用 WriteConsole((,它将写入刚刚写入的字符串上方。 有什么解决方案吗?

ReadConsole读取 stdin时,它会将rn附加到字符串中。您只排除了条件中的n"stringr"将被传递给WriteConsoler会将光标返回到行首。 请尝试以下代码:

#include <windows.h>
#include <iostream>
#include <string>
int main(int argc, char** argv)
{
std::wstring string;
wchar_t c;
DWORD u;
do {
ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), &c, 1, &u, NULL);
} while (u && (c == L' ' || c == L'n'));
do {
string.append(1, c);
ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE), &c, 1, &u, NULL);
} while (u && c != L' ' && c != L'n' && c != L'r');
WriteConsoleW(GetStdHandle(STD_OUTPUT_HANDLE), string.data(), string.length(), &u, NULL);
return 0;
}