Я пытаюсь запустить форму с ShowDialog, и он возвращает DialogResult.Cancel. Почему это?

Progress progress = new Progress();//progress.DialogResult is OK.
if (progress.ShowDialog() != DialogResult.OK)
{//progress.DialogResult is cancel.
    throw new ArgumentException();
}

В отладчике написано, что результатом является DialogResult.Cancel. Почему это? У меня есть форма только с индикатором выполнения и надписью. Ничего более. Я открыл и закрыл некоторые другие формы, если это имеет значение. Форма не открывается.

Прогресс класс:

public partial class Progress : Form
{
    public Progress()
    {
        InitializeComponent();
    }

    bool filesLength = false;

    public void OnWordsChanged()
    {
        if (!filesLength)
        {
            progressBar1.Maximum = Program.numberOfFiles;
            filesLength = true;
        }
        progressBar1.Value = Program.wordsDone;
    }
}

и дизайнер:

 partial class Progress
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.label1 = new System.Windows.Forms.Label();
        this.progressBar1 = new System.Windows.Forms.ProgressBar();
        this.SuspendLayout();
        // 
        // label1
        // 
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(13, 13);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(35, 13);
        this.label1.TabIndex = 0;
        this.label1.Text = "label1";
        // 
        // progressBar1
        // 
        this.progressBar1.Location = new System.Drawing.Point(13, 30);
        this.progressBar1.Name = "progressBar1";
        this.progressBar1.Size = new System.Drawing.Size(259, 23);
        this.progressBar1.TabIndex = 1;
        // 
        // Progress
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(284, 261);
        this.Controls.Add(this.progressBar1);
        this.Controls.Add(this.label1);
        this.Name = "Progress";
        this.Text = "Progess";
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.ProgressBar progressBar1;
}

1 ответ

Это нормальное поведение. Вы можете обратиться к этому ответу и из свойства Form.DialogResult.

Когда форма отображается в виде модального диалогового окна, нажатие кнопки "Закрыть" (кнопка с крестиком в правом верхнем углу формы) приводит к скрытию формы и установке для свойства DialogResult значения DialogResult.Cancel. Метод Close не вызывается автоматически, когда пользователь нажимает кнопку "Закрыть" диалогового окна или устанавливает значение свойства DialogResult. Вместо этого форма скрыта и может быть показана снова без создания нового экземпляра диалогового окна. Из-за этого поведения вы должны вызывать метод Dispose формы, когда форма больше не нужна вашему приложению.

То есть по умолчанию, когда вы закрываете форму, она будет иметь DialogResult.Cancel, если она не будет переопределена.

Другие вопросы по тегам