我试图让我的WinForm基于C#也与命令行进行合作,但我有困难得到它发挥不错。例如,我有这样的code:
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;
}
}
}