我是這樣做的:
,我想顯示的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