Mer*_*ham 22 .net pinvoke winapi console-application
如果我已经将我的程序设置为a Windows Application
,并使用了AttachConsole(-1)
API,那么如何Console.WriteLine
从我启动应用程序的控制台写入?它不适合我.
如果它是相关的,我使用的是Windows 7 x64,并且我启用了UAC.提升似乎并没有解决问题,也没有使用start /wait
.
更新
一些可能有用的其他背景:
我刚刚发现,如果我转到命令提示符并输入cmd /c MyProgram.exe
,那么控制台输出就可以了.如果我启动命令提示符,打开cmd.exe
子进程并从该子shell运行程序,情况也是如此.
我还尝试注销并重新登录,从开始菜单启动的cmd.exe(而不是右键单击 - >命令提示符)运行,并从console2实例运行.这些都不起作用.
背景
我已经阅读过其他网站和几个SO答案,我可以调用win32 API AttachConsole
将我的Windows应用程序绑定到运行我的程序的控制台,所以我可以拥有一个"控制台应用程序和Windows应用程序" .
例如,这个问题:是否可以在C#/ .Net中将消息记录到cmd.exe?.
我已经编写了一堆逻辑来完成这项工作(使用其他几个API),并且我已经让其他所有方案都可以工作(包括重定向,其他人声称这些方案不起作用).剩下的唯一方案是Console.WriteLine
写入我启动程序的控制台.从我读过的所有内容中,如果我使用它,它应该可以工作AttachConsole
.
摄制
这是一个最小的样本 - 请注意,项目设置为Windows Application
:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
class Program
{
[STAThread]
static void Main(string[] args)
{
if (!AttachConsole(-1))
{
MessageBox.Show(
new Win32Exception(Marshal.GetLastWin32Error())
.ToString()
);
}
Console.WriteLine("Test");
}
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
private static extern bool AttachConsole(int processId);
}
Run Code Online (Sandbox Code Playgroud)
AllocConsole
在我的真实应用程序中使用).如果我在调用Marshal.GetLastWin32Error
之后调用Console.WriteLine
,则会收到错误"System.ComponentModel.Win32Exception(0x80004005):句柄无效".我怀疑连接到控制台导致Console.Out
搞砸了,但我不确定如何解决它.
Che*_*eso 14
这就是我在Winforms中的表现.使用WPF会是类似的.
static class SybilProgram
{
[STAThread]
static void Main(string[] args)
{
if (args.Length > 0)
{
// Command line given, display console
if ( !AttachConsole(-1) ) // Attach to a parent process console
AllocConsole(); // Alloc a new console if none available
ConsoleMain(args);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1()); // instantiate the Form
}
}
private static void ConsoleMain(string[] args)
{
Console.WriteLine("Command line = {0}", Environment.CommandLine);
for (int ix = 0; ix < args.Length; ++ix)
Console.WriteLine("Argument{0} = {1}", ix + 1, args[ix]);
Console.ReadLine();
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int pid);
}
Run Code Online (Sandbox Code Playgroud)