如何解决将文本打印到屏幕中间
我想问有没有什么办法,以及如何将像 Windows 安装“我们正在为您设置”这样的文本打印到屏幕中间?如果可以的话,我能不能让它只显示文本,而文本背景应该是你的桌面。
解决方法
在 Windows 中处理控制台的经典方法是通过 Console API。要获得控制台大小,您可以使用 GetConsoleScreenBufferInfo()
。这是一个非常简单的例子,在屏幕中央绘制一个字符串
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cstdint>
#include <windows.h>
int main(void)
{
auto stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);
std::string str;
CONSOLE_SCREEN_BUFFER_INFO oldcsbi{};
COORD coord{};
while (1)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
GetConsoleScreenBufferInfo(stdout_handle,&csbi);
if (csbi.srWindow.Bottom != oldcsbi.srWindow.Bottom || csbi.srWindow.Right != oldcsbi.srWindow.Right)
{
std::fill(str.begin(),str.end(),' ');
SetConsoleCursorPosition(stdout_handle,coord);
std::cout << str; // clear the old text
oldcsbi = csbi;
std::ostringstream s;
s << "Console size: " << csbi.srWindow.Right << 'x' << csbi.srWindow.Bottom;
str = s.str();
coord.X = (short)((csbi.srWindow.Right - str.size()) / 2);
coord.Y = (short)(csbi.srWindow.Bottom/2);
SetConsoleCursorPosition(stdout_handle,coord);
std::cout << str; // draw the new text
}
Sleep(1000);
}
}
上面的代码会定期获取控制台的大小,如果大小发生了变化,则重新绘制屏幕。它无限循环,直到您按 Ctrl+C 或关闭程序
有关控制台 API 的更多信息,请参阅 Using the Console
当然,polling 这样的大小并不是很好,因为它使输出不是很流畅,而且还会占用 CPU 周期。真正的解决方案是监听调整大小事件并在回调函数中做必要的事情
有一种名为 ENABLE_WINDOW_INPUT
的模式,它将调整大小事件传递到控制台,您可以在控制台中通过阻塞 ReadConsoleInput()
或 PeekConsoleInput()
API 进行读取。您可以在 Reading Input Buffer Events 中看到一个示例。只需运行它并调整窗口大小,就会打印出调整大小事件
不幸的是,在该模式下,只有 console buffer size change event 通过 WINDOW_BUFFER_SIZE_RECORD
触发,并且没有控制台屏幕大小更改事件,因此如果您更改行数,那么大部分没有事件产生的时间。这意味着您需要转到较低级别并聆听名为 EVENT_CONSOLE_LAYOUT
的 Console Winevent:
HWINEVENTHOOK eventHook = SetWinEventHook(EVENT_CONSOLE_LAYOUT,EVENT_CONSOLE_LAYOUT,NULL,EventProc,WINEVENT_OUTOFCONTEXT);
...
MSG msg;
while (GetMessage(&msg,g_hWindow,EVENT_CONSOLE_LAYOUT)) {
DispatchMessage(&msg);
您可以在
中找到更多详细信息- How do I disable or detect mode changes in Windows Console?
- Can I prevent the user of my program to resize the console window? (in C)
更简单甚至更好的方法是使用 ncurses 并处理类似于 SIGWINCH
的内容。过去有许多用于 ncurses 的 Windows 端口,鉴于 Windows 10 控制台 supports ANSI sequences,编写 ncurses 端口更加容易。事实上,现在是 recommended 到 use ANSI sequences 用于终端交互,而不是用于可移植性的 ole Console API
- Is ncurses available for windows?
- NCurses-Like System for Windows
- Any Windows Substitutes For Curses/NCurses?
- Ncurses for Windows
<Window x:Class="YourApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="600" Width="800" WindowStyle="None" AllowsTransparency="True" Background="Transparent" Topmost="True">
<StackPanel>
<TextBlock Text="Your Text Here"/>
</StackPanel>
</Window>
请注意,这只会在其他应用程序声明自己为 TopMost 之前有效。 Window “on desktop”
的建议版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。