c# - 如何在 C# 控制台应用程序中创建无模式对话框

标签 c# .net dialog modal-dialog modeless-dialog

我想用下面的代码创建一个无模式对话框。 但是,表单在创建后似乎没有响应。 我猜如果我以这种方式创建消息循环可能会被阻止。 任何人都知道如何以正确的方式创建它?

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/

相关文章:

c# - 使用 .Net 中的 IAmsiStream 会导致 AccessViolationException

c# - WCF:无法访问已关闭的流

.net - 真空分析运行非常缓慢,导致其他系统超时

.net - WPF中的数字编辑字段?

angular - 我无法注入(inject) MAT_DIALOG_DATA!错误 : inject() must be called from an injection context

c# - OnCertificateValidated 未运行 - 自签名证书客户端身份验证 - ASP.NET Core 和 Kestrel

c# - Linq To Sql 和 identity_insert

.net - 将图像从 .NET 传输到 Delphi

android - 如何制作 Material Design 全屏对话框?

jsf - p :fileUpload doesn't work inside p:dialog