对 话 框 对话框 对话框

1.对话框

对话框 Dialog,用于获取用户的输入


Form,代表一个窗口,普通窗口或对话框窗口
演示:

  • 添加一个窗体
  • 界面设计

使用对话框
弹出对话框窗口:

MyDialog dlg =new MyDialog();
dlg.ShowDialog(this);
dlg.Dispose();

其中,

  • dlg.Show() 作为普通窗口显示
  • dlg.ShowDialog() 作为对话框窗口显示
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm基础22
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            MyDialog dlg = new MyDialog();
            dlg.ShowDialog(this);
            dlg.Dispose();
        }
    }
}

Form窗口对象含有非托管资源,需要手工销毁
但是:
为什么刚刚ShowDialog(),就用Dispose()把它销毁掉?

2.对话框的阻塞

阻塞Blocked,是对话框最重要的一个特性
示例:

MyDialog dlg = new MyDialog();
dlg.ShowDialog(this);
dlg.Dispose();

只有当对话框被用户关闭以后,ShowDialog()才会返回,程序得以继续执行。


阻塞的效果:
1 方法卡在ShowDialog这一行,不往下执行
2 对话框窗口可以活动,后面的父窗口不可以活动

3.对话框的属性

(外观)Text窗口标题
(窗口样式)MaximizeBox最大化按钮
(窗口样式) MinimizeBox最大化按钮
(窗口样式) ShowInTaskbar是否在任务栏显示
(布局) StartPosition窗口显示位置
(外观) FormBorderStyle边框设定/是否可以调整大小

进程同步_父窗口
进程同步_json_02

4.对话框的返回

1如何关闭对话框
2如何取得对话框的输入

取得用户输入

先判断用户是点了‘确定’还是‘取消’
再从对话框中取得用户的输入值

DialogResult rc = dlg.ShowDialog();
if(rc == DialogResult.OK)
{
string str = dlg.edit.Text;
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm基础22
{
    public partial class MyDialog : Form
    {
        public MyDialog()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
    }
}


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm基础22
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            MyDialog dlg = new MyDialog();
            DialogResult rc = dlg.ShowDialog();
            if(rc == DialogResult.OK)
            {
                string str = dlg.textBox1.Text;
                MessageBox.Show(str);
            }
            dlg.Dispose();
        }
    }
}


设置DialogResult,有两层作用:

  • 关闭对话框
  • 设定返回值,即ShowDialog()返回的值

5.(练习)样式设定

实现:
1添加对话框StyleDialog

  • 添加控件,设置初始值
  • 添加确定、取消按钮,设置DialogResult

2调用对话框
当用户点确定时,取得输入的值,后续处理。

6.细节