Search code examples
c#.netwinforms.net-4.5topmost

Force MessageBox.Show to display on top


I have a simple winforms appl which will notify me when to add notes to my ticket. The problem I face is that when the application is minimised the messagebox doesnt show in front of all the other windows and programs I have open.

The code I have is:

   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
     }

My understanding is that i need to add TopMost = True. But i cannot see where to add that in my code?


Solution

  • When you show your MessageBox set the TopMost property on your main form to true. The MessageBox will be modal to the top most main form making the MessageBox top most.

    After the MessageBox has been shown you can easily set the TopMost property to false again.

    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.
        }
    }