我有一个主应用程序,它运行控制台应用程序。通常情况下,控制台应用程序会以隐藏的方式启动 (ProcessWindowStyle.Hidden
),但出于测试目的,我可以让它显示窗口。
在控制台应用程序中,我可以加载和执行插件。其中一个插件尝试打开一个WinForm对话框。如果控制台应用程序可见,则正常工作,但如果控制台应用程序被隐藏,则无法工作。
我已经尝试过:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form());
我也尝试在一个新的线程中做同样的事情。
Thread t = new System.Threading.Thread(start);
t.Start();
t.Join();
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()
和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);
}
}