我正在尝试让我的基于 WinForm 的 C# 也与命令行配合,但我很难让它发挥得很好.例如,我有这样的代码:
I'm trying to get my WinForm based C# to cooperate with the commandline too, but I'm having difficulty getting it to play nice. For example, I have this code:
[STAThread]
static void Main(string[] args) {
foreach (string s in args) {
System.Windows.Forms.MessageBox.Show(s);
Console.WriteLine("String: " + s);
}
Mutex appSingleton = new System.Threading.Mutex(false, "WinSyncSingalInstanceMutx");
if (appSingleton.WaitOne(0, false)) {
try {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//start logger
Logger.singleton.makeOpen(true);
Application.Run(new MainForm(false));
} catch (Exception) {
} finally {
appSingleton.Close();
Logger.singleton.makeOpen(false);
}
} else {
System.Windows.Forms.MessageBox.Show("Sorry, only one instance of WinSync can be ran at once.");
}
}
}
它应该使用 Console.WriteLine 写入控制台,但我什么也没看到,只有 MessageBox 出现.
It should write to the console with the Console.WriteLine, but I see nothing, only the MessageBox shows up.
我做错了什么?
尝试 AttachConsole(-1) 重定向 Console.Out,对我有用:
Try AttachConsole(-1) to redirect Console.Out, worked for me:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace PEFixer
{
static class Program
{
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
if (args.Length > 0)
{
AttachConsole(-1);
return Form1.doTransformCmdLine(args);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
return 0;
}
}
}
这篇关于在窗口化应用程序中写入命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!