我想用下面的代码创建一个无模式对话框。 但是,表单在创建后似乎没有响应。 我猜如果我以这种方式创建消息循环可能会被阻止。 任何人都知道如何以正确的方式创建它?
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();
参见:Displaying Modal and Modeless Windows Forms
请参阅以下控制台应用程序代码:
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();
}
}
}
关于c# - 如何在 C# 控制台应用程序中创建无模式对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38549753/