[英]How to create a modeless dialog box within a C# console app
I want to create a modeless dialog box with below code. 我想用下面的代码创建一个无模式对话框 。 However, the form seems not responding after creation. 但是,表单创建后似乎没有响应。 I guess the message loop may be blocked if I create it in this way. 我猜想如果以此方式创建消息循环,可能会阻止该消息循环。 Anyone knows how to create it in the correct way? 有人知道如何以正确的方式创建它吗?
class Program
{
static void Main(string[] args)
{
Form form = new Form();
form.Show();
Console.ReadLine();
}
}
Displaying Modal and Modeless Windows Forms: 显示模态和无模Windows窗体:
To display a form as a modeless dialog box Call the Show method: 将表单显示为无模式对话框调用Show方法:
The following example shows how to display an About dialog box in modeless format. 下面的示例显示如何以无模式格式显示“关于”对话框。
// C#
//Display frmAbout as a modeless dialog
Form f= new Form();
f.Show();
To display a form as a modal dialog box Call the ShowDialog method. 将窗体显示为模式对话框调用ShowDialog方法。
The following example shows how to display a dialog box modally. 以下示例显示如何模态显示对话框。
// C#
//Display frmAbout as a modal dialog
Form frmAbout = new Form();
frmAbout.ShowDialog();
See: Displaying Modal and Modeless Windows Forms 请参阅: 显示模态和无模Windows窗体
See the following console application code: 请参阅以下控制台应用程序代码:
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
class Test
{
[STAThread]
static void Main()
{
var f = new Form();
f.Text = "modeless ";
f.Show();
var f2 = new Form() { Text = "modal " };
Application.Run(f2);
Console.WriteLine("Bye");
}
}
you may use another thread, but you must wait for that thread to join or abort it: 您可以使用另一个线程,但是必须等待该线程加入或中止它:
like this working sample code: 像这样的工作示例代码:
using System;
using System.Threading;
using System.Windows.Forms;
namespace ConsoleApplication2
{
static class Test
{
[STAThread]
static void Main()
{
var f = new Form { Text = "Modeless Windows Forms" };
var t = new Thread(() => Application.Run(f));
t.Start();
// do some job here then press enter
Console.WriteLine("Press Enter to Exit");
var line = Console.ReadLine();
Console.WriteLine(line);
//say Hi
if (t.IsAlive) f.Invoke((Action)(() => f.Text = "Hi"));
if (!t.IsAlive) return;
Console.WriteLine("Close The Window");
// t.Abort();
t.Join();
}
}
}
Finally, I got it working. 终于,我开始工作了。 In order to unblock my main thread, I have to use a new thread and call Applicatoin.Run to create a message pump for the form. 为了解除阻塞我的主线程,我必须使用一个新线程并调用Applicatoin.Run为该表单创建一个消息泵。 Now both the form and main thread are alive now. 现在,窗体和主线程都处于活动状态。 Thanks all 谢谢大家
class Program
{
public static void ThreadProc(object arg)
{
Form form = arg as Form;
Application.Run(form);
}
[STAThread]
static void Main(string[] args)
{
Form form = new Form() { Text = "test" };
Thread t = new Thread(ThreadProc);
t.Start(form);
string line = Console.ReadLine();
Console.WriteLine(line);
form.Close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.