如何在C#控制台应用程序中创建无模式对话框
本文关键字:创建 模式 对话框 应用程序 控制台 | 更新日期: 2023-09-27 17:58:19
我想用下面的代码创建一个无模式对话框。然而,这种形式在创作后似乎没有反应。我想如果我以这种方式创建消息循环,它可能会被阻止。有人知道如何以正确的方式创建它吗?
class Program
{
static void Main(string[] args)
{
Form form = new Form();
form.Show();
Console.ReadLine();
}
}
显示模式和无模式Windows窗体:
要将窗体显示为无模式对话框,请调用Show方法:
以下示例显示如何以非模态格式显示"关于"对话框。
// C#
//Display frmAbout as a modeless dialog
Form f= new Form();
f.Show();
要将窗体显示为模式对话框,请调用ShowDialog方法
以下示例显示了如何以模式显示对话框。
// C#
//Display frmAbout as a modal dialog
Form frmAbout = new Form();
frmAbout.ShowDialog();
请参阅:显示模式和无模式Windows窗体
请参阅以下控制台应用程序代码:
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");
}
}
您可以使用另一个线程,但必须等待该线程加入或中止:
像这样的工作示例代码:
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();
}
}
}
最后,我让它工作起来了。为了解锁我的主线程,我必须使用一个新线程并调用Applicatoin.Run为表单创建一个消息泵。现在形式和主线都活跃起来了。感谢所有
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();
}
}