elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Guía rápida para descarga de herramientas gratuitas de seguridad y desinfección


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP) (Moderador: kub0x)
| | | |-+  Control para seleccionar Carpetas [Solucionado]
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Control para seleccionar Carpetas [Solucionado]  (Leído 6,706 veces)
Maurice_Lupin


Desconectado Desconectado

Mensajes: 356

GPS


Ver Perfil WWW
Control para seleccionar Carpetas [Solucionado]
« en: 22 Febrero 2014, 23:53 pm »

Hola, estoy buscando un control que me permita seleccionar carpetas, no quiero utilizar el FolderBrowserDialog pues es un lio explorar.

Se puede utilizar el control OpenFileDialog para seleccionar carpetas?. Si alguien tiene un link, info... que pueda compartir, quizá algun control personalizado.

Lo último que se me ocurre es usar el SaveFileDialog.

Saludos.



 ;D buscando en ingles, encontré lo que buscaba.




link: http://www.codeproject.com/Articles/44914/Select-file-or-folder-from-the-same-dialog

comparto el code, quizá a alguien le interese.

Código
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Runtime.InteropServices;
  5. using System.Reflection;
  6. using System.IO;
  7. using System.Windows.Forms;
  8.  
  9. public class FileFolderDialog : CommonDialog
  10. {
  11. private OpenFileDialog dialog = new OpenFileDialog();
  12.  
  13. public OpenFileDialog Dialog
  14. {
  15. get { return dialog; }
  16. set { dialog = value; }
  17. }
  18.  
  19. public new DialogResult ShowDialog()
  20. {
  21. return this.ShowDialog(null);
  22. }
  23.  
  24. public new DialogResult ShowDialog(IWin32Window owner)
  25. {
  26. // Set validate names to false otherwise windows will not let you select "Folder Selection."
  27. dialog.ValidateNames = false;
  28. dialog.CheckFileExists = false;
  29. dialog.CheckPathExists = true;
  30.  
  31. try
  32. {
  33. // Set initial directory (used when dialog.FileName is set from outside)
  34. if (dialog.FileName != null && dialog.FileName != "")
  35. {
  36. if (Directory.Exists(dialog.FileName))
  37. dialog.InitialDirectory = dialog.FileName;
  38. else
  39. dialog.InitialDirectory = Path.GetDirectoryName(dialog.FileName);
  40. }
  41. }
  42. catch (Exception ex)
  43. {
  44. // Do nothing
  45. }
  46.  
  47. // Always default to Folder Selection.
  48. dialog.FileName = "Folder Selection.";
  49.  
  50. if (owner == null)
  51. return dialog.ShowDialog();
  52. else
  53. return dialog.ShowDialog(owner);
  54. }
  55.  
  56. /// <summary>
  57. // Helper property. Parses FilePath into either folder path (if Folder Selection. is set)
  58. // or returns file path
  59. /// </summary>
  60. public string SelectedPath
  61. {
  62. get {
  63. try
  64. {
  65. if (dialog.FileName != null &&
  66. (dialog.FileName.EndsWith("Folder Selection.") || !File.Exists(dialog.FileName)) &&
  67. !Directory.Exists(dialog.FileName))
  68. {
  69. return Path.GetDirectoryName(dialog.FileName);
  70. }
  71. else
  72. {
  73. return dialog.FileName;
  74. }
  75. }
  76. catch (Exception ex)
  77. {
  78. return dialog.FileName;
  79. }
  80. }
  81. set
  82. {
  83. if (value != null && value != "")
  84. {
  85. dialog.FileName = value;
  86. }
  87. }
  88. }
  89.  
  90. /// <summary>
  91. /// When multiple files are selected returns them as semi-colon seprated string
  92. /// </summary>
  93. public string SelectedPaths
  94. {
  95. get {
  96. if (dialog.FileNames != null && dialog.FileNames.Length > 1)
  97. {
  98. StringBuilder sb = new StringBuilder();
  99. foreach (string fileName in dialog.FileNames)
  100. {
  101. try
  102. {
  103. if (File.Exists(fileName))
  104. sb.Append(fileName + ";");
  105. }
  106. catch (Exception ex)
  107. {
  108. // Go to next
  109. }
  110. }
  111. return sb.ToString();
  112. }
  113. else
  114. {
  115. return null;
  116. }
  117. }
  118. }
  119.  
  120. public override void Reset()
  121. {
  122. dialog.Reset();
  123. }
  124.  
  125. protected override bool RunDialog(IntPtr hwndOwner)
  126. {
  127. return true;
  128. }
  129. }

uso:
Código
  1. FileFolderDialog ffD = new FileFolderDialog();
  2. ffD.ShowDialog(this);

Saludos.


« Última modificación: 23 Febrero 2014, 01:18 am por Eleкtro » En línea

Un error se comete al equivocarse.
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.810



Ver Perfil
Re: Control para seleccionar Carpetas [Solucionado]
« Respuesta #1 en: 23 Febrero 2014, 01:18 am »

(Porfavor la próxima vez no hagas doble post, utiliza el botón MODIFICAR)



Tienes toda la razón del mundo, es un coñazo usar el FolderBrowserDialog, yo lo veo como un diálogo obsoleto y dificil de manejar, con muy poco rendimiento, ya que con el diálogo de carpetas de Windows puedes acceder a una ubicación en 5 segundos escribiendo la ubicación o usando las ubicaciones favoritas, mientras que con el FolderBrowserDialog pierdes mucho más tiempo expandiendo carpetas ...una por una.
Es una completa basura.

La solución de terceros que has mostrado ....bueno, es una solución y es customizable, pero no tiene ventajas sobre la navegación de directorios, debería customizarse en más aspectos la Class ...cosa que resultaría laboriosa. Así que sin ánimo de ofender al autor del código, me parece algo muy cutre heredar un 'CommonDialog' para hacer sólamente eso.

Te propongo algo más eficiente, usando la librería Windows API Code Pack que provee Microsoft.

Te muestro un ejemplo de uso:

Código
  1.    ' WindowsAPICodePack 'CommonOpenFileDialog' Example.
  2.    ' ( By Elektro )
  3.    '
  4.    ' Instructions:
  5.    ' 1. Reference "Microsoft.WindowsAPICodePack.dll" and "Microsoft.WindowsAPICodePack.Shell.dll".
  6.  
  7.    Imports Microsoft.WindowsAPICodePack.Dialogs
  8.    Imports Microsoft.WindowsAPICodePack.Shell
  9.  
  10.    ''' <summary>
  11.    ''' The WindowsAPICodePack 'CommonOpenFileDialog' instance.
  12.    ''' </summary>
  13.    Private WithEvents FolderPicker As New CommonOpenFileDialog With
  14.        {
  15.            .Title = "Folder Picker Test",
  16.            .DefaultDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}",
  17.            .InitialDirectory = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}",
  18.            .DefaultFileName = "C:\",
  19.            .IsFolderPicker = True,
  20.            .Multiselect = False,
  21.            .ShowPlacesList = True,
  22.            .ShowHiddenItems = True,
  23.            .EnsurePathExists = True,
  24.            .RestoreDirectory = False,
  25.            .NavigateToShortcut = True,
  26.            .AllowNonFileSystemItems = True,
  27.            .AddToMostRecentlyUsedList = True
  28.        }
  29.  
  30.    ''' <summary>
  31.    ''' Handles the Click event of the Button1 control.
  32.    ''' </summary>
  33.    ''' <param name="sender">The source of the event.</param>
  34.    ''' <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
  35.    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
  36.  
  37.        ' If folder is picked then...
  38.        If FolderPicker.ShowDialog() = CommonFileDialogResult.Ok Then
  39.  
  40.            Dim SelectedFolder As ShellObject = FolderPicker.FileAsShellObject
  41.            MsgBox(SelectedFolder.GetDisplayName(DisplayNameType.FileSystemPath))
  42.  
  43.        End If
  44.  
  45.        ' FolderPicker.Dispose()
  46.  
  47.    End Sub
  48.  
  49.    ''' <summary>
  50.    ''' Handles the FolderChanging event of the FolderPicker control.
  51.    ''' </summary>
  52.    ''' <param name="sender">The source of the event.</param>
  53.    ''' <param name="e">The <see cref="Microsoft.WindowsAPICodePack.Dialogs.CommonFileDialogFolderChangeEventArgs"/> instance containing the event data.</param>
  54.    Private Sub FolderPicker_FolderChanging(sender As Object, e As CommonFileDialogFolderChangeEventArgs) _
  55.    Handles FolderPicker.FolderChanging
  56.  
  57.        ' Restrict the navigation on specific folders.
  58.        Select Case True
  59.  
  60.            Case e.Folder = Environment.GetFolderPath(Environment.SpecialFolder.Windows)
  61.                '  Restricts the navigation to 'Windows' directory.
  62.                e.Cancel = True
  63.  
  64.            Case e.Folder.Equals("C:\Juegos", StringComparison.CurrentCultureIgnoreCase)
  65.                ' Restricts the navigation to 'C:\Juegos' directory.
  66.                e.Cancel = True
  67.  
  68.            Case e.Folder.Split("\").Last.Equals("Administrador", StringComparison.CurrentCultureIgnoreCase)
  69.                ' Restricts the navigation to any directory name ending in "Administrador" keyword.
  70.                e.Cancel = True
  71.  
  72.            Case Else
  73.                ' Allow navigation on that directory.
  74.                e.Cancel = False
  75.  
  76.        End Select
  77.  
  78.    End Sub

PD: Y si no quieres depender de librerías siempre puedes sacar la parte importante del código fuente que va incluido.
PD: Además, ese kit de librerías en el futuro te proporcionarían ventajas y comodidades para usar otros tipos de controles y classes muy interesantes.

O también puedes usar la librería Ooki Dialogs, que son diálogos basados en Windows VISTA y es la librería que yo usaba como reemplazamiento del 'FolderBrowserDialog', antes de conocer la existencia de 'WindowsAPICodePack'.

Un mini ejemplo de uso:

Código
  1.  Dim FolderPicker As New Ookii.Dialogs.VistaFolderBrowserDialog
  2.  FolderPicker.ShowNewFolderButton = True
  3.  
  4.  If FolderPicker.ShowDialog.ToString() = "OK" Then
  5.      msgbox(FolderPicker.SelectedPath)
  6.  End If
  7.  
  8.  ' FolderPicker.Dispose()

Saludos.


« Última modificación: 23 Febrero 2014, 01:35 am por Eleкtro » En línea

Maurice_Lupin


Desconectado Desconectado

Mensajes: 356

GPS


Ver Perfil WWW
Re: Control para seleccionar Carpetas [Solucionado]
« Respuesta #2 en: 24 Febrero 2014, 00:17 am »

Hola, Elektro.
No me había dado cuenta que hice doble post, lo siento. Interesante la libreria que comentas, me la bajé completa, estoy dandole una ojeada.

Me has hecho recordar que se puede usar la API también. Encontré esta info:

http://vbnet.mvps.org/index.html?code/hooks/fileopensavedlghookadvtext.htm

Está en vb6 pero usando http://www.pinvoke.net se puede implementar en vb.net, si puedo estos dias lo adapto.




Me parece laborioso pero, ummm las posibilidades son buenisimas.

Saludos y gracias por responder.
« Última modificación: 24 Febrero 2014, 01:25 am por Maurice_Lupin » En línea

Un error se comete al equivocarse.
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines