我是这样做的:
,我想显示的OpenFileDialog点:
Thread posThread = new Thread(positionOpenDialog);
posThread.Start();
DialogResult dr = ofd.ShowDialog();
重新定位代码:
[DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName);
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);
/// <summary>
/// Find the OpenFileDialog window when it appears, and position it so
/// that we can see both dialogs at once. There is no easier way to
/// do this (&^%$! Microsoft!).
/// </summary>
private void positionOpenDialog()
{
int count = 0;
IntPtr zero = (IntPtr)0;
const int SWP_NOSIZE = 0x0001;
IntPtr wind;
while ((wind = FindWindowByCaption(zero, "Open")) == (IntPtr)0)
if (++count > 100)
return; // Find window failed.
else
Thread.Sleep(5);
SetWindowPos(wind, 0, Right, Top, 0, 0, SWP_NOSIZE);
}
我启动一个线程,寻找一个带有“打开”标题的窗口。 (通常在3次迭代或15毫秒内找到。)然后我用获得的句柄设置它的位置。 (请参阅SetWindowPos文档中的位置/大小参数。)
Kludgy。
这听起来很简单,它必须工作(至少它必须测试)!唉,在这个测试用例中,0-arg和1-arg ShowDialog都以同样的方式失败: 1.运行应用程序。 2.调用新的OpenFileDialog()。ShowDialog(this);对话框与应用程序在相同的监视器上 3.关闭对话框。 4.将应用程序窗口拖到不同的显示器上。调用新的OpenFileDialog()。ShowDialog(this);对话框出现在* original *监视器上。 尽管我在第5步中使用了新鲜的OpenFileDialog,但仍然有一些关于主应用程序的原始位置的信息。 – 2009-08-10 19:31:13
我(最后:-)选择Marc的答案是最好的,因为我最近发现它*不适用于Windows 7.我的机器是WinXP,上面提到的测试用例仍然失败。我决定尝试使用相同问题的Microsoft论坛,并给出了适用于WinXP的解决方案 - 请参阅此主题(http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/dec48489- 0a57-4baa-b401-82266be782e0)代码。 – 2010-07-13 18:27:10