Setting the start position for OpenFileDialog/SaveFileDialog

前端 未结 8 1526
野趣味
野趣味 2021-01-01 11:48

For any custom dialog (form) in a WinForm application I can set its size and position before I display it with:

form.StartPosition = FormStartPosition.Manual         


        
相关标签:
8条回答
  • 2021-01-01 12:03

    OpenFileDialog and SaveFileDialog position themselves in the upper-left corner of the client area of the most recently displayed window. So just create a new invisible window positioned where you want the the dialog to appear before creating and showing that dialog.

    Window dialogPositioningWindow = new Window();
    dialogPositioningWindow.Left = MainWindow.Left + <left position within main window>;
    dialogPositioningWindow.Top  = MainWindow.Top  + <top  position within main window>;
    dialogPositioningWindow.Width = 0; 
    dialogPositioningWindow.Height = 0; 
    dialogPositioningWindow.WindowStyle = WindowStyle.None;
    dialogPositioningWindow.ResizeMode = ResizeMode.NoResize;
    dialogPositioningWindow.Show();// OpenFileDialog is positioned in the upper-left corner
                                   // of the last shown window (dialogPositioningWindow)
    Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();
    ...
    if ((bool)dialog.ShowDialog()){
       ...
    }
    dialogPositioningWindow.Close();
    
    0 讨论(0)
  • 2021-01-01 12:05

    Very grateful for BobB's reply on this one. There are a few more "gotchas". You have to pass the handle of PositionForm when calling OpenFileDialog1.ShowDialog(PositionForm) otherwise BobB's technique is not reliable in all cases. Also, now that W8.1 launches a new fileopen control with SkyDrive in it, the Documents folder location in the W8.1 fileopen control is now screwed. So I frig fileopen to use the old W7 control by setting ShowHelp = True.

    Here is the VB.NET code I ended up using, my contribution to the community in case it helps.

    Private Function Get_FileName() As String
    
        ' Gets an Input File Name from the user, works with multi-monitors
    
        Dim OpenFileDialog1 As New OpenFileDialog
        Dim PositionForm As New Form
        Dim MyInputFile As String
    
        ' The FileDialog() opens in the last Form that was created.  It's buggy!  To ensure it appears in the
        ' area of the current Form, we create a new hidden PositionForm and then delete it afterwards.
    
        PositionForm.StartPosition = FormStartPosition.Manual
        PositionForm.Left = Me.Left + CInt(Me.Width / 2)
        PositionForm.Top = Me.Top + CInt(Me.Height / 2)
        PositionForm.Width = 0
        PositionForm.Height = 0
        PositionForm.FormBorderStyle = Forms.FormBorderStyle.None
        PositionForm.Visible = False
        PositionForm.Show()
    
        ' Added the statement "ShowHelp = True" to workaround a problem on W8.1 machines with SkyDrive installed.
        ' It causes the "old" W7 control to be used that does not point to SkyDrive in error.
    
        OpenFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
        OpenFileDialog1.Filter = "Excel files (*.xls*)|*.xls*|CSV Files (*.csv)|*.csv"
        OpenFileDialog1.FilterIndex = 1
        OpenFileDialog1.RestoreDirectory = True
        OpenFileDialog1.AutoUpgradeEnabled = False
        OpenFileDialog1.ShowHelp = True
        OpenFileDialog1.FileName = ""
        OpenFileDialog1.SupportMultiDottedExtensions = False
        OpenFileDialog1.Title = "Select an Excel or .csv file containing patent data or list of Publication Numbers for your project."
    
        If OpenFileDialog1.ShowDialog(PositionForm) <> System.Windows.Forms.DialogResult.OK Then
            Console.WriteLine("No file was selected. Please try again!")
            PositionForm.Close()
            PositionForm.Dispose()
            OpenFileDialog1.Dispose()
            Return ""
        End If
        PositionForm.Close()
        PositionForm.Dispose()
    
        MyInputFile = OpenFileDialog1.FileName
        OpenFileDialog1.Dispose()
        Return MyInputFile
    
    End Function
    
    0 讨论(0)
  • 2021-01-01 12:05

    Using Rob Sherrit's response on Jan 22 '14 as inspiration, I created a new module and called it CKRFileDialog (call it what you want) which contains the following code:

    Public Function Show(fd As Object, CoveredForm As Form, Optional bShowHelp As Boolean = False) As DialogResult
    
        Dim oDR As DialogResult
    
        'The .Net FileDialogs open in the last Form that was created. 
        'To ensure they appear in the area of the current Form, we create a new HIDDEN PositionForm and then 
        'delete it afterwards.
    
        Dim PositionForm As New Form With {
          .StartPosition = FormStartPosition.Manual,
          .Left = CoveredForm.Left + CInt(CoveredForm.Width / 8),  'adjust as required
          .Top = CoveredForm.Top + CInt(CoveredForm.Height / 8),   'adjust as required
          .Width = 0,
          .Height = 0,
          .FormBorderStyle = Windows.Forms.FormBorderStyle.None,
          .Visible = False
        }
        PositionForm.Show()
    
        'If you use SkyDrive you need to ensure that "bShowHelp" is set to True in the passed parameters.
        'This is a workaround for a problem on W8.1 machines with SkyDrive installed.
        'Setting it to "true" causes the "old" W7 control to be used which avoids a pointing to SkyDrive error.
        'If you do not use SkyDrive then simply do not pass the last parameter (defaults to "False")
        fd.ShowHelp = bShowHelp
    
        'store whether the form calling this routine is set as "topmost"
        Dim oldTopMost As Integer = CoveredForm.TopMost
        'set the calling form's topmost setting to "False" (else the dialogue will be "buried"
        CoveredForm.TopMost = False
    
        oDR = fd.ShowDialog(PositionForm)
    
        'set the "topmost" setting of the calling form back to what it was.
        CoveredForm.TopMost = oldTopMost
        PositionForm.Close()
        PositionForm.Dispose()
        Return oDR
    
    End Function
    

    I then call this code in my various modules as follows:

    If performing a "FileOpen" ensure that there is a FileOpenDialog component added to your form or code and adjust the properties of the component if you wish (e.g. InitDirectory,Multiselect,etc.)

    Do the same when using FileSaveDialog components (Different properties to the FileOpenDialog component may apply).

    To "show" the dialog component use a line of code as follows, passing two parameters, the first the FileDialog you are using ("Open" or "Save") and the second parameter the Form upon which you wish to overlay the dialogue.

    CKRFileDialog.Show(saveFileDialog1, CoveredForm) or CKRFileDialog.Show(openFileDialog1, CoveredForm)

    Remember, if you are using SkyDrive you must pass "True" as a third parameter:

    CKRFileDialog.Show(saveFileDialog1, CoveredForm, True) or CKRFileDialog.Show(openFileDialog1, CoveredForm, True)

    I set the "offset" of the dialogue to be 1/8 the way across and down on the form "CoveredForm", but you can set that back to 1/2 (as in Rob Sherret's code) or whatever value you wish.

    This seemed the easiest approach

    Thanks Rob! :-)

    0 讨论(0)
  • 2021-01-01 12:09

    I suspect that the best you can do is make sure you use the overload of ShowDialog that accepts an IWin32Window to use as the parent. This might help it choose an appropriate location; most commonly:

    using(var dlg = new OpenFileDialog()) {
        .... setup
        if(dlg.ShowDialog(this) == DialogResult.OK) {
            .... use
        }
    }
    
    0 讨论(0)
  • 2021-01-01 12:20

    I had this problem for most of yesterday. BobB's answer was the one that helped me out the most (Thanks BobB).

    You can even go as far as to make a private method that creates a window and closes it before the dialog.ShowDialog() method call and it will still centre the OpenFileDialog.

    private void openFileDialogWindow()
    {
        Window openFileDialogWindow = new Window();
        openFileDialogWindow.Left = this.Left;
        openFileDialogWindow.Top = this.Top;
        openFileDialogWindow.Width = 0;
        openFileDialogWindow.Height = 0;
        openFileDialogWindow.WindowStyle = WindowStyle.None;
        openFileDialogWindow.ResizeMode = ResizeMode.NoResize;
        openFileDialogWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
    
        openFileDialogWindow.Show();
        openFileDialogWindow.Close();
    
        openFileDialogWindow = null;
    }
    

    Then call it in any method before the ShowDialog() method.

    public string SelectWebFolder()
    {
        string WebFoldersDestPath = null;
    
        CommonOpenFileDialog filePickerDialog = new CommonOpenFileDialog();
        // OpenFileDialog Parameters..
    
        openFileDialogWindow();
    
        if (filePickerDialog.ShowDialog() == CommonFileDialogResult.Ok)
        {
            WebFoldersDestPath = filePickerDialog.FileName + "\\";
        }
    
        filePickerDialog = null;
    
        return WebFoldersDestPath;
    }
    
    0 讨论(0)
  • 2021-01-01 12:20

    There is quite an old example of one approach on MSDN.

    http://msdn.microsoft.com/en-us/library/ms996463.aspx

    It includes all the code needed to implement your own OpenFileDialog class that allows extensibility.

    0 讨论(0)
提交回复
热议问题