Mal*_*ist 2 .net c# console user-interface
我正在尝试让我的基于WinForm的C#与命令行合作,但是我很难让它发挥得很好.例如,我有这个代码:
[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.");
}
}
}
Run Code Online (Sandbox Code Playgroud)
它应该使用Console.WriteLine写入控制台,但我什么也看不见,只显示MessageBox.
我究竟做错了什么?
小智 5
尝试AttachConsole(-1)重定向Console.Out,为我工作:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)