C# Windows Forms Print Dialog box click OK twice to respond
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.
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:
In
toolstrip1_Click
:private void toolStrip1_Click(object sender, EventArgs e) { this.Validate(); }
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.
I achieved it using a timer.
Drop a timer onto the form containing the toolstrip and turn it into a one shot timer with a delay of say 1mS. Note: Timer must initially have 'Enabled' set to 'False'
private void toolStripBtnPrint_Click(object sender, EventArgs e)
{
timer1.Interval = 1; // 1ms
timer1.Enabled = true;
}
Create a timer tick event handler
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
PrintDialog printDialogue=new PrintDocument();
//Do your initialising here
if(DialogResult.OK == printDialogue.ShowDialog())
{
//Do your stuff here
}
}
It may be dirty but it got me out of a hole. HTH
Maybe it is an issue similar to this one: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/681a50b4-4ae3-407a-a747-87fb3eb427fd
精彩评论