在winform /控制台混合应用程序行为控制台、应用程序、行为、winform

2023-09-03 05:41:56 作者:愿岁月可回头

我有,我想成为可作为一个控制台应用程序,如果某些参数传递给它一个WinForm项目。使用一些技巧,从我读到这里,我用下面的code,使这项工作。

  [System.Runtime.InteropServices.DllImport(KERNEL32.DLL)
私人静态外部布尔AllocConsole();

[System.Runtime.InteropServices.DllImport(KERNEL32.DLL)
私人静态外部布尔AttachConsole(INT PID);

...

如果(!AttachConsole(-1))
{
   AllocConsole();
}
 

这个工作,但有一个讨厌的副作用 - 所有输出似乎从后台线程生成。当我从命令提示符下运行程序,输出显示输出之前会显示一个提示。

我设置了​​项目属性输出类型为控制台应用程序,它修正了这个问题,但现在总有一个显示控制台窗口 - 甚至当它运行在'。WinForm的模式

有没有一种方法来获得两全其美的地方控制台行为像程序是当前进程并没有显示在控制台窗口时,程序将显示WinForm的?

更新: 我的道歉不澄清这一点。我控制台和WinForm的模式之间切换在Program.cs中是这样的:

  // nowin是基于一个参数集的布尔
如果(nowin)
{
    如果(!AttachConsole(-1))
    {
        AllocConsole();
    }
    // ...控制台模式code在这里...
}
其他
{
    //窗口运行
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(假);
    Application.Run(新Form1中(argDict));
}
 

解决方案

它看起来像有没有办法解决它: 1)如果我想在控制台模式下的输出表现得像一个专门的控制台应用程序,控制台窗口必须永远存在。 2)如果我想隐藏控制台,当我在窗口模式下运行它,我就失去了阻止打印。

vs2015怎么创建控制台应用程序

I have a WinForm project that I want to be usable as a console app if certain arguments are passed into it. Using some tips I read from here, I used the following code to make this work.

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();

[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int pid);

...

if (!AttachConsole(-1))
{
   AllocConsole();
}

This works, but there is one annoying side effect - all the output seems to be generated from a background thread. When I run the program from a command prompt, the output displays the next prompt before displaying the output.

I set the project properties' Output Type to Console Application and it fixed this problem, but now there is always a console window displayed - even when it is run in 'WinForm mode'.

Is there a way to get the best of both worlds where the console behaves like the program is the current process and the console window is not displayed when the program displays the WinForm?

UPDATE: My apologies for not clarifying this. I am toggling between console and WinForm mode in Program.cs like this:

// nowin is a bool that is set based on a parameter
if (nowin)
{
    if (!AttachConsole(-1))
    {
        AllocConsole();
    }
    //... Console mode code here...
}
else
{
    // run in window
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1(argDict));
}

解决方案

It looks like there is no way around it: 1) If I want the output in console mode to behave like a dedicated console app, the console window must always be there. 2) If I want to hide the console when I run it in windowed mode, I will lose the blocking prints.