首页 > 解决方案 > 获取 PrintDialog 子级的对话框句柄

问题描述

我有一个连续运行的应用程序。用户可以打开“选项”或“打印”等内容,但通常会离开而将它们未使用并打开。因此,我现在在所有事情上都有超时,但 PrintDialog 让我很伤心。

Get modal dialog handle for PrintDialog中的线程 提供了巨大的帮助,并为我提供了 PrintDialog 句柄,因此我可以将其关闭,但它没有解决关闭 PrintDialog 子项(例如“首选项”等)的问题。

尽管 user32.dll GetActiveWindow() 正确地为我提供了 PrintDialog 的句柄,但它似乎没有获取 Preferences 子项并返回值 0。


public static IntPtr printDialogHandle;

[DllImport("user32.dll")]
static extern bool DestroyWindow(IntPtr hWnd);

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr GetActiveWindow();


private void btnPrint_Click(object sender, EventArgs e)
{
   BeginInvoke(new MethodInvoker(TweakPrintDialog));

   using (this.pdi = new PrintDialog())
   {
      this.pdi.PrinterSettings = Properties.Settings.Default.printSettings;
      if (this.pdi.ShowDialog(this) == DialogResult.Cancel)
         return;

      //do the actual printing
      printPages(false);
   }
}


private void TweakPrintDialog()
{
   // get handle for the just opened PrintDialog
   printDialogHandle = GetActiveWindow();

   // timeout timer
   System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer();
   tmr.Tick += new EventHandler(timer_Tick);
   tmr.Interval = 60000;
   tmr.Start();
}


private static void timer_Tick(object sender, EventArgs e)
{
    System.Windows.Forms.Timer tmr = (System.Windows.Forms.Timer)sender;
    tmr.Stop();
    tmr.Dispose();

    //any children?    returns handles to heaps of unwanted stuff like controls
    //  System.Diagnostics.Process[] otherApps = System.Diagnostics.Process.GetProcessesByName("Printing Selected Papers");
    //  if (otherApps.Length == 0) return;
    //  if (otherApps[0] != null)
    //  {
    //  // var allChildWindows = new WindowHandleInfo(otherApps[0].MainWindowHandle).GetAllChildHandles();
    //   var allChildWindows = new WindowHandleInfo(printDialogHandle).GetAllChildHandles();
    //  }


      // Works but unreliable. Other windows may be active by now
      // SendKeys.Send("{ESC}");
      // System.Threading.Thread.Sleep(50);
      // SendKeys.Send("{ESC}");
      // System.Threading.Thread.Sleep(50);
      // SendKeys.Send("{ESC}");


      // try and get handle to the PrintDialog Preferences form. Doesn't work, just returns 0
      IntPtr child = GetActiveWindow();
      if (child != printDialogHandle)
         DestroyWindow(child);


     // get rid of the PrintDialog
     DestroyWindow(printDialogHandle);
}

在我杀死 PrintDialog 本身之前,如何找到任何 PrintDialog 子句柄以便通过 user32.dll DestroyWindow() 杀死它们?

标签: c#hwndprintdialog

解决方案


推荐阅读