int ret = 0; HRESULT hr = S_OK; LPTSTR szReaders = NULL, szRdr = NULL; DWORD cchReaders = SCARD_AUTOALLOCATE; DWORD dwI, dwRdrCount; SCARD_READERSTATE rgscState[MAXIMUM_SMARTCARD_READERS]; TCHAR szCard[MAX_PATH * 64]; DWORD dwCardLen = sizeof(szCard)/ sizeof(TCHAR); SCARDCONTEXT hSC; LONG lReturn; // Establish a context. lReturn = SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &hSC ); if ( SCARD_S_SUCCESS != lReturn ) { goto cleanup; } // Determine which readers are available. lReturn = SCardListReaders(hSC, NULL, (LPTSTR)&szReaders, &cchReaders ); if ( SCARD_S_SUCCESS != lReturn ) { goto cleanup; } // Place the readers into the state array. szRdr = szReaders; for ( dwI = 0; dwI < MAXIMUM_SMARTCARD_READERS; dwI++ ) { if ( 0 == *szRdr ) break; rgscState[dwI].szReader = szRdr; rgscState[dwI].dwCurrentState = SCARD_STATE_UNAWARE; szRdr += lstrlen(szRdr) + 1; } dwRdrCount = dwI; lReturn = SCardListCards(hSC, NULL, NULL, 0, szCard, &dwCardLen); if (SCARD_S_SUCCESS != lReturn) { goto cleanup; } // If any readers are available, proceed. if ( 0 != dwRdrCount ) { for (;;) { // Look for the card. lReturn = SCardLocateCards(hSC, szCard, rgscState, dwRdrCount ); if ( SCARD_S_SUCCESS != lReturn ) { goto cleanup; } // Look through the array of readers. for ( dwI= 0; dwI < dwRdrCount; dwI++) { if ( 0 != ( SCARD_STATE_ATRMATCH & rgscState[dwI].dwEventState)) { lReturn = SCardListCards(hSC, rgscState[dwI].rgbAtr, NULL, 0, szCard, &dwCardLen); LPTSTR szProvider = NULL; DWORD chProvider = SCARD_AUTOALLOCATE; LONG lReturn = SCARD_S_SUCCESS; lReturn=SCardGetCardTypeProviderName(hSC,szCard,SCARD_PROVIDER_CSP,(LPTSTR)&szProvider,&chProvider); ret = 1; goto cleanup; // Context will be release automatically. } // Update the state. rgscState[dwI].dwCurrentState = rgscState[dwI].dwEventState; } // Card not found yet; wait until there is a change. lReturn = SCardGetStatusChange(hSC, 1000, // time wait rgscState, dwRdrCount ); if ( SCARD_S_SUCCESS != lReturn ) { goto cleanup; } } // for (;;) } cleanup: if (szReaders) SCardFreeMemory(hSC,szReaders); if (hSC) SCardReleaseContext(hSC); return ret;