5 Jun 2008

Detect SDCard ou USB key insertion

Voici deux petits exemples de code permettant de détecter l'insertion d'une SDCard ou d'une clé USB :
Here are 2 code examples for detecting SDCard orUSB key insertion:
avec la WndProc :
with the WndProc:
case WM_DEVICECHANGE:
if (wParam == DBT_DEVICEARRIVAL)
{
Sleep(300);
WIN32_FIND_DATA fd;
if (FindFirstFile(L"sdmmc disk", &fd) != INVALID_HANDLE_VALUE)
{
//Add your code
}
}
break;

avec les notifications Windows CE :
With the Windows CE system notifications:
m_DevNotifyGuid = STORE_MOUNT_GUID;
memset(&m_tMsgQOptions, 0, sizeof(m_tMsgQOptions));
m_tMsgQOptions.dwSize = sizeof(m_tMsgQOptions);
m_tMsgQOptions.dwFlags = 0;
m_tMsgQOptions.dwMaxMessages = 0;
m_tMsgQOptions.cbMaxMessage = 4096;
m_tMsgQOptions.bReadAccess = TRUE;
m_hDevNotifyMsgQ = CreateMsgQueue(NULL, &m_tMsgQOptions);
m_hDevNotify = RequestDeviceNotifications( &m_DevNotifyGuid, m_hDevNotifyMsgQ, TRUE );

// Infinite Loop to detect all mounted drive
while (true)
{
// Wait for notifications
WaitForSingleObject(m_hDevNotifyMsgQ,INFINITE);
ReadMsgQueue(m_hDevNotifyMsgQ, lpBuffer,4096,&dwNbRead,1000,&dwFlags);
// Add your code
}

Pour utiliser les notifications en C#, il suffit de faire les imports des fonctions suivantes :
To use the notifications in C#, you have to import the following functions:
-RequestDeviceNotifications
-StopDeviceNotifications
-WaitForSingleObject
-CreateMsgQueue
-ReadMsgQueue
Ou de surcharger la WndProc pour la première méthode.
Or override the WndProc for the first example.

Ce code peut aussi être utile au démarrage de votre device si vous souhaitez lancer une application C# installée sur une SD.
This code can be also used if you have a startup application installed on a SDCard.

No comments: