gpt4 book ai didi

c# - 从隐藏的控制台应用程序显示表单

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:13 32 4
gpt4 key购买 nike

我有一个运行控制台应用程序的主应用程序。控制台应用程序通常以隐藏方式启动 (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 中, native 调用堆栈始终包含 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 表单?

中南合作:

将其编译为 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);
}
}

最佳答案

使用 Winspector Spy我发现窗口实际上是可用的,但它没有 WS_VISIBLE 样式。将该样式应用于表单使其可见,并显示在 Windows 任务栏中。

解决方案是在显示之前使表单可见,因此以下方法有效:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var f = new Form()
f.Visible = true;
Application.Run(f);

因为在我的例子中我想获得返回值,所以我应该调用 ShowDialog()。但是,不允许在已经可见的窗体上调用 ShowDialog(),因此我坚持使用 Application.Run(f) 并自己检索结果:

var answer = configForm.DialogResult;

关于c# - 从隐藏的控制台应用程序显示表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22605988/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com