Windows平台下Dart程序启动时隐藏控制台窗口的实现方法
在Windows平台用Dart实现启动时隐藏控制台窗口的方法
下面是几种实用的实现方式,根据你的需求选择:
1. 使用win32库调用Windows API直接隐藏窗口
通过Dart的win32库调用系统API,在程序启动后立即隐藏控制台窗口:
- 首先在
pubspec.yaml中添加依赖:dependencies: win32: ^5.0.0 - 编写代码:
这种方式会在程序启动后瞬间隐藏控制台,几乎不会出现弹窗。import 'package:win32/win32.dart'; import 'dart:io'; void main() { // 获取当前控制台窗口的句柄 final consoleHandle = GetConsoleWindow(); if (consoleHandle != 0) { // 调用ShowWindow隐藏窗口,SW_HIDE对应常量0 ShowWindow(consoleHandle, SW_HIDE); } // 这里放置你的后台业务逻辑 // 示例:持续输出日志到文件 final logFile = File('background.log'); while (true) { logFile.writeAsStringSync('${DateTime.now()}: 程序运行中\n', mode: FileMode.append); sleep(const Duration(seconds: 5)); } }
2. 编译为Windows GUI子系统程序
Dart默认编译的exe是控制台程序,通过指定编译参数可以直接生成无控制台的GUI程序:
- 编译命令:
dart compile exe -Dwindows-subsystem=gui your_dart_script.dart - 注意事项:编译后的程序没有控制台输出,所以如果需要日志,要将输出写入文件或其他存储介质,无法通过
print查看内容。
3. 用VBS脚本静默启动已编译的exe
如果不想修改代码或调整编译参数,可以通过VBS脚本实现静默启动:
- 创建一个
.vbs文件,写入以下内容:Set WshShell = CreateObject("WScript.Shell") WshShell.Run "path/to/your_compiled_program.exe", 0, False - 替换
path/to/your_compiled_program.exe为你的exe文件实际路径,运行这个VBS脚本即可在后台启动程序,不会显示控制台窗口。
内容的提问来源于stack exchange,提问作者MrRookoo
相关产品推荐
相关产品推荐

