C# Windows Forms Print Dialog box click OK twice to respond

sbartlett picture sbartlett · Apr 15, 2010 · Viewed 11.4k times · Source

I'm using Visual Studio 2008, .net Framework 3.5 for a Windows forms client-server app that I'm working on. There is a weird bug when I run the program and try to print. The print dialog box opens, but I have to click the OK button twice for it to work. After the second click it works fine, no errors. When I put a breakpoint on: if (result == DialogResult.OK) , the breakpoint doesn't trigger until the second click. Here is the code:

private void tbPrint_Click(object sender, EventArgs e)
{
    try
    {
        printDialog1.Document = pDoc;

        DialogResult result = printDialog1.ShowDialog();

        if (result == DialogResult.OK)
        {
            pDoc.PrinterSettings.PrinterName = printDialog1.PrinterSettings.PrinterName;
            pDoc.Print();
        }
        ...

This is driving me crazy, and I can't see anything else that would interfere with it.

Answer

JonS picture JonS · May 8, 2012

I came across this while having the "first toolstrip click unrecognized" using an OpenFileDialog in C#/WinForms. After much cursing and googling, I did this:

  1. In toolstrip1_Click:

    private void toolStrip1_Click(object sender, EventArgs e)
    {
      this.Validate();
    }
    
  2. In the function that uses calls OpenFileDialog:

    private void locateMappingToolStripMenuItem_Click(object sender, EventArgs e)
    {
      OpenFileDialog dg = new System.Windows.Forms.OpenFileDialog();
      if (dg.ShowDialog() == DialogResult.OK)
      {
        fileLocation = Path.GetDirectoryName(dg.FileName);
        try
        {
          if (LoadData())
          {
            //Enable toolbar buttons
            toolStripButton3.Enabled = true;
            toolStripButton5.Enabled = true;
            toolStripButton1.Enabled = true;
            toolStripButton2.Enabled = true;
            searchParm.Enabled = true;
            toolStripButton4.Enabled = true;
            toolStripButton6.Enabled = true;
            exitToolStripMenuItem.Enabled = true;
            EditorForm.ActiveForm.TopLevelControl.Focus();
          }
        }
        catch (Exception exx) 
        {
          MessageBox.Show(exx.Message + Environment.NewLine + exx.InnerException);
        }
      }
    }
    

Two things lines seem to be key:

  • When the OpenFileDialog closes, focus needs to be reset to the main window (EditorForm.ActiveForm.TopLevelControl.Focus();)
  • When the toolstrip button is clicked, the toolstrip validates itself (this.Validate()) and recognizes the mouse event.