0

I'm showing a print preview window for some large pages. The rendering of these takes some time so I want to show more progress information than the default 'Page 1/1' message.

I created a simple windows form project that shows my current approach:

(you can create a new windows form project with two forms and copy paste if you like)

public event EventHandler PrintReady;
public event ProgressChangedEventHandler ProgressChanged;

private void button1_Click(object sender, EventArgs e)
{
  var printDocument = new PrintDocument();
  printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
  printDocument.EndPrint += new PrintEventHandler(printDocument_EndPrint);

  var printPreviewDialog = new PrintPreviewDialog();
  printPreviewDialog.Document = printDocument;

  // Create the 'progress' form.
  var form2 = new Form2(this);
  form2.Show();

  printPreviewDialog.ShowDialog();            
}

void printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
  for (int i = 0; i < 100; i++)
  {
    // This is where I do some rendering.
    Thread.Sleep(20);
    if (this.ProgressChanged != null)
    {
      this.ProgressChanged.Invoke(this, new ProgressChangedEventArgs(i, null));
    }
  }            
}

void printDocument_EndPrint(object sender, PrintEventArgs e)
{
  if (this.PrintReady != null)
  {
    this.PrintReady.Invoke(this, null);
  }
}

And then off course my progress form:

public Form2(Form1 form1)
{
  form1.ProgressChanged += new ProgressChangedEventHandler(ProgressChangedHandler);
  form1.PrintReady += new EventHandler(PrintReadyHandler);
  InitializeComponent();
}

void PrintReadyHandler(object sender, EventArgs e)
{
  this.Close();
}

void ProgressChangedHandler(object sender, ProgressChangedEventArgs e)
{
  progressBar1.Value = e.ProgressPercentage;
}

The 'this.Close()' also closes my print preview! If I remove that line then the print preview is just shown and stays open. So the Close() function is closing both the progress window and the PrintPreview window.

Why is this happening?

Sunib
  • 304
  • 2
  • 14
  • So hide the form instead? The print preview windows is being closed because your closing the form that launched the print preview. An alternative solution would be to launch the preview from its own thread. – Security Hound Nov 19 '12 at 13:24
  • @Ramhound: I am not closing the form that launched the print preview. I'm only closing Form2. The only reference between the two is an event... – Sunib Nov 19 '12 at 14:39

1 Answers1

0

I think you need to specify the owner of the Print Preview dialog as form1 - see below:

printPreviewDialog.ShowDialog(this);
SpruceMoose
  • 9,737
  • 4
  • 39
  • 53
  • Thanks! This solves the problem. So it must be using the last created window as it's owner by default? I must admit that I cannot fully understand this behaviour. – Sunib Nov 20 '12 at 15:16