我有一个运行控制台应用程序的主应用程序。控制台应用程序通常是隐藏启动的(ProcessWindowStyle.Hidden
),但出于测试目的,我可以使用显示的窗口来运行它。
在控制台应用程序中,我可以加载和执行插件。其中一个插件尝试打开 WinForm 对话框。如果控制台应用程序可见,它可以正常工作,但如果控制台隐藏,它就不再工作。
我努力了:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
我也在新线程中尝试了同样的操作。
Thread t = new System.Threading.Thread(start);
t.Start();
t.Join();
where start()
包含之前的东西。另外我尝试过ShowDialog()
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var f = new Form();
f.ShowDialog();
所有方法均未显示该窗口。
在 WinDbg 中,本机调用堆栈始终包括NtUserWaitMessage()
:
0:000> k
ChildEBP RetAddr
0038dd58 7b0d8e08 USER32!NtUserWaitMessage+0x15
并且托管调用堆栈始终包括WaitMessage()
, FPushMessageLoop()
and RunMessageLoop()
:
0:000> !clrstack
OS Thread Id: 0x47c4 (0)
ESP EIP
0045e560 76bff5be [InlinedCallFrame: 0045e560] System.Windows.Forms.UnsafeNativeMethods.WaitMessage()
0045e55c 7b0d8e08 System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32, Int32, Int32)
0045e5f8 7b0d88f7 System.Windows.Forms.Application+ThreadContext.RunMessageLoopInner(Int32, System.Windows.Forms.ApplicationContext)
0045e64c 7b0d8741 System.Windows.Forms.Application+ThreadContext.RunMessageLoop(Int32, System.Windows.Forms.ApplicationContext)
0045e67c 7b5ee597 System.Windows.Forms.Application.RunDialog(System.Windows.Forms.Form)
0045e690 7b622d98 System.Windows.Forms.Form.ShowDialog(System.Windows.Forms.IWin32Window)
0045e71c 7b622faf System.Windows.Forms.Form.ShowDialog()
如何从隐藏的控制台窗口显示 WinForms 表单?
SSCCE:
将其编译为 Windows 窗体应用程序:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var startInfo = new ProcessStartInfo("Console.exe");
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(startInfo);
}
}
将其编译为控制台应用程序:
class Program
{
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var mainForm = new Form();
// Enable next line to make it show
// mainForm.Visible = true;
Application.Run(mainForm);
}
}