FolderBrowserDialog bring to front





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have the following PowerShell function which works well, but the window opens up in the background behind the PowerShell ISE.



# Shows folder browser dialog box and sets to variable
function Get-FolderName() {
Add-Type -AssemblyName System.Windows.Forms
$FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
SelectedPath = 'C:Temp'
ShowNewFolderButton = $false
Description = "Select Staging Folder."
}
# If cancel is clicked the script will exit
if ($FolderBrowser.ShowDialog() -eq "Cancel") {break}
$FolderBrowser.SelectedPath
} #end function Get-FolderName


I can see there's a .TopMost property that can be used with the OpenFileDialog class but this doesn't appear to transfer over to the FolderBrowserDialog class.



Am I missing something?










share|improve this question































    0















    I have the following PowerShell function which works well, but the window opens up in the background behind the PowerShell ISE.



    # Shows folder browser dialog box and sets to variable
    function Get-FolderName() {
    Add-Type -AssemblyName System.Windows.Forms
    $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
    SelectedPath = 'C:Temp'
    ShowNewFolderButton = $false
    Description = "Select Staging Folder."
    }
    # If cancel is clicked the script will exit
    if ($FolderBrowser.ShowDialog() -eq "Cancel") {break}
    $FolderBrowser.SelectedPath
    } #end function Get-FolderName


    I can see there's a .TopMost property that can be used with the OpenFileDialog class but this doesn't appear to transfer over to the FolderBrowserDialog class.



    Am I missing something?










    share|improve this question



























      0












      0








      0








      I have the following PowerShell function which works well, but the window opens up in the background behind the PowerShell ISE.



      # Shows folder browser dialog box and sets to variable
      function Get-FolderName() {
      Add-Type -AssemblyName System.Windows.Forms
      $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
      SelectedPath = 'C:Temp'
      ShowNewFolderButton = $false
      Description = "Select Staging Folder."
      }
      # If cancel is clicked the script will exit
      if ($FolderBrowser.ShowDialog() -eq "Cancel") {break}
      $FolderBrowser.SelectedPath
      } #end function Get-FolderName


      I can see there's a .TopMost property that can be used with the OpenFileDialog class but this doesn't appear to transfer over to the FolderBrowserDialog class.



      Am I missing something?










      share|improve this question
















      I have the following PowerShell function which works well, but the window opens up in the background behind the PowerShell ISE.



      # Shows folder browser dialog box and sets to variable
      function Get-FolderName() {
      Add-Type -AssemblyName System.Windows.Forms
      $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
      SelectedPath = 'C:Temp'
      ShowNewFolderButton = $false
      Description = "Select Staging Folder."
      }
      # If cancel is clicked the script will exit
      if ($FolderBrowser.ShowDialog() -eq "Cancel") {break}
      $FolderBrowser.SelectedPath
      } #end function Get-FolderName


      I can see there's a .TopMost property that can be used with the OpenFileDialog class but this doesn't appear to transfer over to the FolderBrowserDialog class.



      Am I missing something?







      winforms powershell folderbrowserdialog






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 4 at 13:03









      Ansgar Wiechers

      146k13135193




      146k13135193










      asked Jan 4 at 10:38









      jshizzlejshizzle

      981211




      981211
























          2 Answers
          2






          active

          oldest

          votes


















          2














          Hope this helps



          Add-Type -AssemblyName System.Windows.Forms
          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
          $FolderBrowser.Description = 'Select the folder containing the data'
          $result = $FolderBrowser.ShowDialog((New-Object System.Windows.Forms.Form -Property @{TopMost = $true }))
          if ($result -eq [Windows.Forms.DialogResult]::OK){
          $FolderBrowser.SelectedPath
          } else {
          exit
          }


          //Edit to comment



          There are 2 variants (overloads) of the ShowDialog () method.



          See documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.showdialog%28v=vs.110%29.aspx



          In the second variant, you can specify the window that should be the mother of the dialogue.



          Topmost should be used sparingly or not at all! If multiple windows are topmost then which is topmost? ;-))
          First try to set your window as a mother then the OpenfileDialog / SaveFileDialog should always appear above your window:



          $openFileDialog1.ShowDialog($form1)


          If that's not enough, take Topmost.



          Your dialogue window inherits the properties from the mother. If your mother window is topmost, then the dialog is also topmost.



          Here is an example that sets the dialogue Topmost.



          In this example, however, a new unbound window is used, so the dialog is unbound.



          $openFileDialog1.ShowDialog((New - Object System.Windows.Forms.Form - Property @{TopMost = $true; TopLevel = $true}))





          share|improve this answer


























          • Ok, so I did find this method on my searches but it didn't always appear to work and just seemed to stop vscode from accepting key entry in the console for a credential call after. Was hoping to add "TopMost = $true" to my list of properties in the original code I provided but didn't doesn't like it and can't see why if it can be used in yours...?

            – jshizzle
            Jan 4 at 10:49











          • @jshizzle see the edit ;-)

            – Jaapaap
            Jan 4 at 11:02











          • @Jaapaap Unfortunately, your edit is all about the OpenFileDialog, not the FolderBrowserDialog

            – Theo
            Jan 4 at 14:54



















          1














          A reliable way of doing this is to add a piece of C# code to the function.
          With that code, you can get a Windows handle that implements the IWin32Window interface. Using that handle in the ShowDialog function will ensure the dialog is displayed on top.



          Function Get-FolderName {   
          # To ensure the dialog window shows in the foreground, you need to get a Window Handle from the owner process.
          # This handle must implement System.Windows.Forms.IWin32Window
          # Create a wrapper class that implements IWin32Window.
          # The IWin32Window interface contains only a single property that must be implemented to expose the underlying handle.
          $code = @"
          using System;
          using System.Windows.Forms;

          public class Win32Window : IWin32Window
          {
          public Win32Window(IntPtr handle)
          {
          Handle = handle;
          }

          public IntPtr Handle { get; private set; }
          }
          "@

          if (-not ([System.Management.Automation.PSTypeName]'Win32Window').Type) {
          Add-Type -TypeDefinition $code -ReferencedAssemblies System.Windows.Forms.dll -Language CSharp
          }
          # Get the window handle from the current process
          # $owner = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
          # Or write like this:
          $owner = [Win32Window]::new([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)

          # Or use the the window handle from the desktop
          # $owner = New-Object Win32Window -ArgumentList (Get-Process -Name explorer).MainWindowHandle
          # Or write like this:
          # $owner = [Win32Window]::new((Get-Process -Name explorer).MainWindowHandle)

          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
          SelectedPath = 'C:Temp'
          ShowNewFolderButton = $false
          Description = "Select Staging Folder."
          }
          # set the return value only if a selection was made
          $result = $null
          If ($FolderBrowser.ShowDialog($owner) -eq "OK") {
          $result = $FolderBrowser.SelectedPath
          }
          # clear the dialog from memory
          $FolderBrowser.Dispose()

          return $result
          }

          Get-FolderName


          You can also opt for using the Shell.Application object with something like this:



          # Show an Open Folder Dialog and return the directory selected by the user.
          function Get-FolderName {
          [CmdletBinding()]
          param (
          [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
          [string]$Message = "Select a directory.",

          [string]$InitialDirectory = [System.Environment+SpecialFolder]::MyComputer,

          [switch]$ShowNewFolderButton
          )

          $browserForFolderOptions = 0x00000041 # BIF_RETURNONLYFSDIRS -bor BIF_NEWDIALOGSTYLE
          if (!$ShowNewFolderButton) { $browserForFolderOptions += 0x00000200 } # BIF_NONEWFOLDERBUTTON

          $browser = New-Object -ComObject Shell.Application
          # To make the dialog topmost, you need to supply the Window handle of the current process
          [intPtr]$handle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle

          # see: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773205(v=vs.85).aspx
          $folder = $browser.BrowseForFolder($handle, $Message, $browserForFolderOptions, $InitialDirectory)

          $result = $null
          if ($folder) {
          $result = $folder.Self.Path
          }

          # Release and remove the used Com object from memory
          [System.Runtime.Interopservices.Marshal]::ReleaseComObject($browser) | Out-Null
          [System.GC]::Collect()
          [System.GC]::WaitForPendingFinalizers()


          return $result
          }

          $folder = Get-FolderName
          if ($folder) { Write-Host "You selected the directory: $folder" }
          else { "You did not select a directory." }





          share|improve this answer


























          • Hi Theo, many thanks for helping and providing this code. I've had to put this requirement at the back of the list due to deadlines but will revisit when I can. Apologies for the late reply but this is appreciated.

            – jshizzle
            Jan 7 at 10:12












          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54037292%2ffolderbrowserdialog-bring-to-front%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          Hope this helps



          Add-Type -AssemblyName System.Windows.Forms
          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
          $FolderBrowser.Description = 'Select the folder containing the data'
          $result = $FolderBrowser.ShowDialog((New-Object System.Windows.Forms.Form -Property @{TopMost = $true }))
          if ($result -eq [Windows.Forms.DialogResult]::OK){
          $FolderBrowser.SelectedPath
          } else {
          exit
          }


          //Edit to comment



          There are 2 variants (overloads) of the ShowDialog () method.



          See documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.showdialog%28v=vs.110%29.aspx



          In the second variant, you can specify the window that should be the mother of the dialogue.



          Topmost should be used sparingly or not at all! If multiple windows are topmost then which is topmost? ;-))
          First try to set your window as a mother then the OpenfileDialog / SaveFileDialog should always appear above your window:



          $openFileDialog1.ShowDialog($form1)


          If that's not enough, take Topmost.



          Your dialogue window inherits the properties from the mother. If your mother window is topmost, then the dialog is also topmost.



          Here is an example that sets the dialogue Topmost.



          In this example, however, a new unbound window is used, so the dialog is unbound.



          $openFileDialog1.ShowDialog((New - Object System.Windows.Forms.Form - Property @{TopMost = $true; TopLevel = $true}))





          share|improve this answer


























          • Ok, so I did find this method on my searches but it didn't always appear to work and just seemed to stop vscode from accepting key entry in the console for a credential call after. Was hoping to add "TopMost = $true" to my list of properties in the original code I provided but didn't doesn't like it and can't see why if it can be used in yours...?

            – jshizzle
            Jan 4 at 10:49











          • @jshizzle see the edit ;-)

            – Jaapaap
            Jan 4 at 11:02











          • @Jaapaap Unfortunately, your edit is all about the OpenFileDialog, not the FolderBrowserDialog

            – Theo
            Jan 4 at 14:54
















          2














          Hope this helps



          Add-Type -AssemblyName System.Windows.Forms
          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
          $FolderBrowser.Description = 'Select the folder containing the data'
          $result = $FolderBrowser.ShowDialog((New-Object System.Windows.Forms.Form -Property @{TopMost = $true }))
          if ($result -eq [Windows.Forms.DialogResult]::OK){
          $FolderBrowser.SelectedPath
          } else {
          exit
          }


          //Edit to comment



          There are 2 variants (overloads) of the ShowDialog () method.



          See documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.showdialog%28v=vs.110%29.aspx



          In the second variant, you can specify the window that should be the mother of the dialogue.



          Topmost should be used sparingly or not at all! If multiple windows are topmost then which is topmost? ;-))
          First try to set your window as a mother then the OpenfileDialog / SaveFileDialog should always appear above your window:



          $openFileDialog1.ShowDialog($form1)


          If that's not enough, take Topmost.



          Your dialogue window inherits the properties from the mother. If your mother window is topmost, then the dialog is also topmost.



          Here is an example that sets the dialogue Topmost.



          In this example, however, a new unbound window is used, so the dialog is unbound.



          $openFileDialog1.ShowDialog((New - Object System.Windows.Forms.Form - Property @{TopMost = $true; TopLevel = $true}))





          share|improve this answer


























          • Ok, so I did find this method on my searches but it didn't always appear to work and just seemed to stop vscode from accepting key entry in the console for a credential call after. Was hoping to add "TopMost = $true" to my list of properties in the original code I provided but didn't doesn't like it and can't see why if it can be used in yours...?

            – jshizzle
            Jan 4 at 10:49











          • @jshizzle see the edit ;-)

            – Jaapaap
            Jan 4 at 11:02











          • @Jaapaap Unfortunately, your edit is all about the OpenFileDialog, not the FolderBrowserDialog

            – Theo
            Jan 4 at 14:54














          2












          2








          2







          Hope this helps



          Add-Type -AssemblyName System.Windows.Forms
          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
          $FolderBrowser.Description = 'Select the folder containing the data'
          $result = $FolderBrowser.ShowDialog((New-Object System.Windows.Forms.Form -Property @{TopMost = $true }))
          if ($result -eq [Windows.Forms.DialogResult]::OK){
          $FolderBrowser.SelectedPath
          } else {
          exit
          }


          //Edit to comment



          There are 2 variants (overloads) of the ShowDialog () method.



          See documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.showdialog%28v=vs.110%29.aspx



          In the second variant, you can specify the window that should be the mother of the dialogue.



          Topmost should be used sparingly or not at all! If multiple windows are topmost then which is topmost? ;-))
          First try to set your window as a mother then the OpenfileDialog / SaveFileDialog should always appear above your window:



          $openFileDialog1.ShowDialog($form1)


          If that's not enough, take Topmost.



          Your dialogue window inherits the properties from the mother. If your mother window is topmost, then the dialog is also topmost.



          Here is an example that sets the dialogue Topmost.



          In this example, however, a new unbound window is used, so the dialog is unbound.



          $openFileDialog1.ShowDialog((New - Object System.Windows.Forms.Form - Property @{TopMost = $true; TopLevel = $true}))





          share|improve this answer















          Hope this helps



          Add-Type -AssemblyName System.Windows.Forms
          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog
          $FolderBrowser.Description = 'Select the folder containing the data'
          $result = $FolderBrowser.ShowDialog((New-Object System.Windows.Forms.Form -Property @{TopMost = $true }))
          if ($result -eq [Windows.Forms.DialogResult]::OK){
          $FolderBrowser.SelectedPath
          } else {
          exit
          }


          //Edit to comment



          There are 2 variants (overloads) of the ShowDialog () method.



          See documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.openfiledialog.showdialog%28v=vs.110%29.aspx



          In the second variant, you can specify the window that should be the mother of the dialogue.



          Topmost should be used sparingly or not at all! If multiple windows are topmost then which is topmost? ;-))
          First try to set your window as a mother then the OpenfileDialog / SaveFileDialog should always appear above your window:



          $openFileDialog1.ShowDialog($form1)


          If that's not enough, take Topmost.



          Your dialogue window inherits the properties from the mother. If your mother window is topmost, then the dialog is also topmost.



          Here is an example that sets the dialogue Topmost.



          In this example, however, a new unbound window is used, so the dialog is unbound.



          $openFileDialog1.ShowDialog((New - Object System.Windows.Forms.Form - Property @{TopMost = $true; TopLevel = $true}))






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 4 at 11:01

























          answered Jan 4 at 10:44









          JaapaapJaapaap

          1865




          1865













          • Ok, so I did find this method on my searches but it didn't always appear to work and just seemed to stop vscode from accepting key entry in the console for a credential call after. Was hoping to add "TopMost = $true" to my list of properties in the original code I provided but didn't doesn't like it and can't see why if it can be used in yours...?

            – jshizzle
            Jan 4 at 10:49











          • @jshizzle see the edit ;-)

            – Jaapaap
            Jan 4 at 11:02











          • @Jaapaap Unfortunately, your edit is all about the OpenFileDialog, not the FolderBrowserDialog

            – Theo
            Jan 4 at 14:54



















          • Ok, so I did find this method on my searches but it didn't always appear to work and just seemed to stop vscode from accepting key entry in the console for a credential call after. Was hoping to add "TopMost = $true" to my list of properties in the original code I provided but didn't doesn't like it and can't see why if it can be used in yours...?

            – jshizzle
            Jan 4 at 10:49











          • @jshizzle see the edit ;-)

            – Jaapaap
            Jan 4 at 11:02











          • @Jaapaap Unfortunately, your edit is all about the OpenFileDialog, not the FolderBrowserDialog

            – Theo
            Jan 4 at 14:54

















          Ok, so I did find this method on my searches but it didn't always appear to work and just seemed to stop vscode from accepting key entry in the console for a credential call after. Was hoping to add "TopMost = $true" to my list of properties in the original code I provided but didn't doesn't like it and can't see why if it can be used in yours...?

          – jshizzle
          Jan 4 at 10:49





          Ok, so I did find this method on my searches but it didn't always appear to work and just seemed to stop vscode from accepting key entry in the console for a credential call after. Was hoping to add "TopMost = $true" to my list of properties in the original code I provided but didn't doesn't like it and can't see why if it can be used in yours...?

          – jshizzle
          Jan 4 at 10:49













          @jshizzle see the edit ;-)

          – Jaapaap
          Jan 4 at 11:02





          @jshizzle see the edit ;-)

          – Jaapaap
          Jan 4 at 11:02













          @Jaapaap Unfortunately, your edit is all about the OpenFileDialog, not the FolderBrowserDialog

          – Theo
          Jan 4 at 14:54





          @Jaapaap Unfortunately, your edit is all about the OpenFileDialog, not the FolderBrowserDialog

          – Theo
          Jan 4 at 14:54













          1














          A reliable way of doing this is to add a piece of C# code to the function.
          With that code, you can get a Windows handle that implements the IWin32Window interface. Using that handle in the ShowDialog function will ensure the dialog is displayed on top.



          Function Get-FolderName {   
          # To ensure the dialog window shows in the foreground, you need to get a Window Handle from the owner process.
          # This handle must implement System.Windows.Forms.IWin32Window
          # Create a wrapper class that implements IWin32Window.
          # The IWin32Window interface contains only a single property that must be implemented to expose the underlying handle.
          $code = @"
          using System;
          using System.Windows.Forms;

          public class Win32Window : IWin32Window
          {
          public Win32Window(IntPtr handle)
          {
          Handle = handle;
          }

          public IntPtr Handle { get; private set; }
          }
          "@

          if (-not ([System.Management.Automation.PSTypeName]'Win32Window').Type) {
          Add-Type -TypeDefinition $code -ReferencedAssemblies System.Windows.Forms.dll -Language CSharp
          }
          # Get the window handle from the current process
          # $owner = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
          # Or write like this:
          $owner = [Win32Window]::new([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)

          # Or use the the window handle from the desktop
          # $owner = New-Object Win32Window -ArgumentList (Get-Process -Name explorer).MainWindowHandle
          # Or write like this:
          # $owner = [Win32Window]::new((Get-Process -Name explorer).MainWindowHandle)

          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
          SelectedPath = 'C:Temp'
          ShowNewFolderButton = $false
          Description = "Select Staging Folder."
          }
          # set the return value only if a selection was made
          $result = $null
          If ($FolderBrowser.ShowDialog($owner) -eq "OK") {
          $result = $FolderBrowser.SelectedPath
          }
          # clear the dialog from memory
          $FolderBrowser.Dispose()

          return $result
          }

          Get-FolderName


          You can also opt for using the Shell.Application object with something like this:



          # Show an Open Folder Dialog and return the directory selected by the user.
          function Get-FolderName {
          [CmdletBinding()]
          param (
          [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
          [string]$Message = "Select a directory.",

          [string]$InitialDirectory = [System.Environment+SpecialFolder]::MyComputer,

          [switch]$ShowNewFolderButton
          )

          $browserForFolderOptions = 0x00000041 # BIF_RETURNONLYFSDIRS -bor BIF_NEWDIALOGSTYLE
          if (!$ShowNewFolderButton) { $browserForFolderOptions += 0x00000200 } # BIF_NONEWFOLDERBUTTON

          $browser = New-Object -ComObject Shell.Application
          # To make the dialog topmost, you need to supply the Window handle of the current process
          [intPtr]$handle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle

          # see: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773205(v=vs.85).aspx
          $folder = $browser.BrowseForFolder($handle, $Message, $browserForFolderOptions, $InitialDirectory)

          $result = $null
          if ($folder) {
          $result = $folder.Self.Path
          }

          # Release and remove the used Com object from memory
          [System.Runtime.Interopservices.Marshal]::ReleaseComObject($browser) | Out-Null
          [System.GC]::Collect()
          [System.GC]::WaitForPendingFinalizers()


          return $result
          }

          $folder = Get-FolderName
          if ($folder) { Write-Host "You selected the directory: $folder" }
          else { "You did not select a directory." }





          share|improve this answer


























          • Hi Theo, many thanks for helping and providing this code. I've had to put this requirement at the back of the list due to deadlines but will revisit when I can. Apologies for the late reply but this is appreciated.

            – jshizzle
            Jan 7 at 10:12
















          1














          A reliable way of doing this is to add a piece of C# code to the function.
          With that code, you can get a Windows handle that implements the IWin32Window interface. Using that handle in the ShowDialog function will ensure the dialog is displayed on top.



          Function Get-FolderName {   
          # To ensure the dialog window shows in the foreground, you need to get a Window Handle from the owner process.
          # This handle must implement System.Windows.Forms.IWin32Window
          # Create a wrapper class that implements IWin32Window.
          # The IWin32Window interface contains only a single property that must be implemented to expose the underlying handle.
          $code = @"
          using System;
          using System.Windows.Forms;

          public class Win32Window : IWin32Window
          {
          public Win32Window(IntPtr handle)
          {
          Handle = handle;
          }

          public IntPtr Handle { get; private set; }
          }
          "@

          if (-not ([System.Management.Automation.PSTypeName]'Win32Window').Type) {
          Add-Type -TypeDefinition $code -ReferencedAssemblies System.Windows.Forms.dll -Language CSharp
          }
          # Get the window handle from the current process
          # $owner = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
          # Or write like this:
          $owner = [Win32Window]::new([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)

          # Or use the the window handle from the desktop
          # $owner = New-Object Win32Window -ArgumentList (Get-Process -Name explorer).MainWindowHandle
          # Or write like this:
          # $owner = [Win32Window]::new((Get-Process -Name explorer).MainWindowHandle)

          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
          SelectedPath = 'C:Temp'
          ShowNewFolderButton = $false
          Description = "Select Staging Folder."
          }
          # set the return value only if a selection was made
          $result = $null
          If ($FolderBrowser.ShowDialog($owner) -eq "OK") {
          $result = $FolderBrowser.SelectedPath
          }
          # clear the dialog from memory
          $FolderBrowser.Dispose()

          return $result
          }

          Get-FolderName


          You can also opt for using the Shell.Application object with something like this:



          # Show an Open Folder Dialog and return the directory selected by the user.
          function Get-FolderName {
          [CmdletBinding()]
          param (
          [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
          [string]$Message = "Select a directory.",

          [string]$InitialDirectory = [System.Environment+SpecialFolder]::MyComputer,

          [switch]$ShowNewFolderButton
          )

          $browserForFolderOptions = 0x00000041 # BIF_RETURNONLYFSDIRS -bor BIF_NEWDIALOGSTYLE
          if (!$ShowNewFolderButton) { $browserForFolderOptions += 0x00000200 } # BIF_NONEWFOLDERBUTTON

          $browser = New-Object -ComObject Shell.Application
          # To make the dialog topmost, you need to supply the Window handle of the current process
          [intPtr]$handle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle

          # see: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773205(v=vs.85).aspx
          $folder = $browser.BrowseForFolder($handle, $Message, $browserForFolderOptions, $InitialDirectory)

          $result = $null
          if ($folder) {
          $result = $folder.Self.Path
          }

          # Release and remove the used Com object from memory
          [System.Runtime.Interopservices.Marshal]::ReleaseComObject($browser) | Out-Null
          [System.GC]::Collect()
          [System.GC]::WaitForPendingFinalizers()


          return $result
          }

          $folder = Get-FolderName
          if ($folder) { Write-Host "You selected the directory: $folder" }
          else { "You did not select a directory." }





          share|improve this answer


























          • Hi Theo, many thanks for helping and providing this code. I've had to put this requirement at the back of the list due to deadlines but will revisit when I can. Apologies for the late reply but this is appreciated.

            – jshizzle
            Jan 7 at 10:12














          1












          1








          1







          A reliable way of doing this is to add a piece of C# code to the function.
          With that code, you can get a Windows handle that implements the IWin32Window interface. Using that handle in the ShowDialog function will ensure the dialog is displayed on top.



          Function Get-FolderName {   
          # To ensure the dialog window shows in the foreground, you need to get a Window Handle from the owner process.
          # This handle must implement System.Windows.Forms.IWin32Window
          # Create a wrapper class that implements IWin32Window.
          # The IWin32Window interface contains only a single property that must be implemented to expose the underlying handle.
          $code = @"
          using System;
          using System.Windows.Forms;

          public class Win32Window : IWin32Window
          {
          public Win32Window(IntPtr handle)
          {
          Handle = handle;
          }

          public IntPtr Handle { get; private set; }
          }
          "@

          if (-not ([System.Management.Automation.PSTypeName]'Win32Window').Type) {
          Add-Type -TypeDefinition $code -ReferencedAssemblies System.Windows.Forms.dll -Language CSharp
          }
          # Get the window handle from the current process
          # $owner = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
          # Or write like this:
          $owner = [Win32Window]::new([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)

          # Or use the the window handle from the desktop
          # $owner = New-Object Win32Window -ArgumentList (Get-Process -Name explorer).MainWindowHandle
          # Or write like this:
          # $owner = [Win32Window]::new((Get-Process -Name explorer).MainWindowHandle)

          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
          SelectedPath = 'C:Temp'
          ShowNewFolderButton = $false
          Description = "Select Staging Folder."
          }
          # set the return value only if a selection was made
          $result = $null
          If ($FolderBrowser.ShowDialog($owner) -eq "OK") {
          $result = $FolderBrowser.SelectedPath
          }
          # clear the dialog from memory
          $FolderBrowser.Dispose()

          return $result
          }

          Get-FolderName


          You can also opt for using the Shell.Application object with something like this:



          # Show an Open Folder Dialog and return the directory selected by the user.
          function Get-FolderName {
          [CmdletBinding()]
          param (
          [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
          [string]$Message = "Select a directory.",

          [string]$InitialDirectory = [System.Environment+SpecialFolder]::MyComputer,

          [switch]$ShowNewFolderButton
          )

          $browserForFolderOptions = 0x00000041 # BIF_RETURNONLYFSDIRS -bor BIF_NEWDIALOGSTYLE
          if (!$ShowNewFolderButton) { $browserForFolderOptions += 0x00000200 } # BIF_NONEWFOLDERBUTTON

          $browser = New-Object -ComObject Shell.Application
          # To make the dialog topmost, you need to supply the Window handle of the current process
          [intPtr]$handle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle

          # see: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773205(v=vs.85).aspx
          $folder = $browser.BrowseForFolder($handle, $Message, $browserForFolderOptions, $InitialDirectory)

          $result = $null
          if ($folder) {
          $result = $folder.Self.Path
          }

          # Release and remove the used Com object from memory
          [System.Runtime.Interopservices.Marshal]::ReleaseComObject($browser) | Out-Null
          [System.GC]::Collect()
          [System.GC]::WaitForPendingFinalizers()


          return $result
          }

          $folder = Get-FolderName
          if ($folder) { Write-Host "You selected the directory: $folder" }
          else { "You did not select a directory." }





          share|improve this answer















          A reliable way of doing this is to add a piece of C# code to the function.
          With that code, you can get a Windows handle that implements the IWin32Window interface. Using that handle in the ShowDialog function will ensure the dialog is displayed on top.



          Function Get-FolderName {   
          # To ensure the dialog window shows in the foreground, you need to get a Window Handle from the owner process.
          # This handle must implement System.Windows.Forms.IWin32Window
          # Create a wrapper class that implements IWin32Window.
          # The IWin32Window interface contains only a single property that must be implemented to expose the underlying handle.
          $code = @"
          using System;
          using System.Windows.Forms;

          public class Win32Window : IWin32Window
          {
          public Win32Window(IntPtr handle)
          {
          Handle = handle;
          }

          public IntPtr Handle { get; private set; }
          }
          "@

          if (-not ([System.Management.Automation.PSTypeName]'Win32Window').Type) {
          Add-Type -TypeDefinition $code -ReferencedAssemblies System.Windows.Forms.dll -Language CSharp
          }
          # Get the window handle from the current process
          # $owner = New-Object Win32Window -ArgumentList ([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)
          # Or write like this:
          $owner = [Win32Window]::new([System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle)

          # Or use the the window handle from the desktop
          # $owner = New-Object Win32Window -ArgumentList (Get-Process -Name explorer).MainWindowHandle
          # Or write like this:
          # $owner = [Win32Window]::new((Get-Process -Name explorer).MainWindowHandle)

          $FolderBrowser = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
          SelectedPath = 'C:Temp'
          ShowNewFolderButton = $false
          Description = "Select Staging Folder."
          }
          # set the return value only if a selection was made
          $result = $null
          If ($FolderBrowser.ShowDialog($owner) -eq "OK") {
          $result = $FolderBrowser.SelectedPath
          }
          # clear the dialog from memory
          $FolderBrowser.Dispose()

          return $result
          }

          Get-FolderName


          You can also opt for using the Shell.Application object with something like this:



          # Show an Open Folder Dialog and return the directory selected by the user.
          function Get-FolderName {
          [CmdletBinding()]
          param (
          [Parameter(Mandatory=$false, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, Position=0)]
          [string]$Message = "Select a directory.",

          [string]$InitialDirectory = [System.Environment+SpecialFolder]::MyComputer,

          [switch]$ShowNewFolderButton
          )

          $browserForFolderOptions = 0x00000041 # BIF_RETURNONLYFSDIRS -bor BIF_NEWDIALOGSTYLE
          if (!$ShowNewFolderButton) { $browserForFolderOptions += 0x00000200 } # BIF_NONEWFOLDERBUTTON

          $browser = New-Object -ComObject Shell.Application
          # To make the dialog topmost, you need to supply the Window handle of the current process
          [intPtr]$handle = [System.Diagnostics.Process]::GetCurrentProcess().MainWindowHandle

          # see: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773205(v=vs.85).aspx
          $folder = $browser.BrowseForFolder($handle, $Message, $browserForFolderOptions, $InitialDirectory)

          $result = $null
          if ($folder) {
          $result = $folder.Self.Path
          }

          # Release and remove the used Com object from memory
          [System.Runtime.Interopservices.Marshal]::ReleaseComObject($browser) | Out-Null
          [System.GC]::Collect()
          [System.GC]::WaitForPendingFinalizers()


          return $result
          }

          $folder = Get-FolderName
          if ($folder) { Write-Host "You selected the directory: $folder" }
          else { "You did not select a directory." }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jan 4 at 14:54

























          answered Jan 4 at 11:38









          TheoTheo

          6,5143521




          6,5143521













          • Hi Theo, many thanks for helping and providing this code. I've had to put this requirement at the back of the list due to deadlines but will revisit when I can. Apologies for the late reply but this is appreciated.

            – jshizzle
            Jan 7 at 10:12



















          • Hi Theo, many thanks for helping and providing this code. I've had to put this requirement at the back of the list due to deadlines but will revisit when I can. Apologies for the late reply but this is appreciated.

            – jshizzle
            Jan 7 at 10:12

















          Hi Theo, many thanks for helping and providing this code. I've had to put this requirement at the back of the list due to deadlines but will revisit when I can. Apologies for the late reply but this is appreciated.

          – jshizzle
          Jan 7 at 10:12





          Hi Theo, many thanks for helping and providing this code. I've had to put this requirement at the back of the list due to deadlines but will revisit when I can. Apologies for the late reply but this is appreciated.

          – jshizzle
          Jan 7 at 10:12


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54037292%2ffolderbrowserdialog-bring-to-front%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Monofisismo

          Angular Downloading a file using contenturl with Basic Authentication

          Olmecas