Page 1 of 1

Reconocer puerta USB

PostPosted: Mon Oct 01, 2012 12:11 am
by daniel_halon
Hola amigos, estoy haciendo un programa y necesito realizar una copia de seguridad en un PenDrive, mi cliente entiende poco y nada de computadores. La idea es abrir una Listbox com aDrives() y seleccionar la unidad del pendrive.
Code: Select all  Expand view

 @ 1, 1 LISTBOX cDrive ITEMS aDrives(2) SIZE 100, 100 OF oDlg ;
      ON DBLCLICK (msginfo(cDrive), oDlg:End())
 

Solo que en la listBox no se como agregar al lado de la unidad el texto Drice C o USB etc.
Existe algun comando como IsCdroom() que sea IsUSB ?, o alguna ayuda sobre el tema?

Desde ya muchas gracias, Daniel

Re: Reconocer puerta USB

PostPosted: Mon Oct 01, 2012 2:57 pm
by FiveWiDi
Code: Select all  Expand view
/* *************************** */
FUNCTION cSelectUSB( lMensaje )

Local aDriveUSB := {}
Local nDriveUSB := 0
Local cDriveUSB := ""
Local nContador := 0

aDriveUSB := aUSBDrive()

If Len( aDriveUSB ) = 0
    If lMensaje
        MsgAlert( GetTrad("No hi han unitats USB disponibles, insereixi una unitat USB."), GetTrad("A T E N C I Ó !" ) )
    EndIf
  Else

    nDriveUSB := MsgList( aDriveUSB, GetTrad("Unitats USB disponibles:"), Nil, Nil, Nil, 15, "Seleccionar", nDriveUSB, .T., Nil )

    //Traza( 1, nDriveUSB := MsgList( aDriveUSB, GetTrad("Unitats USB disponibles:"), Nil, Nil, Nil, 15, "Seleccionar", nDriveUSB, .T., Nil ) )

    If nDriveUSB > 0
        cDriveUSB := SubStr( aDriveUSB[ nDriveUSB ], 1, 3 )
   
        //Traza(1, "aDriveUSB[ nDriveUSB ]=", aDriveUSB[ nDriveUSB ])

    EndIf
   
EndIf

//Traza(1, "cDriveUSB=", cDriveUSB)

Return cDriveUSB
/* *************************** */

/* ************************************
   Torna una array dels USB connectats.
   --------------------------------- */


#define DRIVE_REMOVABLE  2

STATIC FUNCTION aUSBDrive()
Local nBitDrives := GetLogicalDrives()
Local nContador  := 0
Local cDrive     := ""
Local aDrives    := {}

For nContador := 1 to 32
    If lAnd( nBitDrives, 2 ^ ( nContador - 1 ) )
        cDrive = Chr( Asc( "A" ) - 1 + nContador ) + ":\"
        If nContador != 1 .and. GetDriveType( cDrive ) == DRIVE_REMOVABLE

            If lExistUSB( cDrive )
                AAdd( aDrives, cDrive )
            EndIf

        Endif
    Endif
Next

Return aDrives
/* *************************** */
/* *************************** */
FUNCTION lExistUSB( cDisk )
/* Se da el caso de que con un PenDrive (al menos el que yo he usado) las
funciones IsDisk() y lIsDir() dan .F..
Cuando se trata de una tarjeta de memoria (por ejemplo XD) insertada en
un lector de tarjetas externo conectado a un puerto USB, la IsDisk() sigue
dando .F. y la lIsDir() da .T..
Como lo que se pretende es poder saber que unidades USB son susceptibles de
usarse independientemente de PenDrive o tarjetas de memoria, se opta por
la función GetDiskFreeSpace() que da .T. tanto para PenDrive como para
tarjetas de memoria.
22/08/2010
*/

Local lExist        := .F.
Local nSetErrorMode := 0

//Traza( 1, "
cDisk=", cDisk )
//Traza( 1, "
1-SETERRORMODE=", SETERRORMODE() )

nSetErrorMode := SETERRORMODE( 1 )
//Traza( 1, "
1-nSetErrorMode=", nSetErrorMode )

//lExist := IsDisk( Left( cDisk, 1) + "
:" )
//Traza( 1, "
1-lExist=", lExist )
//lExist := lIsDir( Left( cDisk, 1) + "
:\" )
//Traza( 1, "
2-lExist=", lExist )

lExist := GetDiskFreeSpace( Left( cDisk, 1) + "
:\" )
//Traza( 1, "
3-lExist=", lExist )

nSetErrorMode := SETERRORMODE( nSetErrorMode )

//Traza( 1, "
2-nSetErrorMode=", nSetErrorMode )
//Traza( 1, "
2-SETERRORMODE=", SETERRORMODE() )

Return lExist
/* *************************** */#pragma BEGINDUMP

#include "
hbapi.h"
#include "
windows.h"

HB_FUNC( SETERRORMODE )
{
   hb_retni( SetErrorMode( hb_parni( 1 ) ) ) ;
}

HB_FUNC( GETDISKFREESPACE ) // cRootPathName, @nSectorsByCluster, @nBytesPerSector,
                            // @nNumberOfFreeClusters, @nTotalNumberOfClusters --> lResult
{
   LPSTR lpRootPathName = hb_parc( 1 );
   DWORD SectorsPerCluster;
   DWORD BytesPerSector;
   DWORD NumberOfFreeClusters;
   DWORD TotalNumberOfClusters;

   hb_retl( GetDiskFreeSpace( lpRootPathName, &SectorsPerCluster,
                              &BytesPerSector, &NumberOfFreeClusters,
                              &TotalNumberOfClusters ) );
   hb_stornl( SectorsPerCluster, 2 );
   hb_stornl( BytesPerSector, 3 );
   hb_stornl( NumberOfFreeClusters, 4 );
   hb_stornl( TotalNumberOfClusters, 5 );
}

#pragma ENDDUMP

Re: Reconocer puerta USB

PostPosted: Mon Oct 01, 2012 3:06 pm
by daniel_halon
Desde ya Muchas gracias, voy a testar todo esto.

Re: Reconocer puerta USB

PostPosted: Mon Oct 01, 2012 9:43 pm
by acuellar
Lo hago asi:

Code: Select all  Expand view

Local   aUnidades:=aDrives()  
      FOR xI=1 TO LEN( aUnidades )
            IF GetDriveType( aUnidades[xI] )=2
              ?"USB"
           ELSEIF GetDriveType( aUnidades[xI] )=3
              ?"HDISK"
           ELSEIF GetDriveType( aUnidades[xI] )=5
              ?"CDROOM"
           ENDif
       NEXT
 


Saludos,

Adhemar

Re: Reconocer puerta USB

PostPosted: Mon Oct 01, 2012 10:37 pm
by daniel_halon
Gracias Adhemar, parece tan simple :oops: y yo buscando por el lado difícil, voy a testar y retorno.

Abrazos, Daniel

Re: Reconocer puerta USB

PostPosted: Mon Oct 01, 2012 11:55 pm
by daniel_halon
Adhemar, funcionó perfecto, solo me falta saber que letra es la unidad usb, como podria implementarlo en este ejemplo?
Gracias, Daniel

Re: Reconocer puerta USB (Resuelto)

PostPosted: Tue Oct 02, 2012 1:47 am
by daniel_halon
Gracias Ahemar, quedo asi:

Code: Select all  Expand view

Function Integrar()
Local   aUnidades:=aDrives(), Pendrive := '', uni := 0  
      FOR xI=1 TO LEN( aUnidades )
            IF GetDriveType( aUnidades[xI] )=2
              Uni :=  GetDriveType( aUnidades[xI])
              Pendrive := aUnidades[xI,1] + ':'
            ENDif
             
          * ELSEIF GetDriveType( aUnidades[xI] )=3
          *    ?"HDISK"
          * ELSEIF GetDriveType( aUnidades[xI] )=5
          *    ?"CDROOM"
         
       NEXT
       
       IF uni == 2
         IF File(PenDrive + '
Evs.txt')
            COPYFILE('
Bak.rar', PenDrive + 'Bak.rar', .F. )
         ELSE
           IF MsgInfo(OemToAnsi('
Este nÆo e o PenDrive de Backup'), + CRLF +;
              '
Deseja copiar mesmo assim?',OemToAnsi('Aten‡Æo'))
              COPYFILE('
Bak.rar', PenDrive + 'Bak.rar', .F. )
           ENDIF
         ENDIF
       ELSE
         MsgStop('
Insira o PenDrive na entrada USB e tente novamente')
       ENDIF
Return Pendrive

Re: Reconocer puerta USB

PostPosted: Tue Oct 02, 2012 7:26 am
by mastintin
Si el ordenador tiene un lector de tarjetas ( de camara de fotos me refiero ) la funcion aDrives devuelve error y no funciona .
Saludos.

Re: Reconocer puerta USB

PostPosted: Tue Oct 02, 2012 1:50 pm
by daniel_halon
No habia pensado en eso, tienes alguna otra idea de como hacerlo? Mastintin

Re: Reconocer puerta USB

PostPosted: Tue Oct 02, 2012 7:12 pm
by mastintin
Pues no , la idea me parece perfecta , pero se tendria que revisar la funcion aDrive() para que el error no estropease todo.
Tendremos que pensar como arreglarlo .
Saludos.

Re: Reconocer puerta USB

PostPosted: Tue Oct 02, 2012 9:50 pm
by FiveWiDi
mastintin wrote:Pues no , la idea me parece perfecta , pero se tendria que revisar la funcion aDrive() para que el error no estropease todo.
Tendremos que pensar como arreglarlo .
Saludos.


Hola a todos,

Creo que con las funciones que os he dejado os funcionará para un lector de targetas.
Lo acabo de probar con un lector de 4 targetas y solo muestra la unidad en la que está insertada la targeta.

:)

Re: Reconocer puerta USB

PostPosted: Wed Oct 03, 2012 7:34 am
by mastintin
FiveWiDi wrote:Creo que con las funciones que os he dejado os funcionará para un lector de targetas.
Lo acabo de probar con un lector de 4 targetas y solo muestra la unidad en la que está insertada la targeta.

:)


FiveWidi , pues me devuelve que la funcion SETERRORMODE no la encuentra , por otro lado si la anulo tambien falta la funcion GetDiskFreeSpace() que ha sido sustituida por GetDiskFreeSpaceEx() .
Usando esta ultima funcion ( que devuelve el espacio libre ) ,genera el mismo error que aDrives() y ademas devuelve que tiene espacio libre en unidades ( lectoras de tarjeta) que no tienen tarjeta insertada.

Tendremos que seguir buscando la solución. Gracias por el apunte.

Re: Reconocer puerta USB

PostPosted: Wed Oct 03, 2012 10:14 am
by mastintin
mastintin wrote:
FiveWiDi wrote:Creo que con las funciones que os he dejado os funcionará para un lector de targetas.
Lo acabo de probar con un lector de 4 targetas y solo muestra la unidad en la que está insertada la targeta.

:)


FiveWidi , pues me devuelve que la funcion SETERRORMODE no la encuentra , por otro lado si la anulo tambien falta la funcion GetDiskFreeSpace() que ha sido sustituida por GetDiskFreeSpaceEx() .
Usando esta ultima funcion ( que devuelve el espacio libre ) ,genera el mismo error que aDrives() y ademas devuelve que tiene espacio libre en unidades ( lectoras de tarjeta) que no tienen tarjeta insertada.

Tendremos que seguir buscando la solución. Gracias por el apunte.


Lo he encontrado aqui ... :-) viewtopic.php?f=3&t=10541&start=30
la funcion GETDISKFREESPACE da un Warning W8075 varih.prg 2354: Suspicious pointer conversion in function HB_FUN_GETDISKFREESPACE. pero funciona perfecto.
Para solucionar el Warning asi:
Code: Select all  Expand view

 hb_retl( GetDiskFreeSpace( ( char * ) hb_parc( 1), &SectorsPerCluster,
                              &BytesPerSector, &NumberOfFreeClusters,
                              &TotalNumberOfClusters ) );
 



Saludos y gracias.

Re: Reconocer puerta USB

PostPosted: Wed Oct 03, 2012 10:53 am
by mastintin
Amplio:
He modificado la funcion de fivewin para que devuelva un nuevo parametro que es el resultado de la ejecucion de la función , ya no necesitamos GetdiskFreespace :

Code: Select all  Expand view

HB_FUNC( GETDISKFREESPACEEX )
{
   LONGLONG FreeBytesAvailable, TotalNumberOfBytes, TotalNumberOfFreeBytes;

   hb_reta( 4 );

   hb_storvnll( GetDiskFreeSpaceEx( ( char * ) hb_parc( 1 ), ( PULARGE_INTEGER ) &FreeBytesAvailable,
                       ( PULARGE_INTEGER ) &TotalNumberOfBytes, ( PULARGE_INTEGER ) &TotalNumberOfFreeBytes ) , -1, 4 );

   hb_storvnll( FreeBytesAvailable, -1, 1 );
   hb_storvnll( TotalNumberOfBytes, -1, 2 );
   hb_storvnll( TotalNumberOfFreeBytes, -1, 3 );
}


 


Por otra parte , esto funciona perfectamante al anular los mensajes de error :
Code: Select all  Expand view

 LOCAL nSetErrorMode := SETERRORMODE( 1 )
 Local   aUnidades:=aDrives()
 nSetErrorMode := SETERRORMODE( nSetErrorMode )
 

Re: Reconocer puerta USB

PostPosted: Wed Oct 03, 2012 3:26 pm
by FiveWiDi
mastintin wrote:
FiveWiDi wrote:Creo que con las funciones que os he dejado os funcionará para un lector de targetas.
Lo acabo de probar con un lector de 4 targetas y solo muestra la unidad en la que está insertada la targeta.

:)


FiveWidi , pues me devuelve que la funcion SETERRORMODE no la encuentra , por otro lado si la anulo tambien falta la funcion GetDiskFreeSpace() que ha sido sustituida por GetDiskFreeSpaceEx() .
Usando esta ultima funcion ( que devuelve el espacio libre ) ,genera el mismo error que aDrives() y ademas devuelve que tiene espacio libre en unidades ( lectoras de tarjeta) que no tienen tarjeta insertada.

Tendremos que seguir buscando la solución. Gracias por el apunte.


He añadido estas funciones en el post de más arriba que contienen las funciones que menciono.