USB Device Shut Down\Dispositivo USB Apagar

General Help regarding HMG, Compilation, Linking, Samples

Moderator: Rathinagiri

User avatar
vagblad
Posts: 160
Joined: Tue Jun 18, 2013 12:18 pm
DBs Used: MySQL,DBF
Location: Thessaloniki, Greece

USB Device Shut Down\Dispositivo USB Apagar

Post by vagblad »

Hello all,

I wonder if anyone knows if it is possible to control through our programs the on/off state of a USB device. More specific i am talking about an external USB HDD.
For example to help you understand more easily what i want to do:
I schedule a task for a backup operation from my C: drive to my external Z: usb drive.
When the task is done i would like to disconnect the external drive so no one could have access to it. And on the next day i would have to unplug and plug again the HDD to have access.

Thanks a lot in advance

Best Regards

Google translate
----------------------------------------------------------------------
Hola a todos,

Me pregunto si alguien sabe si es posible controlar a través de nuestros programas el estado de encendido / apagado de un dispositivo USB . Más específico que estoy hablando de un disco duro USB externo .
Por ejemplo, para ayudar a entender más fácilmente lo que quiero hacer :
Puedo programar una tarea para una operación de copia de seguridad de mi unidad C: a mi Z externa : unidad USB .
Cuando se lleva a cabo la tarea que me gustaría desconectar la unidad externa para que nadie pueda tener acceso a ella. Y al día siguiente yo tendría que desconectar y conectar de nuevo el disco duro para tener acceso .

Muchas gracias desde ya

Atentamente
Vagelis Prodromidis
Email: vagblad@gmail.com, Skype: vagblad
User avatar
vagblad
Posts: 160
Joined: Tue Jun 18, 2013 12:18 pm
DBs Used: MySQL,DBF
Location: Thessaloniki, Greece

Re: USB Device Shut Down\Dispositivo USB Apagar

Post by vagblad »

mol wrote:Is it your way to avoid ransomware problems?
Yes definitely one more way to protect myself :)
Vagelis Prodromidis
Email: vagblad@gmail.com, Skype: vagblad
User avatar
andyglezl
Posts: 1461
Joined: Fri Oct 26, 2012 7:58 pm
Location: Guadalajara Jalisco, MX
Contact:

Re: USB Device Shut Down\Dispositivo USB Apagar

Post by andyglezl »

Hola
en teoria se puede hacer manualmente, habria que buscar la forma
de hacerlo automaticamente.
--------------------------------------------------------------------------------
Hello
in theory it can be done manually, would have to find a way
to do so automatically.
DeshabUSB.jpg
DeshabUSB.jpg (258.21 KiB) Viewed 5941 times
desconectar la unidad externa para que nadie pueda tener acceso a ella
Tienes la unidad compartida ?, sino es cuestion de permisos.
---------------------------------------------------------------------------
You have the shared drive?, But it is a matter of permissions.


ó con el administrador de dispositivos...
------------------------------------------------
or the device manager ...
DeshabUSB2.jpg
DeshabUSB2.jpg (135.49 KiB) Viewed 5938 times
Andrés González López
Desde Guadalajara, Jalisco. México.
User avatar
Clip2Mania
Posts: 99
Joined: Fri Jun 13, 2014 7:16 am
Location: Belgium

Re: USB Device Shut Down\Dispositivo USB Apagar

Post by Clip2Mania »

You can do this on the command line via Devcon.exe, a utility which is part of the Windows Development Kit.. This is the command-line equivalent of Windows Device Manager.

First, query all USB DeviceID's:

Code: Select all

devcon findall =usb
Pick the corrrect one and you can "eject" it via the command

Code: Select all

devcon remove "USB\VID_9999&PID_9999"
You can use wildcards in the above DeviceID's.

You can also use an alternative of Devcon, such asRemoveDrive

Hope this helps a bit.
User avatar
Rathinagiri
Posts: 5471
Joined: Tue Jul 29, 2008 6:30 pm
DBs Used: MariaDB, SQLite, SQLCipher and MySQL
Location: Sivakasi, India
Contact:

Re: USB Device Shut Down\Dispositivo USB Apagar

Post by Rathinagiri »

I am sure we have to call this Win32 API function CM_Request_Device_EjectW()

Probably Claudio can help.
East or West HMG is the Best.
South or North HMG is worth.
...the possibilities are endless.
User avatar
vagblad
Posts: 160
Joined: Tue Jun 18, 2013 12:18 pm
DBs Used: MySQL,DBF
Location: Thessaloniki, Greece

Re: USB Device Shut Down\Dispositivo USB Apagar

Post by vagblad »

@Andy
Thanks Andy. Yeah it can be done manually, i am just trying to automate the whole process as much as possible, so that there is as less human involment as it can be to avoid errors like(forgot to take backup etc..).

Gracias Andy . Sí que se puede hacer manualmente , estoy tratando de automatizar todo el proceso tanto como sea posible , de modo que no es tan involment menos humano , ya que puede ser para evitar errores similares ( se olvidó de tener copia de seguridad , etc .. ) .
--------------------------------------------------------------------------------------------------------------------------------
Clip2Mania wrote:You can do this on the command line via Devcon.exe, a utility which is part of the Windows Development Kit.. This is the command-line equivalent of Windows Device Manager.

You can also use an alternative of Devcon, such asRemoveDrive

Hope this helps a bit.
Yes Devcon seems a great solution, i tried it yesterday but unfortunately i didn't manage to get it to work so far.
I get the message that the device is disabled but i can still access it through windows explorer.
I will do some more tries today and i will try RemoveDrive also.
Thanks a lot for the help!

Sí Devcon parece una gran solución , lo intenté ayer, pero por desgracia no me las arreglo para conseguir que funcione hasta el momento.
Me sale el mensaje de que el dispositivo está deshabilitado , pero yo todavía puedo acceder a ella a través de Windows Explorer .
Voy a hacer algunas más tries hoy y voy a tratar RemoveDrive también .
¡Muchas gracias por la ayuda!
--------------------------------------------------------------------------------------------------------------------------------
@Rathi

Yeah Rathi that seems to be the one.

Sí Rathi que parece ser la única.
Vagelis Prodromidis
Email: vagblad@gmail.com, Skype: vagblad
PeteWG
Posts: 176
Joined: Sun Mar 21, 2010 5:45 pm

Re: USB Device Shut Down\Dispositivo USB Apagar

Post by PeteWG »

Hi,

try the code below to see if it serves your purpose:

Code: Select all

// test program
request hb_gt_win_default
PROC MAIN( cDriveLetter )

	hb_Default( @cDriveLetter, "G:" )

	IF EjectRemovable( cDriveLetter )
		? "The drive " + cDriveLetter + " can be safely removed."
	ELSE
		? "Failed to safely remove/eject drive " + cDriveLetter
	ENDIF
	WAIT
	RETURN
// end test program

***************************************************************
#pragma begindump

#include <windows.h>
#include <winioctl.h>
#include <tchar.h>
#include <stdio.h>

// Prototypes
BOOL EjectVolume(TCHAR cDriveLetter);
HANDLE OpenVolume(TCHAR cDriveLetter);
BOOL LockVolume(HANDLE hVolume);
BOOL DismountVolume(HANDLE hVolume);
BOOL PreventRemovalOfVolume(HANDLE hVolume, BOOL fPrevent);
BOOL AutoEjectVolume(HANDLE hVolume);
BOOL CloseVolume(HANDLE hVolume);

LPTSTR szVolumeFormat = TEXT("\\\\.\\%c:");
LPTSTR szRootFormat = TEXT("%c:\\");

HANDLE OpenVolume(TCHAR cDriveLetter)
{
	HANDLE hVolume;
	UINT uDriveType;
	TCHAR szVolumeName[8];
	TCHAR szRootName[5];
	DWORD dwAccessFlags;

	wsprintf(szRootName, szRootFormat, cDriveLetter);
	uDriveType = GetDriveType(szRootName);

	switch(uDriveType) 
	{
	case DRIVE_REMOVABLE:
	  dwAccessFlags = GENERIC_READ | GENERIC_WRITE;
	  break;
	case DRIVE_CDROM:
	  dwAccessFlags = GENERIC_READ;
	  break;
	default:
	  return INVALID_HANDLE_VALUE;
	}

	wsprintf(szVolumeName, szVolumeFormat, cDriveLetter);

	hVolume = CreateFile(   szVolumeName,
								 dwAccessFlags,
								 FILE_SHARE_READ | FILE_SHARE_WRITE,
								 NULL,
								 OPEN_EXISTING,
								 0,
								 NULL );
	return hVolume;
}

BOOL CloseVolume(HANDLE hVolume)
{
	return CloseHandle(hVolume);
}

#define LOCK_TIMEOUT        10000       // 10 Seconds
#define LOCK_RETRIES        20

BOOL LockVolume( HANDLE hVolume )
{
	DWORD dwBytesReturned;
	DWORD dwSleepAmount;
	int nTryCount;

	dwSleepAmount = LOCK_TIMEOUT / LOCK_RETRIES;

	for( nTryCount = 0; nTryCount < LOCK_RETRIES; nTryCount++ ) 
	{
	  if( DeviceIoControl( hVolume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0,
								  &dwBytesReturned, NULL ) )
			return TRUE;

	  Sleep( dwSleepAmount );
	}

	return FALSE;
}

BOOL DismountVolume( HANDLE hVolume )
{
	DWORD dwBytesReturned;
	return DeviceIoControl( hVolume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0,
								   &dwBytesReturned, NULL );
}

BOOL PreventRemovalOfVolume(HANDLE hVolume, BOOL fPreventRemoval)
{
	DWORD dwBytesReturned;
	PREVENT_MEDIA_REMOVAL PMRBuffer;
	PMRBuffer.PreventMediaRemoval = fPreventRemoval;
	return DeviceIoControl( hVolume, IOCTL_STORAGE_MEDIA_REMOVAL,
								   &PMRBuffer, sizeof(PREVENT_MEDIA_REMOVAL),
								   NULL, 0, &dwBytesReturned, NULL );
}

AutoEjectVolume( HANDLE hVolume )
{
	DWORD dwBytesReturned;
	return DeviceIoControl( hVolume, IOCTL_STORAGE_EJECT_MEDIA, NULL, 0, NULL, 0,
								 &dwBytesReturned,
								 NULL );
}

BOOL EjectVolume( TCHAR cDriveLetter )
{
	HANDLE hVolume;

	BOOL fRemoveSafely = FALSE;
	BOOL fAutoEject = FALSE;

	hVolume = OpenVolume(cDriveLetter);
	if( hVolume == INVALID_HANDLE_VALUE )
	  return FALSE;

	if( LockVolume(hVolume) && DismountVolume(hVolume) )
	{
	  fRemoveSafely = TRUE;

	  if (PreventRemovalOfVolume(hVolume, FALSE) && AutoEjectVolume(hVolume))
			fAutoEject = TRUE;
	}

	if( ! CloseVolume(hVolume) )
	  return FALSE;

	return TRUE;
}

#include "hbapi.h"
#include "hbapifs.h"
HB_FUNC( EJECTREMOVABLE )
{ 
	char * szDrive = hb_parc( 1 );
	hb_retl( EjectVolume( *szDrive ) ); 
	return;
}

#pragma enddump

regards,
Pete
User avatar
danielmaximiliano
Posts: 2612
Joined: Fri Apr 09, 2010 4:53 pm
Location: Argentina
Contact:

Re: USB Device Shut Down\Dispositivo USB Apagar

Post by danielmaximiliano »

Soluciones perfectas, gracias por compa
*´¨)
¸.·´¸.·*´¨) ¸.·*¨)
(¸.·´. (¸.·` *
.·`. Harbour/HMG : It's magic !
(¸.·``··*

Saludos / Regards
DaNiElMaXiMiLiAnO

Whatsapp. := +54901169026142
Telegram Name := DaNiElMaXiMiLiAnO
User avatar
quartz565
Posts: 667
Joined: Mon Oct 01, 2012 12:37 pm
Location: Thessaloniki, Greece
Contact:

Re: USB Device Shut Down\Dispositivo USB Apagar

Post by quartz565 »

Hi Pete, this works perfectly !
Τhank you !
Best Regards,
Nikos.

os: Windows Server 2019 - 64
Post Reply