强制MessageBox.Show显示在顶部

时间:2016-07-16 06:27:29

标签: c# .net winforms .net-4.5 topmost

我有一个简单的winforms appl,它会通知我何时向我的票证添加备注。我面临的问题是,当应用程序最小化时,消息框不会显示在我打开的所有其他窗口和程序之前。

我的代码是:

   private void button1_Click(object sender, EventArgs e) {
     DialogResult result1 = MessageBox.Show("Add some notes to your current ticket?",
      "Add Notes",
      MessageBoxButtons.YesNo);


     if (result1 == DialogResult.Yes) {
      Timer tm;
      tm = new Timer();

      tm.Interval = int.Parse(textBox2.Text);
      tm.Tick += new EventHandler(button1_Click);

      string pastebuffer = DateTime.Now.ToString();
      pastebuffer = "### Edited on " + pastebuffer + " by " + txtUsername.Text + " ###";
      Clipboard.SetText(pastebuffer);

      tm.Start();
     } else if (result1 == DialogResult.No) {
      //do something else
     }

我的理解是我需要添加TopMost = True。但我无法在我的代码中看到将其添加到哪里?

1 个答案:

答案 0 :(得分:2)

当您显示MessageBox时,将主表单上的TopMost属性设置为trueMessageBox将是最主要形式的模态,使MessageBox 最顶层

显示MessageBox后,您可以轻松地将TopMost属性设置为false。

private void button1_Click(object sender, EventArgs e)
{
    this.TopMost = true; // Here.

    DialogResult result1 = MessageBox.Show("Add some notes to your current ticket?",
    "Add Notes",
    MessageBoxButtons.YesNo);

    this.TopMost = false; // And over here.

    if (result1 == DialogResult.Yes) {
        Timer tm;
        tm = new Timer();

        tm.Interval = int.Parse(textBox2.Text);
        tm.Tick += new EventHandler(button1_Click);

        string pastebuffer = DateTime.Now.ToString();
        pastebuffer = "### Edited on " + pastebuffer + " by " + txtUsername.Text + " ###";
        Clipboard.SetText(pastebuffer);

        tm.Start();
    }
    else if (result1 == DialogResult.No)
    {
        // Do something else.
    }
}