1

我想达到与本文相同的效果,对于 Windows 窗体,是否可以不将控件托管在不同的窗体上?

编辑我更感兴趣的是在文章中实现控件的确切行为,在表单上显示控件并阻止调用函数,但没有为此目的使用其他表单。

4

2 回答 2

3

您可以使用两个按钮和消息标签创建一个 UserControl,然后在构造函数中将其可见性设置为 false:

    public MyDialog()
    {
        InitializeComponent();
        Visible = false;
    }

然后将三个变量添加到控件中:

    Form _parent;
    bool _result;
    bool _clicked = false;

父表单将是包含您的控件的表单,并且必须在使用该控件之前进行设置,因为它必须知道必须禁用什么。

    public void SetParent(Form f)
    {
        _parent = f;
    }

_result 将包含对话框的结果,_clicked 将用于确定何时关闭对话框。显示对话框时必须做的是:

  1. 设置标签
  2. 禁用表单(但不是对话框)
  3. 使对话框可见
  4. 等待用户单击其中一个按钮
  5. 隐藏对话框
  6. 重新启用父窗体
  7. 返回结果

所以你可以添加这个方法来启用/禁用父表单:

    private void ParentEnabled(bool aBool)
    {
        if (_parent == null)
            return;
        foreach (Control c in _parent.Controls)
            if (c != this)
                c.Enabled = aBool;
    }

并在 ShowDialog 方法中使用它:

    public bool ShowDialog(string msg)
    {
        if (_parent == null)
            return false;
        // set the label
        msgLbl.Text = msg;
        // disable the form
        ParentEnabled(false);
        // make the dialog visible
        Visible = true;
        // wait for the user to click a button
        _clicked = false;
        while (!_clicked)
        {
            Thread.Sleep(20);
            Application.DoEvents();
        }
        // reenable the form
        ParentEnabled(true);
        // hide the dialog 
        Visible = false;
        // return the result
        return _result;
    }

显然,按钮有责任设置 _result 和 _clicked 变量:

    private void okBtn_Click(object sender, EventArgs e)
    {
        _result = true;
        _clicked = true;
    }
    private void cancelBtn_Click(object sender, EventArgs e)
    {
        _result = false;
        _clicked = true;
    }
于 2011-08-08T10:02:21.463 回答
0

如何创建中间包含不透明形状上的文本的透明表单(无论您喜欢什么)。然后在运行时,您将调整此表单的大小,使其与您要在其上显示它的窗口具有相同的大小,并放置它以使其覆盖它。

于 2011-08-08T08:14:47.480 回答