void DisplayScreen() { COORD pos; COORD size; TCHAR lpStr[80]; DWORD numChars; int lines; int idx; GetConsoleScreenBufferInfo(hStdout,&screenBufferInfo); size=screenBufferInfo.dwSize; ScreenLines=size.Y; ProcPerScreen = ScreenLines-7; if (first == 0) { // Header pos.X = 1; pos.Y = 1; WriteConsoleOutputCharacter(hStdout, lpTitle, _tcslen(lpTitle), pos, &numChars); pos.X = 1; pos.Y = 2; WriteConsoleOutputCharacter(hStdout, lpSeparator, _tcslen(lpSeparator), pos, &numChars); pos.X = 1; pos.Y = 3; WriteConsoleOutputCharacter(hStdout, lpHeader, _tcslen(lpHeader), pos, &numChars); pos.X = 1; pos.Y = 4; WriteConsoleOutputCharacter(hStdout, lpSeparator, _tcslen(lpSeparator), pos, &numChars); // Footer pos.X = 1; pos.Y = ScreenLines-2; WriteConsoleOutputCharacter(hStdout, lpSeparator, _tcslen(lpSeparator), pos, &numChars); // Menu pos.X = 1; pos.Y = ScreenLines-1; WriteConsoleOutputCharacter(hStdout, lpEmpty, _tcslen(lpEmpty), pos, &numChars); WriteConsoleOutputCharacter(hStdout, lpMenu, _tcslen(lpMenu), pos, &numChars); first = 1; } // Processess lines = ProcessCount; if (lines > ProcPerScreen) lines = ProcPerScreen; for (idx=0; idx<ProcPerScreen; idx++) { int len, i; TCHAR lpNumber[5]; TCHAR lpPid[8]; TCHAR lpCpu[6]; TCHAR lpMemUsg[12]; TCHAR lpPageFaults[15]; WORD wColor; for (i = 0; i < 80; i++) lpStr[i] = _T(' '); // data if (idx < lines && scrolled + idx < ProcessCount) { // number _stprintf(lpNumber, _T("%3d"), idx+scrolled); _tcsncpy(&lpStr[2], lpNumber, 3); // image name #ifdef _UNICODE len = wcslen(pPerfData[scrolled+idx].ImageName); #else WideCharToMultiByte(CP_ACP, 0, pPerfData[scrolled+idx].ImageName, -1, imgName, MAX_PATH, NULL, NULL); len = strlen(imgName); #endif if (len > columnRightPositions[1]) { len = columnRightPositions[1]; } #ifdef _UNICODE wcsncpy(&lpStr[columnRightPositions[0]+3], pPerfData[scrolled+idx].ImageName, len); #else strncpy(&lpStr[columnRightPositions[0]+3], imgName, len); #endif // PID _stprintf(lpPid, _T("%6ld"), pPerfData[scrolled+idx].ProcessId); _tcsncpy(&lpStr[columnRightPositions[2] - 6], lpPid, 6); #ifdef TIMES // CPU _stprintf(lpCpu, _T("%3d%%"), pPerfData[scrolled+idx].CPUUsage); _tcsncpy(&lpStr[columnRightPositions[3] - 4], lpCpu, 4); #endif // Mem usage _stprintf(lpMemUsg, _T("%6ld %s"), pPerfData[scrolled+idx].WorkingSetSizeBytes / 1024, lpMemUnit); _tcsncpy(&lpStr[columnRightPositions[4] - 9], lpMemUsg, 9); // Page Fault _stprintf(lpPageFaults, _T("%12ld"), pPerfData[scrolled+idx].PageFaultCount); _tcsncpy(&lpStr[columnRightPositions[5] - 12], lpPageFaults, 12); } // columns lpStr[0] = _T(' '); lpStr[1] = _T('|'); for (i = 0; i < 6; i++) lpStr[columnRightPositions[i] + 1] = _T('|'); pos.X = 0; pos.Y = 5+idx; WriteConsoleOutputCharacter(hStdout, lpStr, 80, pos, &numChars); // Attributes now... pos.X = columnRightPositions[0] + 1; pos.Y = 5+idx; if (selection == idx) { wColor = BACKGROUND_GREEN | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; } else { wColor = BACKGROUND_BLUE | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; } FillConsoleOutputAttribute( hStdout, // screen buffer handle wColor, // color to fill with columnRightPositions[1] - 4, // number of cells to fill pos, // first cell to write to &numChars); // actual number written } return; }
// protocol service function for adding a new contact onto contact list // lParam = PROTOSEARCHRESULT INT_PTR WeatherAddToList(WPARAM wParam, LPARAM lParam) { PROTOSEARCHRESULT *psr = (PROTOSEARCHRESULT*)lParam; if(!psr || !psr->email) return 0; // search for existing contact for (MCONTACT hContact = db_find_first(); hContact; hContact = db_find_next(hContact)) { // check if it is a weather contact if ( IsMyContact(hContact)) { DBVARIANT dbv; // check ID to see if the contact already exist in the database if ( !db_get_ts(hContact, WEATHERPROTONAME, "ID", &dbv)) { if ( !_tcsicmp(psr->email, dbv.ptszVal)) { // remove the flag for not on list and hidden, thus make the contact visible // and add them on the list if (db_get_b(hContact, "CList", "NotOnList", 1)) { db_unset(hContact, "CList", "NotOnList"); db_unset(hContact, "CList", "Hidden"); } db_free(&dbv); // contact is added, function quitting return (INT_PTR)hContact; } db_free(&dbv); } } } // if contact with the same ID was not found, add it if (psr->cbSize < sizeof(PROTOSEARCHRESULT)) return 0; MCONTACT hContact = (MCONTACT)CallService(MS_DB_CONTACT_ADD, 0, 0); CallService(MS_PROTO_ADDTOCONTACT, hContact, (LPARAM)WEATHERPROTONAME); // suppress online notification for the new contact CallService(MS_IGNORE_IGNORE, hContact, IGNOREEVENT_USERONLINE); // set contact info and settings TCHAR svc[256]; _tcsncpy(svc, psr->email, SIZEOF(svc)); svc[SIZEOF(svc)-1] = 0; GetSvc(svc); // set settings by obtaining the default for the service if (psr->lastName[0] != 0) { WIDATA *sData = GetWIData(svc); db_set_ts(hContact, WEATHERPROTONAME, "MapURL", sData->DefaultMap); db_set_s(hContact, WEATHERPROTONAME, "InfoURL", sData->DefaultURL); } else { // if no valid service is found, create empty strings for MapURL and InfoURL db_set_s(hContact, WEATHERPROTONAME, "MapURL", ""); db_set_s(hContact, WEATHERPROTONAME, "InfoURL", ""); } // write the other info and settings to the database db_set_ts(hContact, WEATHERPROTONAME, "ID", psr->email); db_set_ts(hContact, WEATHERPROTONAME, "Nick", psr->nick); db_set_w(hContact, WEATHERPROTONAME, "Status", ID_STATUS_OFFLINE); AvatarDownloaded(hContact); TCHAR str[256]; mir_sntprintf(str, SIZEOF(str), TranslateT("Current weather information for %s."), psr->nick); db_set_ts(hContact, WEATHERPROTONAME, "About", str); // make the last update tags to something invalid db_set_s(hContact, WEATHERPROTONAME, "LastLog", "never"); db_set_s(hContact, WEATHERPROTONAME, "LastCondition", "None"); db_set_s(hContact, WEATHERPROTONAME, "LastTemperature", "None"); // ignore status change db_set_dw(hContact, "Ignore", "Mask", 8); // if no default station is found, set the new contact as default station if (opt.Default[0] == 0) { DBVARIANT dbv; GetStationID(hContact, opt.Default, SIZEOF(opt.Default)); opt.DefStn = hContact; if ( !db_get_ts(hContact, WEATHERPROTONAME, "Nick", &dbv)) { // notification message box mir_sntprintf(str, SIZEOF(str), TranslateT("%s is now the default weather station"), dbv.ptszVal); db_free(&dbv); MessageBox(NULL, str, TranslateT("Weather Protocol"), MB_OK|MB_ICONINFORMATION); } db_set_ts(NULL, WEATHERPROTONAME, "Default", opt.Default); } // display the Edit Settings dialog box EditSettings(hContact, 0); return (INT_PTR)hContact; }
int _tmain(int argc, _TCHAR* argv[]) { LONG retval; Params p; LPVOID cert, crl; DWORD certSz = 0, crlSz = 0, index = 0, disp = 0; HKEY rootKey = NULL, storesKey = NULL, key = NULL; HCERTSTORE hCertStore = NULL; TCHAR root[MAX_REG_KEY_LEN]; // Get params if (!GetParams(&p, argc, argv)) { _tprintf(TEXT("Usage:\n")); _tprintf(TEXT("%s hive crt.cer [/CRL crl.crl] [/Store store]\n\n"), argv[0]); _tprintf(TEXT("hive\ta registry hive for HKLM\\SOFTWARE (user hives not supported)\n")); _tprintf(TEXT(" found at Windows\\System32\\config\\SOFTWARE (cannot use be an in-use hive)\n")); _tprintf(TEXT("crt.cer\tthe certificate to import\n")); _tprintf(TEXT("crl.crl\tif provided adds a CRL as well\n")); _tprintf(TEXT("store\tthe store to import to, defaults to ROOT\n\n")); return -1; } // Enable privileges if (!EnablePriv(SE_TAKE_OWNERSHIP_NAME) || !EnablePriv(SE_BACKUP_NAME) || !EnablePriv(SE_RESTORE_NAME)) { return LastError(TEXT("Failed to enable take ownership, backup, and restore privileges"), NULL); } // Read the certificate file if ((cert = Read(p.cert, &certSz)) == NULL) { return LastError(TEXT("Failed to read certificate file '%s'"), p.cert); } // Read the CRL file if (p.crl && ((crl = Read(p.crl, &crlSz)) == NULL)) { LocalFree(cert); return LastError(TEXT("Failed to read the CRL file '%s'"), p.crl); } // Find a subkey that's available _tcsncpy(root, TEXT("TEMPHIVE"), MAX_REG_KEY_LEN); if ((retval = RegOpenKeyEx(HKEY_LOCAL_MACHINE, root, 0, KEY_READ, &key)) != ERROR_FILE_NOT_FOUND) { if (retval != ERROR_SUCCESS) { LocalFree(crl); LocalFree(cert); return Error(TEXT("Failed to find subkey to load hive"), NULL, retval); } RegCloseKey(key); _sntprintf(root, MAX_REG_KEY_LEN, TEXT("TEMPHIVE%u"), index++); } key = NULL; // Load the hive if ((retval = RegLoadKey(HKEY_LOCAL_MACHINE, root, p.hive)) != ERROR_SUCCESS) { LocalFree(cert); if (crl) LocalFree(crl); return Error(TEXT("Failed to load hive file '%s'"), p.hive, retval); } // Open the HKLM\TEMPHIVE\Microsoft\SystemCertificates if ((retval = RegOpenKeyEx(HKEY_LOCAL_MACHINE, root, 0, KEY_ALL_ACCESS, &rootKey)) != ERROR_SUCCESS) { Error(TEXT("Failed to get root key '%s'"), root, retval); } else if ((retval = RegOpenKeyEx(rootKey, TEXT("Microsoft\\SystemCertificates"), 0, KEY_ALL_ACCESS, &storesKey)) != ERROR_SUCCESS) { Error(TEXT("Failed to get stores key: %u\n"), NULL, retval); // Create/Open the registry certificate store } else if ((retval = RegCreateKeyEx(storesKey, p.store, 0, NULL, REG_OPTION_BACKUP_RESTORE, KEY_ALL_ACCESS, NULL, &key, &disp)) != ERROR_SUCCESS) { Error(TEXT("Failed to create store key '%s'"), p.store, retval); // Open the store } else if ((hCertStore = CertOpenStore(CERT_STORE_PROV_REG, 0, (HCRYPTPROV)NULL, CERT_STORE_BACKUP_RESTORE_FLAG | CERT_STORE_OPEN_EXISTING_FLAG, key)) == NULL) { retval = LastError(TEXT("Failed to create certificate store"), NULL); // Add the certificate to the store } else if (!CertAddEncodedCertificateToStore(hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, cert, certSz, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) { retval = LastError(TEXT("Failed add certificate to store"), NULL); // Add the crl to the store } else if (crl && !CertAddEncodedCRLToStore(hCertStore, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, crl, crlSz, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) { retval = LastError(TEXT("Failed add the CRL to store"), NULL); } // Cleanup if (hCertStore) { CertCloseStore(hCertStore, CERT_CLOSE_STORE_FORCE_FLAG); } if (key) { RegCloseKey(key); } if (storesKey) { RegCloseKey(storesKey); } if (rootKey) { RegCloseKey(rootKey); } LocalFree(crl); LocalFree(cert); // Unload the hive if ((disp = RegUnLoadKey(HKEY_LOCAL_MACHINE, root)) != ERROR_SUCCESS) { if (retval == ERROR_SUCCESS) { retval = disp; } Error(TEXT("Failed to unload the hive"), NULL, disp); } // Successful? Yeah! if (retval == ERROR_SUCCESS) { if (p.crl) { _tprintf(TEXT("Successfully added %s and %s to the %s store in %s\n\n"), p.cert, p.crl, p.store, p.hive); } else { _tprintf(TEXT("Successfully added %s to the %s store in %s\n\n"), p.cert, p.store, p.hive); } } return retval; }
//-------------------------------------------------------------------------------------- // Search a set of typical directories //-------------------------------------------------------------------------------------- bool DXUtil_FindMediaSearchTypicalDirs( TCHAR* strSearchPath, int cchSearch, LPCTSTR strLeaf, TCHAR* strExePath, TCHAR* strExeName, TCHAR* strMediaDir ) { // Typical directories: // .\ // ..\ // ..\..\ // %EXE_DIR%\ // %EXE_DIR%\..\ // %EXE_DIR%\..\..\ // %EXE_DIR%\..\%EXE_NAME% // %EXE_DIR%\..\..\%EXE_NAME% // DXSDK media path // Search in .\ _tcsncpy( strSearchPath, strLeaf, cchSearch ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in ..\ _sntprintf( strSearchPath, cchSearch, TEXT("..\\%s"), strLeaf ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in ..\..\ _sntprintf( strSearchPath, cchSearch, TEXT("..\\..\\%s"), strLeaf ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in ..\..\ _sntprintf( strSearchPath, cchSearch, TEXT("..\\..\\%s"), strLeaf ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in the %EXE_DIR%\ _sntprintf( strSearchPath, cchSearch, TEXT("%s\\%s"), strExePath, strLeaf ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in the %EXE_DIR%\..\ _sntprintf( strSearchPath, cchSearch, TEXT("%s\\..\\%s"), strExePath, strLeaf ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in the %EXE_DIR%\..\..\ _sntprintf( strSearchPath, cchSearch, TEXT("%s\\..\\..\\%s"), strExePath, strLeaf ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in "%EXE_DIR%\..\%EXE_NAME%\". This matches the DirectX SDK layout _sntprintf( strSearchPath, cchSearch, TEXT("%s\\..\\%s\\%s"), strExePath, strExeName, strLeaf ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in "%EXE_DIR%\..\..\%EXE_NAME%\". This matches the DirectX SDK layout _sntprintf( strSearchPath, cchSearch, TEXT("%s\\..\\..\\%s\\%s"), strExePath, strExeName, strLeaf ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; // Search in DirectX SDK's media dir _sntprintf( strSearchPath, cchSearch, TEXT("%s%s"), strMediaDir, strLeaf ); strSearchPath[cchSearch-1] = 0; if( GetFileAttributes( strSearchPath ) != 0xFFFFFFFF ) return true; return false; }
//----------------------------------------------------------------------------- // Name: DXUtil_LaunchReadme() // Desc: Finds and opens the readme for this sample //----------------------------------------------------------------------------- VOID DXUtil_LaunchReadme( HWND hWnd, LPCTSTR strLoc ) { #ifdef UNDER_CE // This is not available on PocketPC MessageBox( hWnd, TEXT("For operating instructions, please open the ") TEXT("readme.txt file included with the project."), TEXT("DirectX SDK Sample"), MB_ICONWARNING | MB_OK ); return; #endif const int NUM_FILENAMES = 2; LPCTSTR strFilenames[] = { TEXT("readme.htm"), TEXT("readme.txt") }; TCHAR strReadmePath[1024]; TCHAR strExeName[MAX_PATH]; TCHAR strExePath[MAX_PATH]; TCHAR strSamplePath[MAX_PATH]; TCHAR* strLastSlash = NULL; for( int i=0; i < NUM_FILENAMES; i++ ) { LPCTSTR strFilename = strFilenames[i]; bool bSuccess = false; bool bFound = false; lstrcpy( strReadmePath, TEXT("") ); lstrcpy( strExePath, TEXT("") ); lstrcpy( strExeName, TEXT("") ); lstrcpy( strSamplePath, TEXT("") ); // If the user provided a location for the readme, check there first. if( strLoc ) { HKEY hKey; LONG lResult = RegOpenKeyEx( HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\DirectX SDK"), 0, KEY_READ, &hKey ); if( ERROR_SUCCESS == lResult ) { DWORD dwType; DWORD dwSize = MAX_PATH * sizeof(TCHAR); lResult = RegQueryValueEx( hKey, _T("DX9S4SDK Samples Path"), NULL, &dwType, (BYTE*)strSamplePath, &dwSize ); strSamplePath[MAX_PATH-1] = 0; // RegQueryValueEx doesn't NULL term if buffer too small if( ERROR_SUCCESS == lResult ) { _sntprintf( strReadmePath, 1023, TEXT("%s\\C++\\%s\\%s"), strSamplePath, strLoc, strFilename ); strReadmePath[1023] = 0; if( GetFileAttributes( strReadmePath ) != 0xFFFFFFFF ) bFound = TRUE; } } RegCloseKey( hKey ); } // Get the exe name, and exe path GetModuleFileName( NULL, strExePath, MAX_PATH ); strExePath[MAX_PATH-1]=0; strLastSlash = _tcsrchr( strExePath, TEXT('\\') ); if( strLastSlash ) { _tcsncpy( strExeName, &strLastSlash[1], MAX_PATH ); strExeName[MAX_PATH-1]=0; // Chop the exe name from the exe path *strLastSlash = 0; // Chop the .exe from the exe name strLastSlash = _tcsrchr( strExeName, TEXT('.') ); if( strLastSlash ) *strLastSlash = 0; } if( !bFound ) { // Search in "%EXE_DIR%\..\%EXE_NAME%\". This matches the DirectX SDK layout _tcscpy( strReadmePath, strExePath ); strLastSlash = _tcsrchr( strReadmePath, TEXT('\\') ); if( strLastSlash ) *strLastSlash = 0; lstrcat( strReadmePath, TEXT("\\") ); lstrcat( strReadmePath, strExeName ); lstrcat( strReadmePath, TEXT("\\") ); lstrcat( strReadmePath, strFilename ); if( GetFileAttributes( strReadmePath ) != 0xFFFFFFFF ) bFound = TRUE; } if( !bFound ) { // Search in "%EXE_DIR%\..\BumpMapping\%EXE_NAME%\". _tcscpy( strReadmePath, strExePath ); strLastSlash = _tcsrchr( strReadmePath, TEXT('\\') ); if( strLastSlash ) *strLastSlash = 0; lstrcat( strReadmePath, TEXT("\\BumpMapping\\") ); lstrcat( strReadmePath, strExeName ); lstrcat( strReadmePath, TEXT("\\") ); lstrcat( strReadmePath, strFilename ); if( GetFileAttributes( strReadmePath ) != 0xFFFFFFFF ) bFound = TRUE; } if( !bFound ) { // Search in "%EXE_DIR%\..\EnvMapping\%EXE_NAME%\". _tcscpy( strReadmePath, strExePath ); strLastSlash = _tcsrchr( strReadmePath, TEXT('\\') ); if( strLastSlash ) *strLastSlash = 0; lstrcat( strReadmePath, TEXT("\\EnvMapping\\") ); lstrcat( strReadmePath, strExeName ); lstrcat( strReadmePath, TEXT("\\") ); lstrcat( strReadmePath, strFilename ); if( GetFileAttributes( strReadmePath ) != 0xFFFFFFFF ) bFound = TRUE; } if( !bFound ) { // Search in "%EXE_DIR%\..\Meshes\%EXE_NAME%\". _tcscpy( strReadmePath, strExePath ); strLastSlash = _tcsrchr( strReadmePath, TEXT('\\') ); if( strLastSlash ) *strLastSlash = 0; lstrcat( strReadmePath, TEXT("\\Meshes\\") ); lstrcat( strReadmePath, strExeName ); lstrcat( strReadmePath, TEXT("\\") ); lstrcat( strReadmePath, strFilename ); if( GetFileAttributes( strReadmePath ) != 0xFFFFFFFF ) bFound = TRUE; } if( !bFound ) { // Search in "%EXE_DIR%\..\StencilBuffer\%EXE_NAME%\". _tcscpy( strReadmePath, strExePath ); strLastSlash = _tcsrchr( strReadmePath, TEXT('\\') ); if( strLastSlash ) *strLastSlash = 0; lstrcat( strReadmePath, TEXT("\\StencilBuffer\\") ); lstrcat( strReadmePath, strExeName ); lstrcat( strReadmePath, TEXT("\\") ); lstrcat( strReadmePath, strFilename ); if( GetFileAttributes( strReadmePath ) != 0xFFFFFFFF ) bFound = TRUE; } if( !bFound ) { // Search in "%EXE_DIR%\" _tcscpy( strReadmePath, strExePath ); lstrcat( strReadmePath, TEXT("\\") ); lstrcat( strReadmePath, strFilename ); if( GetFileAttributes( strReadmePath ) != 0xFFFFFFFF ) bFound = TRUE; } if( !bFound ) { // Search in "%EXE_DIR%\.." _tcscpy( strReadmePath, strExePath ); strLastSlash = _tcsrchr( strReadmePath, TEXT('\\') ); if( strLastSlash ) *strLastSlash = 0; lstrcat( strReadmePath, TEXT("\\") ); lstrcat( strReadmePath, strFilename ); if( GetFileAttributes( strReadmePath ) != 0xFFFFFFFF ) bFound = TRUE; } if( !bFound ) { // Search in "%EXE_DIR%\..\.." _tcscpy( strReadmePath, strExePath ); strLastSlash = _tcsrchr( strReadmePath, TEXT('\\') ); if( strLastSlash ) *strLastSlash = 0; strLastSlash = _tcsrchr( strReadmePath, TEXT('\\') ); if( strLastSlash ) *strLastSlash = 0; lstrcat( strReadmePath, TEXT("\\") ); lstrcat( strReadmePath, strFilename ); if( GetFileAttributes( strReadmePath ) != 0xFFFFFFFF ) bFound = TRUE; } if( bFound ) { // GetProcAddress for ShellExecute, so we don't have to include shell32.lib // in every project that uses dxutil.cpp LPShellExecute pShellExecute = NULL; HINSTANCE hInstShell32 = LoadLibrary(TEXT("shell32.dlTEXT(")); if (hInstShell32 != NULL) { #ifdef UNICODE pShellExecute = (LPShellExecute)GetProcAddress(hInstShell32, _TWINCE("ShellExecuteW")); #else pShellExecute = (LPShellExecute)GetProcAddress(hInstShell32, _TWINCE("ShellExecuteA")); #endif if( pShellExecute != NULL ) { if( pShellExecute( hWnd, TEXT("open"), strReadmePath, NULL, NULL, SW_SHOW ) > (HINSTANCE) 32 ) bSuccess = true; } FreeLibrary(hInstShell32); } } if( bSuccess ) return; } // Tell the user that the readme couldn't be opened MessageBox( hWnd, TEXT("Could not find readme"), TEXT("DirectX SDK Sample"), MB_ICONWARNING | MB_OK ); }
UINT ShowMessageBox (UINT Id, UINT Button, UINT Help, ...) { CString temp; TCHAR *pszstring, *pszpaste, *pszcut, *pszdone, *pszconvert; TCHAR chread; va_list params; int x; pszconvert = new TCHAR[255]; va_start(params, Help); LoadString (temp, Id); pszstring = temp.GetBuffer(512); _tcscpy(pszstring,pszstring); temp.ReleaseBuffer(); // Look and see - is there a need to insert chars (95% of the time, there won't) if (!_tcsstr(pszstring, _T("%"))) { delete pszconvert; return AfxMessageBox(pszstring, Button, Help); } x = _tcscspn(pszstring, _T("%")); pszdone = new TCHAR[512]; pszcut = new TCHAR[512]; pszpaste = new TCHAR[512]; _tcscpy(pszcut, &pszstring[x+2]); _tcsncpy(pszpaste, pszstring, x); pszpaste[x] = _T('\0'); chread = pszstring[x+1]; for ( ; ; ) { switch (chread) { case _T('i') : case _T('d') : { int anint = va_arg(params, int); _itot( anint, pszconvert, 10); break; } case _T('u') : { UINT anuint = va_arg(params, UINT); _itot( anuint, pszconvert, 10); break; } case _T('x') : case _T('X') : { int ahex = va_arg(params, int); _itot( ahex, pszconvert, 16); break; } case _T('g') : case _T('f') : case _T('e') : { double adbl = va_arg(params, double); _stprintf(pszconvert, _T("%g"), adbl); break; } case _T('s') : { TCHAR *pStr = va_arg(params, TCHAR*); ASSERT(_tcslen(pStr) <= 255); _tcscpy(pszconvert, pStr); break; } case _T('l') : { chread = pszdone[x+2]; switch(chread) { case _T('x') : { long int alhex = va_arg(params, long int); _ltot(alhex, pszconvert, 16); _tcscpy(pszcut, &pszcut[1]); break; } case _T('d') : default : { long int along = va_arg(params, long int); _ltot( along, pszconvert, 10); // For the L, there will be one character after it, // so move ahead another letter _tcscpy(pszcut, &pszcut[1]); break; } } break; } case _T('c') : { int letter = va_arg(params, int); pszconvert[0] = (TCHAR)letter; pszconvert[1] = '\0'; break; } case _T('a') : { CString zeta; TCHAR* lsc; UINT ls = va_arg(params, UINT); LoadString (zeta, ls); lsc = zeta.GetBuffer(255); _tcscpy(pszconvert, lsc); zeta.ReleaseBuffer(); break; } case _T('o') : { CString get = va_arg(params, CString); TCHAR* ex = get.GetBuffer(255); _tcscpy(pszconvert,ex); get.ReleaseBuffer(); break; } default : { _tcscpy(pszconvert, _T(" Could not load message. Invalid %type in string table entry. ")); delete pszdone; pszdone = new TCHAR[_tcslen(pszpaste)+_tcslen(pszcut)+_tcslen(pszconvert)+5]; _tcscpy(pszdone, pszpaste); _tcscat(pszdone, pszconvert); _tcscat(pszdone, pszcut); AfxMessageBox(pszdone, Button, Help); delete pszcut; delete pszpaste; delete pszconvert; delete pszdone; ASSERT(FALSE); return 0; } } // case delete pszdone; pszdone = new TCHAR[_tcslen(pszpaste)+_tcslen(pszcut)+_tcslen(pszconvert)+5]; _tcscpy(pszdone, pszpaste); _tcscat(pszdone, pszconvert); _tcscat(pszdone, pszcut); // Now pszdone holds the entire message. // Check to see if there are more insertions to be made or not if (!_tcsstr(pszdone, _T("%"))) { UINT rt_type = AfxMessageBox(pszdone, Button, Help); delete pszcut; delete pszpaste; delete pszconvert; delete pszdone; return rt_type; } // if // there are more insertions to make, prepare the strings to use. x = _tcscspn(pszdone, _T("%")); _tcscpy(pszcut, &pszdone[x+2]); _tcsncpy(pszpaste, pszdone, x); pszpaste[x] = _T('\0'); chread = pszdone[x+1]; } // for ASSERT(FALSE); return 0; } // ShowMessageBox
static int add_option(options_t *options, int i, TCHAR **p) { if (streq(p[0], _T("help"))) { TCHAR caption[200]; LoadLocalizedStringBuf(caption, _countof(caption), IDS_NFO_USAGECAPTION); ShowLocalizedMsgEx(MB_OK, caption, IDS_NFO_USAGE); exit(0); } else if (streq(p[0], _T("connect")) && p[1]) { ++i; static int auto_connect_nr = 0; if (auto_connect_nr == MAX_CONFIGS) { /* Too many configs */ ShowLocalizedMsg(IDS_ERR_MANY_CONFIGS, MAX_CONFIGS); exit(1); } options->auto_connect[auto_connect_nr++] = p[1]; } else if (streq(p[0], _T("exe_path")) && p[1]) { ++i; _tcsncpy(options->exe_path, p[1], _countof(options->exe_path) - 1); } else if (streq(p[0], _T("config_dir")) && p[1]) { ++i; _tcsncpy(options->config_dir, p[1], _countof(options->config_dir) - 1); } else if (streq(p[0], _T("ext_string")) && p[1]) { ++i; _tcsncpy(options->ext_string, p[1], _countof(options->ext_string) - 1); } else if (streq(p[0], _T("log_dir")) && p[1]) { ++i; _tcsncpy(options->log_dir, p[1], _countof(options->log_dir) - 1); } else if (streq(p[0], _T("priority_string")) && p[1]) { ++i; _tcsncpy(options->priority_string, p[1], _countof(options->priority_string) - 1); } else if (streq(p[0], _T("append_string")) && p[1]) { ++i; _tcsncpy(options->append_string, p[1], _countof(options->append_string) - 1); } else if (streq(p[0], _T("log_viewer")) && p[1]) { ++i; _tcsncpy(options->log_viewer, p[1], _countof(options->log_viewer) - 1); } else if (streq(p[0], _T("editor")) && p[1]) { ++i; _tcsncpy(options->editor, p[1], _countof(options->editor) - 1); } else if (streq(p[0], _T("allow_edit")) && p[1]) { ++i; _tcsncpy(options->allow_edit, p[1], _countof(options->allow_edit) - 1); } else if (streq(p[0], _T("allow_service")) && p[1]) { ++i; _tcsncpy(options->allow_service, p[1], _countof(options->allow_service) - 1); } else if (streq(p[0], _T("allow_password")) && p[1]) { ++i; _tcsncpy(options->allow_password, p[1], _countof(options->allow_password) - 1); } else if (streq(p[0], _T("allow_proxy")) && p[1]) { ++i; _tcsncpy(options->allow_proxy, p[1], _countof(options->allow_proxy) - 1); } else if (streq(p[0], _T("show_balloon")) && p[1]) { ++i; _tcsncpy(options->show_balloon, p[1], _countof(options->show_balloon) - 1); } else if (streq(p[0], _T("service_only")) && p[1]) { ++i; _tcsncpy(options->service_only, p[1], _countof(options->service_only) - 1); } else if (streq(p[0], _T("show_script_window")) && p[1]) { ++i; _tcsncpy(options->show_script_window, p[1], _countof(options->show_script_window) - 1); } else if (streq(p[0], _T("silent_connection")) && p[1]) { ++i; _tcsncpy(options->silent_connection, p[1], _countof(options->silent_connection) - 1); } else if (streq(p[0], _T("passphrase_attempts")) && p[1]) { ++i; _tcsncpy(options->psw_attempts_string, p[1], _countof(options->psw_attempts_string) - 1); } else if (streq(p[0], _T("connectscript_timeout")) && p[1]) { ++i; _tcsncpy(options->connectscript_timeout_string, p[1], _countof(options->connectscript_timeout_string) - 1); } else if (streq(p[0], _T("disconnectscript_timeout")) && p[1]) { ++i; _tcsncpy(options->disconnectscript_timeout_string, p[1], _countof(options->disconnectscript_timeout_string) - 1); } else if (streq(p[0], _T("preconnectscript_timeout")) && p[1]) { ++i; _tcsncpy(options->preconnectscript_timeout_string, p[1], _countof(options->preconnectscript_timeout_string) - 1); } else { /* Unrecognized option or missing parameter */ ShowLocalizedMsg(IDS_ERR_BAD_OPTION, p[0]); exit(1); } return i; }
int CpDeviceStandby(int argc, _TCHAR* argv[]) { HNDAS hNDAS = NULL; NDASCOMM_CONNECTION_INFO ci; BYTE DeviceID[6]; DWORD dwUnitNo; NDASCOMM_IDE_REGISTER IdeRegister; // // Get arguments. // if(argc < 2) { _ftprintf(stderr, _T("ERROR: More parameter needed.\n")); return -1; } _ftprintf(stdout, _T("Starting the operation...\n")); SetLastError(0); API_CALL(NdasCommInitialize()); // // Connect and login // ZeroMemory(&ci, sizeof(ci)); ci.Size = sizeof(NDASCOMM_CONNECTION_INFO); ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID*/ ci.UnitNo = 0; /* Use first Unit Device */ ci.WriteAccess = TRUE; /* Connect with read-write privilege */ ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */ ci.OEMCode.UI64Value = 0; /* Use default password */ ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */ ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */ _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */ _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */ API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out); // // Display NDAS device info // API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out); _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n", DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5], (int)dwUnitNo); // // Request the NDAS device to enter Standby mode // ZeroMemory(&IdeRegister, sizeof(NDASCOMM_IDE_REGISTER)); IdeRegister.command.command = 0xE0; /* WIN_STANDBYNOW1 */ IdeRegister.device.dev = 0; API_CALL_JMP(NdasCommIdeCommand(hNDAS, &IdeRegister, NULL, 0, NULL, 0), out); out: if(GetLastError()) { _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError()); } if(hNDAS) { NdasCommDisconnect(hNDAS); hNDAS = NULL; } NdasCommUninitialize(); _ftprintf(stdout, _T("Finished the operation.\n")); return GetLastError(); }
int CpQueryLockOwner(int argc, _TCHAR* argv[]) { HNDAS hNDAS = NULL; NDASCOMM_CONNECTION_INFO ci; BYTE DeviceID[6]; DWORD dwUnitNo; NDASCOMM_VCMD_PARAM param_vcmd; ULONG lockIdx; // // Get arguments. // if(argc < 3) { _ftprintf(stderr, _T("ERROR: More parameter needed.\n")); return -1; } lockIdx = _tcstoul(argv[2], NULL, 10); if(lockIdx == 0) { // // Check to see if a user inputs the zero. // if( argv[2][0] != _T('0') || argv[2][1] != _T('\0') ) { _ftprintf(stderr, _T("ERROR: Invalid timeout value.\n")); return -1; } } _ftprintf(stdout, _T("Starting the operation...\n")); SetLastError(0); API_CALL(NdasCommInitialize()); // // Connect and login // ZeroMemory(&ci, sizeof(ci)); ci.Size = sizeof(NDASCOMM_CONNECTION_INFO); ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */ ci.UnitNo = 0; /* Use first Unit Device */ ci.WriteAccess = FALSE; /* Connect with read-only privilege */ ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */ ci.OEMCode.UI64Value = 0; /* Use default password */ ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */ ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */ _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */ _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */ API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out ); // // Display NDAS device info // API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out); _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n", DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5], (int)dwUnitNo); // // Query lock owner // _ftprintf(stderr, _T("Querying lock #%u's owner of the device...\n"), (ULONG)(UINT8)lockIdx); ZeroMemory(¶m_vcmd, sizeof(NDASCOMM_VCMD_PARAM)); param_vcmd.GET_OWNER_SEMA.Index = (UINT8)lockIdx; API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_get_owner_sema, ¶m_vcmd, NULL, 0, NULL, 0), out); out: if(GetLastError()) { _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError()); } else { _ftprintf(stdout, _T("Owner's addr:%02X%02X%02X%02X%02X%02X%02X%02X\n"), param_vcmd.GET_OWNER_SEMA.AddressLPX[0], param_vcmd.GET_OWNER_SEMA.AddressLPX[1], param_vcmd.GET_OWNER_SEMA.AddressLPX[2], param_vcmd.GET_OWNER_SEMA.AddressLPX[3], param_vcmd.GET_OWNER_SEMA.AddressLPX[4], param_vcmd.GET_OWNER_SEMA.AddressLPX[5], param_vcmd.GET_OWNER_SEMA.AddressLPX[6], param_vcmd.GET_OWNER_SEMA.AddressLPX[7]); } if(hNDAS) { NdasCommDisconnect(hNDAS); hNDAS = NULL; } NdasCommUninitialize(); _ftprintf(stdout, _T("Finished the operation.\n")); return GetLastError(); }
int CpSetEncryptionMode(int argc, _TCHAR* argv[]) { HNDAS hNDAS = NULL; NDASCOMM_CONNECTION_INFO ci; BYTE DeviceID[6]; DWORD dwUnitNo; NDASCOMM_VCMD_PARAM param_vcmd; ULONG HeaderEnc; ULONG DataEnc; // // Get arguments. // if(argc < 4) { _ftprintf(stderr, _T("ERROR: Header encryption mode and data encryption mode is required.\n")); return -1; } HeaderEnc = _tcstoul(argv[2], NULL, 10); if(HeaderEnc != 0 && HeaderEnc!=1) { _ftprintf(stderr, _T("ERROR: Avaiable header encryption mode is 0 (off) or 1 (hash encryption).\n")); return -1; } DataEnc = _tcstoul(argv[2], NULL, 10); if(DataEnc != 0 && DataEnc!=1) { _ftprintf(stderr, _T("ERROR: Avaiable header encryption mode is 0 (off) or 1 (hash encryption).\n")); return -1; } SetLastError(0); API_CALL(NdasCommInitialize()); // // Connect and login // ZeroMemory(&ci, sizeof(ci)); ci.Size = sizeof(NDASCOMM_CONNECTION_INFO); ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */ ci.UnitNo = 0; /* Use first Unit Device */ ci.WriteAccess = FALSE; /* Connect with read-write privilege */ ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */ ci.OEMCode.UI64Value = 0; /* Use default password */ /* Log in as super user */ ci.PrivilegedOEMCode = NDAS_DEFAULT_PRIVILEGED_OEM_CODE; /* Privileged Connection cannot use lock commands */ ci.Flags = NDASCOMM_CNF_DISABLE_LOCK_CLEANUP_ON_CONNECT; ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */ _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */ _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */ API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out); // // Display NDAS device info // API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out); _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n", DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5], (int)dwUnitNo); // // Set encryption mode // _ftprintf(stderr, _T("Applying setting to the device...\n")); ZeroMemory(¶m_vcmd, sizeof(NDASCOMM_VCMD_PARAM)); param_vcmd.SET_ENC_OPT.EncryptHeader = HeaderEnc; param_vcmd.SET_ENC_OPT.EncryptData = DataEnc; API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_set_enc_opt, ¶m_vcmd, NULL, 0, NULL, 0), out); _ftprintf(stderr, _T("Resetting the device...\n")); ZeroMemory(¶m_vcmd, sizeof(NDASCOMM_VCMD_PARAM)); API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_reset, ¶m_vcmd, NULL, 0, NULL, 0), out); out: if(GetLastError()) { _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError()); } if(hNDAS) { NdasCommDisconnect(hNDAS); hNDAS = NULL; } NdasCommUninitialize(); _ftprintf(stdout, _T("Finished the operation.\n")); return GetLastError(); }
int CpGetEncryptionMode(int argc, _TCHAR* argv[]) { HNDAS hNDAS = NULL; NDASCOMM_CONNECTION_INFO ci; BYTE DeviceID[6]; DWORD dwUnitNo; NDASCOMM_VCMD_PARAM param_vcmd; /* PNDASCOMM_HANDLE_CONTEXT Context; UINT16 HeaderEnc=FALSE; UINT16 DataEnc = FALSE; */ // // Get arguments. // if(argc < 2) { _ftprintf(stderr, _T("ERROR: More parameter needed.\n")); return -1; } _ftprintf(stdout, _T("Starting the operation...\n")); SetLastError(0); API_CALL(NdasCommInitialize()); // // Connect and login // ZeroMemory(&ci, sizeof(ci)); ci.Size = sizeof(NDASCOMM_CONNECTION_INFO); ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */ ci.UnitNo = 0; /* Use first Unit Device */ ci.WriteAccess = FALSE; /* Connect with read-write privilege */ ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */ ci.OEMCode.UI64Value = 0; /* Use default password */ ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */ ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */ _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */ _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */ API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out); // // Display NDAS device info // API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out); _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n", DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5], (int)dwUnitNo); _tprintf(L"This vendor operation is not supported yet\n"); /* Context = NdasHandleToContext(hNDAS); lsp_get_handle_info( Context->hLSP, lsp_handle_info_hw_header_encrypt_algo, &HeaderEnc, sizeof(HeaderEnc)); lsp_get_handle_info( Context->hLSP, lsp_handle_info_hw_data_encrypt_algo, &DataEnc, sizeof(DataEnc)); */ out: if(GetLastError()) { _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError()); } if(hNDAS) { NdasCommDisconnect(hNDAS); hNDAS = NULL; } NdasCommUninitialize(); _ftprintf(stdout, _T("Finished the operation.\n")); // _ftprintf(stderr, _T("\nRetransmission time: %d milli-seconds.\n"), param_vcmd.GET_MAX_CONN_TIME.MaxConnTime); return GetLastError(); }
// GetReplaceString - Converts a replace expression to a string // Returns - Pointer to newly allocated string // Caller is responsible for deleting it TCHAR* CRegExp::GetReplaceString(const TCHAR* sReplaceExp) { TCHAR *src = (TCHAR *)sReplaceExp; TCHAR *buf; TCHAR c; int no; size_t len; if (sReplaceExp == NULL || sFoundText == NULL) return NULL; // First compute the length of the string int replacelen = 0; while ((c = *src++) != _T('\0')) { if (c == _T('&')) no = 0; else if (c == _T('\\') && isdigit(*src)) no = *src++ - _T('0'); else no = -1; if (no < 0) { // Ordinary character. if (c == _T('\\') && (*src == _T('\\') || *src == _T('&'))) c = *src++; replacelen++; } else if (startp[no] != NULL && endp[no] != NULL && endp[no] > startp[no]) { // Get tagged expression len = endp[no] - startp[no]; replacelen += len; } } // Now allocate buf buf = new TCHAR[replacelen + 1]; if (buf == NULL) return NULL; TCHAR* sReplaceStr = buf; // Add null termination buf[replacelen] = _T('\0'); // Now we can create the string src = (TCHAR *)sReplaceExp; while ((c = *src++) != _T('\0')) { if (c == _T('&')) no = 0; else if (c == _T('\\') && isdigit(*src)) no = *src++ - _T('0'); else no = -1; if (no < 0) { // Ordinary character. if (c == _T('\\') && (*src == _T('\\') || *src == _T('&'))) c = *src++; *buf++ = c; } else if (startp[no] != NULL && endp[no] != NULL && endp[no] > startp[no]) { // Get tagged expression len = endp[no] - startp[no]; int tagpos = startp[no] - startp[0]; _tcsncpy(buf, sFoundText + tagpos, len); buf += len; } } return sReplaceStr; }
// RegFind - match a regexp against a string // Returns - Returns position of regexp or -1 // if regular expression not found // Note - The regular expression should have been // previously compiled using RegComp int CRegExp::RegFind(const TCHAR *str) { TCHAR *string = (TCHAR *)str; // avert const poisoning TCHAR *s; // Delete any previously stored found string delete sFoundText; sFoundText = NULL; // Be paranoid. if (string == NULL) { TRACE0("NULL argument to regexec\n"); return(-1); } // Check validity of regex if (!bCompiled) { TRACE0("No regular expression provided yet.\n"); return(-1); } // If there is a "must appear" string, look for it. if (regmust != NULL && _tcsstr(string, regmust) == NULL) return(-1); // Mark beginning of line for ^ regbol = string; // Simplest case: anchored match need be tried only once. if (reganch) { if (regtry(string)) { // Save the found substring in case we need it sFoundText = new TCHAR[GetFindLen() + 1]; sFoundText[GetFindLen()] = _T('\0'); _tcsncpy(sFoundText, string, GetFindLen()); return 0; } //String not found return -1; } // Messy cases: unanchored match. if (regstart != _T('\0')) { // We know what TCHAR it must start with. for (s = string; s != NULL; s = _tcschr(s + 1, regstart)) if (regtry(s)) { int nPos = s - str; // Save the found substring in case we need it later sFoundText = new TCHAR[GetFindLen() + 1]; sFoundText[GetFindLen()] = _T('\0'); _tcsncpy(sFoundText, s, GetFindLen()); return nPos; } return -1; } else { // We don't -- general case for (s = string; !regtry(s); s++) if (*s == _T('\0')) return(-1); int nPos = s - str; // Save the found substring in case we need it later sFoundText = new TCHAR[GetFindLen() + 1]; sFoundText[GetFindLen()] = _T('\0'); _tcsncpy(sFoundText, s, GetFindLen()); return nPos; } // NOTREACHED }
int _tmain(int argc, char **argv) { int i; TCHAR lpStr[80]; for (i = 0; i < 80; i++) lpEmpty[i] = lpHeader[i] = _T(' '); lpEmpty[79] = _T('\0'); /* Initialize global variables */ hInst = 0 /* FIXME: which value? [used with LoadString(hInst, ..., ..., ...)] */; if (LoadString(hInst, IDS_COLUMN_NUMBER, lpStr, 80)) { columnRightPositions[0] = _tcslen(lpStr) + 3; _tcsncpy(&lpHeader[2], lpStr, _tcslen(lpStr)); } if (LoadString(hInst, IDS_COLUMN_IMAGENAME, lpStr, 80)) { columnRightPositions[1] = columnRightPositions[0] + _tcslen(lpStr) + 3; _tcsncpy(&lpHeader[columnRightPositions[0] + 2], lpStr, _tcslen(lpStr)); } if (LoadString(hInst, IDS_COLUMN_PID, lpStr, 80)) { columnRightPositions[2] = columnRightPositions[1] + _tcslen(lpStr) + 3; _tcsncpy(&lpHeader[columnRightPositions[1] + 2], lpStr, _tcslen(lpStr)); } if (LoadString(hInst, IDS_COLUMN_CPU, lpStr, 80)) { columnRightPositions[3] = columnRightPositions[2] + _tcslen(lpStr) + 3; _tcsncpy(&lpHeader[columnRightPositions[2] + 2], lpStr, _tcslen(lpStr)); } if (LoadString(hInst, IDS_COLUMN_MEM, lpStr, 80)) { columnRightPositions[4] = columnRightPositions[3] + _tcslen(lpStr) + 3; _tcsncpy(&lpHeader[columnRightPositions[3] + 2], lpStr, _tcslen(lpStr)); } if (LoadString(hInst, IDS_COLUMN_PF, lpStr, 80)) { columnRightPositions[5] = columnRightPositions[4] + _tcslen(lpStr) + 3; _tcsncpy(&lpHeader[columnRightPositions[4] + 2], lpStr, _tcslen(lpStr)); } for (i = 0; i < columnRightPositions[5]; i++) lpSeparator[i] = _T('-'); lpHeader[0] = _T('|'); lpSeparator[0] = _T('+'); for (i = 0; i < 6; i++) { lpHeader[columnRightPositions[i]] = _T('|'); lpSeparator[columnRightPositions[i]] = _T('+'); } lpSeparator[columnRightPositions[5] + 1] = _T('\0'); lpHeader[columnRightPositions[5] + 1] = _T('\0'); if (!LoadString(hInst, IDS_APP_TITLE, lpTitle, 80)) lpTitle[0] = _T('\0'); if (!LoadString(hInst, IDS_COLUMN_MEM_UNIT, lpMemUnit, 3)) lpMemUnit[0] = _T('\0'); if (!LoadString(hInst, IDS_MENU, lpMenu, 80)) lpMenu[0] = _T('\0'); if (!LoadString(hInst, IDS_IDLE_PROCESS, lpIdleProcess, 80)) lpIdleProcess[0] = _T('\0'); if (LoadString(hInst, IDS_MENU_QUIT, lpStr, 2)) KEY_QUIT = lpStr[0]; if (LoadString(hInst, IDS_MENU_KILL_PROCESS, lpStr, 2)) KEY_KILL = lpStr[0]; if (LoadString(hInst, IDS_YES, lpStr, 2)) KEY_YES = lpStr[0]; if (LoadString(hInst, IDS_NO, lpStr, 2)) KEY_NO = lpStr[0]; GetInputOutputHandles(); if (hStdin == INVALID_HANDLE_VALUE || hStdout == INVALID_HANDLE_VALUE) { if (LoadString(hInst, IDS_CTM_GENERAL_ERR1, lpStr, 80)) _tprintf(lpStr); return -1; } if (GetConsoleMode(hStdin, &inConMode) == 0) { if (LoadString(hInst, IDS_CTM_GENERAL_ERR2, lpStr, 80)) _tprintf(lpStr); return -1; } if (GetConsoleMode(hStdout, &outConMode) == 0) { if (LoadString(hInst, IDS_CTM_GENERAL_ERR3, lpStr, 80)) _tprintf(lpStr); return -1; } SetConsoleMode(hStdin, 0); //FIXME: Should check for error! SetConsoleMode(hStdout, 0); //FIXME: Should check for error! PerfInit(); while (1) { DWORD numEvents; PerfDataRefresh(); DisplayScreen(); /* WaitForSingleObject for console handles is not implemented in ROS */ WaitForSingleObject(hStdin, 1000); GetNumberOfConsoleInputEvents(hStdin, &numEvents); if (numEvents > 0) { if (ProcessKeys(numEvents) == TRUE) break; } } RestoreConsole(); return 0; }
void CLATEDView::OnGetDispInfo(NMHDR* pNMHDR, LRESULT* pResult) { TV_DISPINFO* pDisp = (TV_DISPINFO*)pNMHDR; CString str; CLCBase * pBase = NULL; DWORD dwData; CTreeCtrl& rTree = GetTreeCtrl(); dwData = rTree.GetItemData(pDisp->item.hItem); *pResult = 0; switch(dwData) { case 1UL: if (pDisp->item.mask & TVIF_TEXT) { _tcsncpy(pDisp->item.pszText, m_strLinkGroupLabel,pDisp->item.cchTextMax); } if (pDisp->item.mask & TVIF_IMAGE) { pDisp->item.iImage = LATED_IMAGEID_GROUP; } // query for selected image: if (pDisp->item.mask & TVIF_SELECTEDIMAGE) { pDisp->item.iSelectedImage = LATED_IMAGEID_GROUP; } break; case 2UL: if (pDisp->item.mask & TVIF_TEXT) { _tcsncpy(pDisp->item.pszText, m_strDataGroupLabel,pDisp->item.cchTextMax); } if (pDisp->item.mask & TVIF_IMAGE) { pDisp->item.iImage = LATED_IMAGEID_DATAGROUP; } // query for selected image: if (pDisp->item.mask & TVIF_SELECTEDIMAGE) { pDisp->item.iSelectedImage = LATED_IMAGEID_DATAGROUP; } break; case 0UL: return; default: pBase = GetNode(pDisp->item.hItem); if(!pBase) { break; } if (pDisp->item.mask & TVIF_TEXT) { pBase->GetName(str); _tcsncpy(pDisp->item.pszText,str,pDisp->item.cchTextMax); } if (pDisp->item.mask & TVIF_IMAGE) { pDisp->item.iImage = pBase->GetImageId(); } // query for selected image: if (pDisp->item.mask & TVIF_SELECTEDIMAGE) { pDisp->item.iSelectedImage = pBase->GetImageId(); } break; } }
int CpQueryConTimeout(int argc, _TCHAR* argv[]) { HNDAS hNDAS = NULL; NDASCOMM_CONNECTION_INFO ci; BYTE DeviceID[6]; DWORD dwUnitNo; NDASCOMM_VCMD_PARAM param_vcmd; // // Get arguments. // if(argc < 2) { _ftprintf(stderr, _T("ERROR: More parameter needed.\n")); return -1; } _ftprintf(stdout, _T("Starting the operation...\n")); SetLastError(0); API_CALL(NdasCommInitialize()); // // Connect and login // ZeroMemory(&ci, sizeof(ci)); ci.Size = sizeof(NDASCOMM_CONNECTION_INFO); ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */ ci.UnitNo = 0; /* Use first Unit Device */ ci.WriteAccess = FALSE; /* Connect with read-write privilege */ ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */ ci.OEMCode.UI64Value = 0; /* Use default password */ ci.PrivilegedOEMCode.UI64Value = 0; /* Log in as normal user */ ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */ _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */ _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */ API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out); // // Display NDAS device info // API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out); _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n", DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5], (int)dwUnitNo); // // Query Connection timeout // ZeroMemory(¶m_vcmd, sizeof(NDASCOMM_VCMD_PARAM)); API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_get_max_conn_time, ¶m_vcmd, NULL, 0, NULL, 0), out); out: if(GetLastError()) { _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError()); } if(hNDAS) { NdasCommDisconnect(hNDAS); hNDAS = NULL; } NdasCommUninitialize(); _ftprintf(stdout, _T("Finished the operation.\n")); _ftprintf(stderr, _T("\nConnection timeout: %d.\n"), param_vcmd.GET_MAX_CONN_TIME.MaxConnTime); return GetLastError(); }
int ParseArgument(TCHAR *pszToken, unsigned char **ppucBuffer, int *piSize) { TCHAR *pszPrefix; TCHAR *pszValue; int iToken; int iIter; int iByte; char szByte[3]; if (ParseStringColonString(pszToken, &pszPrefix, &pszValue)) return 0; iToken = LookupToken(pszPrefix); free(pszPrefix); switch(iToken) { case TOK_HEX: *piSize = _tcslen(pszValue)/sizeof(TCHAR)/2; *ppucBuffer = malloc(*piSize); if (*ppucBuffer == NULL) { free(pszValue); return 0; } szByte[2] = TCHAR_NULL; for (iIter=0; iIter<*piSize; iIter++) { szByte[0] = pszValue[iIter*2]; szByte[1] = pszValue[iIter*2+1]; sscanf(szByte, "%2x", &iByte); (*ppucBuffer)[iIter] = (unsigned char) iByte; } break; case TOK_UNICODE: *piSize = _tcslen(pszValue)/sizeof(TCHAR)*2; *ppucBuffer = malloc(*piSize); if (*ppucBuffer == NULL) { free(pszValue); return 0; } for (iIter=0; iIter<*piSize/2; iIter++) { (*ppucBuffer)[iIter*2] = (unsigned char) pszValue[iIter]; (*ppucBuffer)[iIter*2+1] = '\0'; } break; case TOK_ASCII: *piSize = _tcslen(pszValue)/sizeof(TCHAR); *ppucBuffer = malloc(*piSize); if (*ppucBuffer == NULL) return 0; _tcsncpy(*ppucBuffer, pszValue, *piSize); break; case TOK_FILE: *piSize = _tcslen(pszValue)/sizeof(TCHAR) + 1; *ppucBuffer = pszValue; break; default: iToken = 0; } return iToken; }
int CpSetMacAddress(int argc, _TCHAR* argv[]) { HNDAS hNDAS = NULL; NDASCOMM_CONNECTION_INFO ci; BYTE DeviceID[6]; DWORD dwUnitNo; NDASCOMM_VCMD_PARAM param_vcmd; _TCHAR *MacAddress; size_t argv_len; ULONG MacAddressSegs[6]; // // Get arguments. // if(argc < 3) { _ftprintf(stderr, _T("ERROR: More parameter needed.\n")); return -1; } // Mac address : XX:XX:XX:XX:XX:XX MacAddress = argv[2]; if(17 != _tcslen(MacAddress) || _T(':') != MacAddress[2] || _T(':') != MacAddress[5] || _T(':') != MacAddress[8] || _T(':') != MacAddress[11] || _T(':') != MacAddress[14]) { _ftprintf(stderr, _T("ERROR: Invalid MAC address. \n")); return -1; } if(6 != _stscanf(MacAddress, _T("%02X:%02X:%02X:%02X:%02X:%02X"), &MacAddressSegs[0], &MacAddressSegs[1], &MacAddressSegs[2], &MacAddressSegs[3], &MacAddressSegs[4], &MacAddressSegs[5])) { _ftprintf(stderr, _T("ERROR: Invalid MAC address. \n")); return -1; } _ftprintf(stdout, _T("Starting the operation...\n")); SetLastError(0); API_CALL(NdasCommInitialize()); // // Connect and login // ZeroMemory(&ci, sizeof(ci)); ci.Size = sizeof(NDASCOMM_CONNECTION_INFO); ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */ ci.UnitNo = 0; /* Use first Unit Device */ ci.WriteAccess = FALSE; /* Connect with read-write privilege */ ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */ ci.OEMCode.UI64Value = 0; /* Use default password */ /* Log in as super user */ ci.PrivilegedOEMCode = NDAS_DEFAULT_PRIVILEGED_OEM_CODE; /* Privileged Connection cannot use lock commands */ ci.Flags = NDASCOMM_CNF_DISABLE_LOCK_CLEANUP_ON_CONNECT; ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */ _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */ _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */ API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out); // // Display NDAS device info // API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out); _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n", DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5], (int)dwUnitNo); // // Set Mac address // _ftprintf(stderr, _T("Applying setting to the device...\n")); ZeroMemory(¶m_vcmd, sizeof(NDASCOMM_VCMD_PARAM)); param_vcmd.SET_LPX_ADDRESS.AddressLPX[0] = (BYTE)MacAddressSegs[0]; param_vcmd.SET_LPX_ADDRESS.AddressLPX[1] = (BYTE)MacAddressSegs[1]; param_vcmd.SET_LPX_ADDRESS.AddressLPX[2] = (BYTE)MacAddressSegs[2]; param_vcmd.SET_LPX_ADDRESS.AddressLPX[3] = (BYTE)MacAddressSegs[3]; param_vcmd.SET_LPX_ADDRESS.AddressLPX[4] = (BYTE)MacAddressSegs[4]; param_vcmd.SET_LPX_ADDRESS.AddressLPX[5] = (BYTE)MacAddressSegs[5]; API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_set_lpx_address, ¶m_vcmd, NULL, 0, NULL, 0), out); _ftprintf(stderr, _T("Resetting the device...\n")); ZeroMemory(¶m_vcmd, sizeof(NDASCOMM_VCMD_PARAM)); API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_reset, ¶m_vcmd, NULL, 0, NULL, 0), out); out: if(GetLastError()) { _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError()); } if(hNDAS) { NdasCommDisconnect(hNDAS); hNDAS = NULL; } NdasCommUninitialize(); _ftprintf(stdout, _T("Finished the operation.\n")); return GetLastError(); }
void CDirectoryTreeCtrl::Init(void) { #ifdef _UNICODE SendMessage(CCM_SETUNICODEFORMAT, TRUE); #endif ShowWindow(SW_HIDE); DeleteAllItems(); ModifyStyle( 0, TVS_CHECKBOXES ); // START: added by FoRcHa ///////////// WORD wWinVer = thePrefs.GetWindowsVersion(); // maybe causes problems on 98 & nt4 if(wWinVer == _WINVER_2K_ || wWinVer == _WINVER_XP_ || wWinVer == _WINVER_ME_) { SHFILEINFO shFinfo; HIMAGELIST hImgList = NULL; // Get the system image list using a "path" which is available on all systems. [patch by bluecow] hImgList = (HIMAGELIST)SHGetFileInfo(_T("."), 0, &shFinfo, sizeof(shFinfo), SHGFI_SYSICONINDEX | SHGFI_SMALLICON); if(!hImgList) { TRACE(_T("Cannot retrieve the Handle of SystemImageList!")); //return; } m_image.m_hImageList = hImgList; SetImageList(&m_image, TVSIL_NORMAL); } //////////////////////////////// TCHAR drivebuffer[500]; ::GetLogicalDriveStrings(ARRSIZE(drivebuffer), drivebuffer); // e.g. "a:\ c:\ d:\" const TCHAR* pos = drivebuffer; while(*pos != _T('\0')){ // Copy drive name TCHAR drive[4]; _tcsncpy(drive, pos, ARRSIZE(drive)); drive[ARRSIZE(drive) - 1] = _T('\0'); switch(drive[0]){ case _T('a'): case _T('A'): case _T('b'): case _T('B'): // Skip floppy disk break; default: drive[2] = _T('\0'); AddChildItem(NULL, drive); // e.g. ("c:") } // Point to the next drive (4 chars interval) pos = &pos[4]; } ShowWindow(SW_SHOW); }
int CpSetRetTime(int argc, _TCHAR* argv[]) { HNDAS hNDAS = NULL; NDASCOMM_CONNECTION_INFO ci; BYTE DeviceID[6]; DWORD dwUnitNo; NDASCOMM_VCMD_PARAM param_vcmd; ULONG retTime; // // Get arguments. // if(argc < 3) { _ftprintf(stderr, _T("ERROR: More parameter needed.\n")); return -1; } retTime = _tcstoul(argv[2], NULL, 10); if(retTime == 0) { // // Check to see if a user inputs the zero. // if( argv[2][0] != _T('0') || argv[2][1] != _T('\0') ) { _ftprintf(stderr, _T("ERROR: Invalid timeout value.\n")); return -1; } } _ftprintf(stdout, _T("Starting the operation...\n")); SetLastError(0); API_CALL(NdasCommInitialize()); // // Connect and login // ZeroMemory(&ci, sizeof(ci)); ci.Size = sizeof(NDASCOMM_CONNECTION_INFO); ci.AddressType = NDASCOMM_CIT_NDAS_ID; /* Use NDAS ID */ ci.UnitNo = 0; /* Use first Unit Device */ ci.WriteAccess = FALSE; /* Connect with read-write privilege */ ci.Protocol = NDASCOMM_TRANSPORT_LPX; /* Use LPX protocol */ ci.OEMCode.UI64Value = 0; /* Use default password */ /* Log in as super user */ ci.PrivilegedOEMCode = NDAS_DEFAULT_PRIVILEGED_OEM_CODE; /* Privileged Connection cannot use lock commands */ ci.Flags = NDASCOMM_CNF_DISABLE_LOCK_CLEANUP_ON_CONNECT; ci.LoginType = NDASCOMM_LOGIN_TYPE_NORMAL; /* Normal operations */ _tcsncpy(ci.Address.NdasId.Id, argv[0], 20); /* ID */ _tcsncpy(ci.Address.NdasId.Key, argv[1], 5); /* Key */ API_CALL_JMP( hNDAS = NdasCommConnect(&ci), out); // // Display NDAS device info // API_CALL_JMP(NdasCommGetDeviceID(hNDAS, DeviceID, &dwUnitNo), out); _tprintf(L"DeviceID : %02X%02X%02X%02X%02X%02X, Unit No. : %d\n", DeviceID[0], DeviceID[1], DeviceID[2], DeviceID[3], DeviceID[4], DeviceID[5], (int)dwUnitNo); // // Set connection timeout // _ftprintf(stderr, _T("Applying setting to the device...\n")); ZeroMemory(¶m_vcmd, sizeof(NDASCOMM_VCMD_PARAM)); param_vcmd.SET_RET_TIME.RetTime = retTime; API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_set_ret_time, ¶m_vcmd, NULL, 0, NULL, 0), out); _ftprintf(stderr, _T("Resetting the device...\n")); ZeroMemory(¶m_vcmd, sizeof(NDASCOMM_VCMD_PARAM)); API_CALL_JMP(NdasCommVendorCommand(hNDAS, ndascomm_vcmd_reset, ¶m_vcmd, NULL, 0, NULL, 0), out); out: if(GetLastError()) { _ftprintf(stdout, _T("Error! Code:%08lx\n"), GetLastError()); } if(hNDAS) { NdasCommDisconnect(hNDAS); hNDAS = NULL; } NdasCommUninitialize(); _ftprintf(stdout, _T("Finished the operation.\n")); return GetLastError(); }
static void RebuildPageTree(HWND hdlg, OptionsDlgData *dat) { BOOL bRemoveFocusFromFilter = FALSE; HINSTANCE FilterInst = NULL; LPARAM oldSel = SendDlgItemMessage(hdlg, IDC_KEYWORD_FILTER, CB_GETEDITSEL, 0, 0); GetDlgItemText(hdlg, IDC_KEYWORD_FILTER, dat->szFilterString, SIZEOF(dat->szFilterString)); //if filter string is set to all modules then make the filter string empty (this will return all modules) if (_tcscmp(dat->szFilterString, TranslateT(ALL_MODULES_FILTER)) == 0) { dat->szFilterString[0] = 0; bRemoveFocusFromFilter = TRUE; } //if filter string is set to core modules replace it with the name of the executable (this will return all core modules) else if (_tcscmp(dat->szFilterString, TranslateT(CORE_MODULES_FILTER)) == 0) { //replace string with process name - that will show core settings TCHAR szFileName[300]; GetModuleFileName(NULL, szFileName, SIZEOF(szFileName)); TCHAR *pos = _tcsrchr(szFileName, _T('\\')); if (pos) pos++; else pos = szFileName; _tcsncpy(dat->szFilterString, pos, SIZEOF(dat->szFilterString)); } else { int sel = SendMessage(GetDlgItem(hdlg, IDC_KEYWORD_FILTER), (UINT)CB_GETCURSEL, 0, 0); if (sel != -1) { HINSTANCE hinst = (HINSTANCE)SendMessage(GetDlgItem(hdlg, IDC_KEYWORD_FILTER), (UINT)CB_GETITEMDATA, sel, 0); TCHAR szFileName[300]; GetModuleFileName(hinst, szFileName, SIZEOF(szFileName)); TCHAR *pos = _tcsrchr(szFileName, _T('\\')); if (pos) pos++; else pos = szFileName; _tcsncpy(dat->szFilterString, pos, SIZEOF(dat->szFilterString)); } } _tcslwr_locale(dat->szFilterString); //all strings are stored as lowercase ... make sure filter string is lowercase too HWND hwndTree = GetDlgItem(hdlg, IDC_PAGETREE); SendMessage(hwndTree, WM_SETREDRAW, FALSE, 0); HWND oldWnd = NULL; HWND oldTab = NULL; OptionsPageData *opd = dat->getCurrent(); if (opd != NULL) { oldWnd = opd->hwnd; if (opd->insideTab) oldTab = GetDlgItem(hdlg, IDC_TAB); } dat->hCurrentPage = NULL; TreeView_SelectItem(hwndTree, NULL); TreeView_DeleteAllItems(hwndTree); TVINSERTSTRUCT tvis; tvis.hParent = NULL; tvis.hInsertAfter = TVI_SORT; tvis.item.mask = TVIF_TEXT | TVIF_STATE | TVIF_PARAM; tvis.item.state = tvis.item.stateMask = TVIS_EXPANDED; for (int i = 0; i < dat->arOpd.getCount(); i++) { static TCHAR *fullTitle = NULL; mir_free(fullTitle); fullTitle = NULL; if (!CheckPageShow(hdlg, dat, i)) continue; opd = dat->arOpd[i]; TCHAR *ptszGroup = TranslateTH(opd->hLangpack, opd->ptszGroup); TCHAR *ptszTitle = opd->getString(opd->ptszTitle); TCHAR *ptszTab = TranslateTH(opd->hLangpack, opd->ptszTab); tvis.hParent = NULL; if (FilterInst != NULL) { size_t sz = ptszGroup ? _tcslen(ptszGroup) + 1 : 0; if (sz) sz += 3; sz += ptszTitle ? _tcslen(ptszTitle) + 1 : 0; fullTitle = (TCHAR*)mir_alloc(sz*sizeof(TCHAR)); mir_sntprintf(fullTitle, sz, (ptszGroup && ptszTitle) ? _T("%s - %s") : _T("%s%s"), ptszGroup ? ptszGroup : _T(""), ptszTitle ? ptszTitle : _T("")); } TCHAR *useTitle = fullTitle ? fullTitle : ptszTitle; if (ptszGroup != NULL && FilterInst == NULL) { tvis.hParent = FindNamedTreeItemAtRoot(hwndTree, ptszGroup); if (tvis.hParent == NULL) { tvis.item.lParam = -1; tvis.item.pszText = ptszGroup; tvis.hParent = TreeView_InsertItem(hwndTree, &tvis); } } else { TVITEM tvi; tvi.hItem = FindNamedTreeItemAtRoot(hwndTree, useTitle); if (tvi.hItem != NULL) { if (i == dat->currentPage) dat->hCurrentPage = tvi.hItem; tvi.mask = TVIF_PARAM; TreeView_GetItem(hwndTree, &tvi); if (tvi.lParam == -1) { tvi.lParam = i; TreeView_SetItem(hwndTree, &tvi); continue; } } } if (ptszTab != NULL) { HTREEITEM hItem; if (tvis.hParent == NULL) hItem = FindNamedTreeItemAtRoot(hwndTree, useTitle); else hItem = FindNamedTreeItemAtChildren(hwndTree, tvis.hParent, useTitle); if (hItem != NULL) { if (i == dat->currentPage) { TVITEM tvi; tvi.hItem = hItem; tvi.mask = TVIF_PARAM; tvi.lParam = dat->currentPage; TreeView_SetItem(hwndTree, &tvi); dat->hCurrentPage = hItem; } continue; } } tvis.item.pszText = useTitle; tvis.item.lParam = i; opd->hTreeItem = TreeView_InsertItem(hwndTree, &tvis); if (i == dat->currentPage) dat->hCurrentPage = opd->hTreeItem; if (fullTitle) mir_free(fullTitle); fullTitle = NULL; } char str[128]; TVITEMA tvi; tvi.mask = TVIF_TEXT | TVIF_STATE; tvi.pszText = str; tvi.cchTextMax = SIZEOF(str); tvi.hItem = TreeView_GetRoot(hwndTree); while (tvi.hItem != NULL) { if (SendMessageA(hwndTree, TVM_GETITEMA, 0, (LPARAM)&tvi)) { char buf[130]; mir_snprintf(buf, SIZEOF(buf), "%s%s", OPTSTATE_PREFIX, str); if (!db_get_b(NULL, "Options", buf, 1)) TreeView_Expand(hwndTree, tvi.hItem, TVE_COLLAPSE); } tvi.hItem = TreeView_GetNextSibling(hwndTree, tvi.hItem); } if (dat->hCurrentPage == NULL) { dat->hCurrentPage = TreeView_GetRoot(hwndTree); dat->currentPage = -1; } TreeView_SelectItem(hwndTree, dat->hCurrentPage); if (oldWnd) { opd = dat->getCurrent(); if (opd && oldWnd != opd->hwnd) { ShowWindow(oldWnd, SW_HIDE); if (oldTab && (opd == NULL || !opd->insideTab)) ShowWindow(oldTab, SW_HIDE); } } if (dat->szFilterString[0] == 0) // Clear the keyword combo box SetWindowText(GetDlgItem(hdlg, IDC_KEYWORD_FILTER), _T("")); if (!bRemoveFocusFromFilter) SetFocus(GetDlgItem(hdlg, IDC_KEYWORD_FILTER)); //set the focus back to the combo box SendDlgItemMessage(hdlg, IDC_KEYWORD_FILTER, CB_SETEDITSEL, 0, oldSel); //but don't select any of the text SendMessage(hwndTree, WM_SETREDRAW, TRUE, 0); TreeView_EnsureVisible(hwndTree, dat->hCurrentPage); }
DWORD ShortPathToLongPath(LPCTSTR lpszShortPath,LPTSTR lpszLongPath,DWORD cchBuffer) { LONG i=0; TCHAR path[_MAX_PATH]={0}; TCHAR ret[_MAX_PATH]={0}; LONG pos=0, prev_pos=0; LONG len=_tcslen(lpszShortPath); /* Is the string valid? */ if (!lpszShortPath) { SetLastError(ERROR_INVALID_PARAMETER); return 0; } /* Is the path valid? */ if (GetFileAttributes(lpszShortPath)==INVALID_FILE_ATTRIBUTES) return 0; /* Convert "/" to "\" */ for (i=0;i<len;++i) { if (lpszShortPath[i]==_T('/')) path[i]=_T('\\'); else path[i]=lpszShortPath[i]; } /* UNC path? */ if (path[0]==_T('\\') && path[1]==_T('\\')) { pos=2; for (i=0;i<2;++i) { while (path[pos]!=_T('\\') && path[pos]!=_T('\0')) ++pos; ++pos; } _tcsncpy(ret,path,pos-1); } /* Drive letter? */ else if (path[1]==_T(':')) { if (path[2]==_T('\\')) pos=3; if (len==3) { if (cchBuffer>3) _tcscpy(lpszLongPath,lpszShortPath); return len; } _tcsncpy(ret,path,2); } /* Expand the path for each subpath, and strip trailing backslashes */ for (prev_pos = pos-1;pos<=len;++pos) { if (path[pos]==_T('\\') || (path[pos]==_T('\0') && path[pos-1]!=_T('\\'))) { WIN32_FIND_DATA fd; HANDLE hf=0; TCHAR c=path[pos]; char* new_element; path[pos]=_T('\0'); /* the path[prev_pos+1]... path[pos] range is the part of path we're handling right now. We need to find long name for that element and add it. */ new_element = path + prev_pos + 1; /* First add separator, but only if there's something in result already. */ if (ret[0] != _T('\0')) { _tcscat(ret,_T("\\")); } /* If it's ".." element, we need to append it, not the name in parent that FindFirstFile will return. Same goes for "." */ if (new_element[0] == _T('.') && new_element[1] == _T('\0') || new_element[0] == _T('.') && new_element[1] == _T('.') && new_element[2] == _T('\0')) { _tcscat(ret, new_element); } else { hf=FindFirstFile(path, &fd); if (hf==INVALID_HANDLE_VALUE) return 0; _tcscat(ret,fd.cFileName); FindClose(hf); } path[pos]=c; prev_pos = pos; } } len=_tcslen(ret)+1; if (cchBuffer>=len) _tcscpy(lpszLongPath,ret); return len; }
//----------------------------------------------------------------------------- // Name: DXUtil_FindMediaFileCch() // Desc: Trys to find the location of a SDK media file // cchDest is the size in TCHARs of strDestPath. Be careful not to // pass in sizeof(strDest) on UNICODE builds. //----------------------------------------------------------------------------- HRESULT DXUtil_FindMediaFileCch( TCHAR* strDestPath, int cchDest, LPCTSTR strFilename ) { bool bFound; TCHAR strSearchFor[MAX_PATH]; if( NULL==strFilename || strFilename[0] == 0 || NULL==strDestPath || cchDest < 10 ) return E_INVALIDARG; // Get the DirectX SDK's media dir if the SDK is installed TCHAR strMediaDir[MAX_PATH] = {0}; DXUtil_GetDXSDKMediaPathCch( strMediaDir, MAX_PATH ); // Get the exe name, and exe path TCHAR strExePath[MAX_PATH] = {0}; TCHAR strExeName[MAX_PATH] = {0}; TCHAR* strLastSlash = NULL; GetModuleFileName( NULL, strExePath, MAX_PATH ); strExePath[MAX_PATH-1]=0; strLastSlash = _tcsrchr( strExePath, TEXT('\\') ); if( strLastSlash ) { lstrcpyn( strExeName, &strLastSlash[1], MAX_PATH ); // Chop the exe name from the exe path *strLastSlash = 0; // Chop the .exe from the exe name strLastSlash = _tcsrchr( strExeName, TEXT('.') ); if( strLastSlash ) *strLastSlash = 0; } // Typical directories: // .\ // ..\ // ..\..\ // %EXE_DIR%\ // %EXE_DIR%\..\ // %EXE_DIR%\..\..\ // %EXE_DIR%\..\%EXE_NAME% // %EXE_DIR%\..\..\%EXE_NAME% // DXSDK media path // Typical directory search bFound = DXUtil_FindMediaSearchTypicalDirs( strDestPath, cchDest, strFilename, strExePath, strExeName, strMediaDir ); if( bFound ) return S_OK; // Typical directory search again, but also look in a subdir called "\media\" _sntprintf( strSearchFor, MAX_PATH, TEXT("media\\%s"), strFilename ); strSearchFor[MAX_PATH-1] = 0; bFound = DXUtil_FindMediaSearchTypicalDirs( strDestPath, cchDest, strSearchFor, strExePath, strExeName, strMediaDir ); if( bFound ) return S_OK; TCHAR strLeafName[MAX_PATH] = {0}; // Search all parent directories starting at .\ and using strFilename as the leaf name _tcsncpy( strLeafName, strFilename, MAX_PATH ); strLeafName[MAX_PATH-1] = 0; bFound = DXUtil_FindMediaSearchParentDirs( strDestPath, cchDest, TEXT("."), strLeafName ); if( bFound ) return S_OK; // Search all parent directories starting at the exe's dir and using strFilename as the leaf name bFound = DXUtil_FindMediaSearchParentDirs( strDestPath, cchDest, strExePath, strLeafName ); if( bFound ) return S_OK; // Search all parent directories starting at .\ and using "media\strFilename" as the leaf name _sntprintf( strLeafName, MAX_PATH, TEXT("media\\%s"), strFilename ); strLeafName[MAX_PATH-1] = 0; bFound = DXUtil_FindMediaSearchParentDirs( strDestPath, cchDest, TEXT("."), strLeafName ); if( bFound ) return S_OK; // Search all parent directories starting at the exe's dir and using "media\strFilename" as the leaf name bFound = DXUtil_FindMediaSearchParentDirs( strDestPath, cchDest, strExePath, strLeafName ); if( bFound ) return S_OK; // On failure, return the file as the path but also return an error code _tcsncpy( strDestPath, strFilename, cchDest ); strDestPath[cchDest-1] = 0; return E_FAIL; }
// Split a string usinf a particular delimiter, split result are copied into lpBuffer // in the "double null terminated string" format as the following figure shows: // xxx\0xxxx\0xx\0xxx\0\0 // // For example, if the delimiter is ",", then string "ab,cd,e" will be // splitted into "ab\0cd\0e\0\0", this string format can be parsed into an array // of sub strings easily using user defined functions or CIni::ParseStringArray. DWORD CIni::__StringSplit(LPCTSTR lpString, LPTSTR lpBuffer, DWORD dwBufSize, LPCTSTR lpDelimiter, BOOL bTrimString) { if (lpString == NULL || lpBuffer == NULL || dwBufSize == 0) return 0; DWORD dwCopied = 0; *lpBuffer = _T('\0'); if (*lpString == _T('\0')) return 0; // If lpDelimiter is NULL, use the default delimiter ",", if delimiter length // is 0, then return whole string if (lpDelimiter != NULL && *lpDelimiter == _T('\0')) { _tcsncpy(lpBuffer, lpString, dwBufSize - 1); return (DWORD)_tcslen(lpBuffer); } LPTSTR pszDel = (lpDelimiter == NULL) ? _tcsdup(DEF_PROFILE_DELIMITER) : _tcsdup(lpDelimiter); const DWORD DEL_LEN = (DWORD)_tcslen(pszDel); LPTSTR lpTarget = lpBuffer; // Search through lpString for delimiter matches, and extract sub strings out LPCTSTR lpPos = lpString; LPCTSTR lpEnd = _tcsstr(lpPos, pszDel); while (lpEnd != NULL) { LPTSTR pszSeg = __StrDupEx(lpPos, lpEnd); if (bTrimString) __TrimString(pszSeg); const DWORD SEG_LEN = (DWORD)_tcslen(pszSeg); const DWORD COPY_LEN = min(SEG_LEN, dwBufSize - dwCopied); // Need to avoid buffer overflow if (COPY_LEN > 0) { dwCopied += COPY_LEN + 1; _tcsncpy(lpTarget, pszSeg, COPY_LEN); lpTarget[COPY_LEN] = _T('\0'); lpTarget = &lpTarget[SEG_LEN + 1]; } delete [] pszSeg; lpPos = &lpEnd[DEL_LEN]; // Advance the pointer for next search lpEnd = _tcsstr(lpPos, pszDel); } // The last part of string, there may not be the trailing delimiter, so we // need to take care of this part, too LPTSTR pszSeg = _tcsdup(lpPos); if (bTrimString) __TrimString(pszSeg); const DWORD SEG_LEN = (DWORD)_tcslen(pszSeg); const DWORD COPY_LEN = min(SEG_LEN, dwBufSize - dwCopied); if (COPY_LEN > 0) { dwCopied += COPY_LEN + 1; _tcsncpy(lpTarget, pszSeg, COPY_LEN); lpTarget[COPY_LEN] = _T('\0'); } delete [] pszSeg; lpBuffer[dwCopied] = _T('\0'); delete [] pszDel; return dwCopied; }
BOOL OmapBus::AssignChildDriver() { DWORD NumSubKeys; DWORD MaxSubKeyLen; DWORD MaxClassLen; DWORD NumValues; DWORD MaxValueNameLen; DWORD MaxValueLen; // Get info on Template Key BOOL bSuccess = m_DeviceKey.RegQueryInfoKey( NULL, // class name buffer (lpszClass) NULL, // ptr to length of class name buffer (lpcchClass) NULL, // reserved &NumSubKeys, // ptr to number of sub-keys (lpcSubKeys) &MaxSubKeyLen, // ptr to longest subkey name length (lpcchMaxSubKeyLen) &MaxClassLen, // ptr to longest class string length (lpcchMaxClassLen) &NumValues, // ptr to number of value entries (lpcValues) &MaxValueNameLen, // ptr to longest value name length (lpcchMaxValueNameLen) &MaxValueLen, // ptr to longest value data length (lpcbMaxValueData) NULL, // ptr to security descriptor length NULL); // ptr to last write time if (!bSuccess) { RETAILMSG(1, (TEXT("PCMCIA::RegCopyKey RegQueryInfoKey returned fails.\r\n"))); return FALSE; } // Recurse for each sub-key for (DWORD Key = 0; Key < NumSubKeys; Key++) { // Get TKey sub-key according to Key WCHAR ValName[PCI_MAX_REG_NAME]; DWORD ValLen = sizeof(ValName) / sizeof(WCHAR); if (! m_DeviceKey.RegEnumKeyEx( Key, ValName, &ValLen, NULL, NULL, NULL, NULL)){ RETAILMSG(1, (TEXT("OmapBus::RegCopyKey RegEnumKeyEx(%d) returned Error\r\n"), ValName)); break; } else { // Open sub-key under TKey CRegistryEdit TSubKey(m_DeviceKey.GetHKey(),ValName); if (!TSubKey.IsKeyOpened()) { RETAILMSG(1, (TEXT("PCIBUS::RegCopyKey RegOpenKeyEx(%s) returned Error\r\n"), ValName)); continue; } else { // Get Bus Info. DDKPCIINFO dpi; dpi.cbSize = sizeof (DDKPCIINFO); dpi.dwDeviceNumber = (DWORD)-1; dpi.dwFunctionNumber = (DWORD)-1; if (TSubKey.GetPciInfo(&dpi)!=ERROR_SUCCESS || dpi.dwDeviceNumber == (DWORD)-1 || dpi.dwFunctionNumber == (DWORD)-1) { dpi.dwDeviceNumber = m_dwDeviceIndex++; dpi.dwFunctionNumber = 0; } DWORD dwBusNumber = (DWORD)-1; if ( !TSubKey.GetRegValue(PCIBUS_BUSNUMBER_VALNAME, (LPBYTE)&dwBusNumber, sizeof(dwBusNumber)) || dwBusNumber == (DWORD)-1) { dwBusNumber = m_dwBusNumber; } // We Create Foler for this driver. TCHAR lpChildPath[DEVKEY_LEN]; _tcsncpy(lpChildPath,m_lpActiveRegPath,DEVKEY_LEN-1); lpChildPath[DEVKEY_LEN-2] = 0; DWORD dwLen=_tcslen(lpChildPath); lpChildPath[dwLen]=_T('\\'); dwLen++; lpChildPath[dwLen]=0; _tcsncat(lpChildPath,ValName,DEVKEY_LEN-1-dwLen); lpChildPath[DEVKEY_LEN-1]=0; DeviceFolder * nDevice = new DeviceFolder (m_lpBusName!=NULL?m_lpBusName:BUSNAMEUNKNOWN, lpChildPath,m_dwBusType,dwBusNumber,dpi.dwDeviceNumber,dpi.dwFunctionNumber,GetDeviceHandle()); if (nDevice) { InsertChild(nDevice); } } } } return TRUE; }
LRESULT CALLBACK FrameWindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { MEASUREITEMSTRUCT *mis; DRAWITEMSTRUCT *dis; SIZE textSize; SIZE timeSize; switch(msg) { case WM_CREATE: hwnd_list = CreateWindow(_T("LISTBOX"), _T(""), (WS_VISIBLE | WS_CHILD | LBS_NOINTEGRALHEIGHT | LBS_STANDARD | LBS_NOTIFY | LBS_OWNERDRAWFIXED) & ~LBS_SORT & ~WS_BORDER, 0, 0, 0, 0, hwnd, NULL, hInst,0); return FALSE; case WMU_INITIALIZE: PostMessage(hwnd, WMU_FILL_LIST, 0, 0); SetTimer(hwnd, ID_FRAME_UPDATE_TIMER, 5000, 0); SetTimer(hwnd, ID_FRAME_SHOWHIDE_TIMER, 200, 0); return TRUE; case WM_MEASUREITEM: mis = (MEASUREITEMSTRUCT *)lParam; mis->itemHeight = options.row_height; return TRUE; case WM_DRAWITEM: dis = (DRAWITEMSTRUCT *)lParam; if (dis->itemID != (DWORD)-1) { ALARM alarm = {0}; mir_cslock lck(list_cs); ALARM &list_alarm = alarm_list.at(dis->itemData); copy_alarm_data(&alarm, &list_alarm); RECT r; GetClientRect(hwnd, &r); int min = MinutesInFuture(alarm.time, alarm.occurrence); FillRect(dis->hDC, &dis->rcItem, bk_brush); dis->rcItem.left += options.indent; SetBkMode(dis->hDC, TRANSPARENT); SetTextColor(dis->hDC, fontColour); HICON hIcon = (min <= 5 ? hIconList2 : hIconList1); DrawIconEx(dis->hDC,dis->rcItem.left,(dis->rcItem.top + dis->rcItem.bottom - 16)>>1,hIcon,0, 0, 0, NULL, DI_NORMAL); GetTextExtentPoint32(dis->hDC,alarm.szTitle,(int)mir_tstrlen(alarm.szTitle),&textSize); TCHAR buff[100]; if (min >= 60) mir_sntprintf(buff, TranslateT("%dh %dm"), min / 60, min % 60); else mir_sntprintf(buff, TranslateT("%dm"), min); GetTextExtentPoint32(dis->hDC,buff,(int)mir_tstrlen(buff),&timeSize); if (textSize.cx > (dis->rcItem.right - dis->rcItem.left) - (GetSystemMetrics(SM_CXSMICON) + 4) - timeSize.cx - 2 - 4) { // need elipsis TCHAR titlebuff[512]; size_t len = mir_tstrlen(alarm.szTitle); if (len > 511) len = 511; while(len > 0 && textSize.cx > (dis->rcItem.right - dis->rcItem.left) - (GetSystemMetrics(SM_CXSMICON) + 4) - timeSize.cx - 2 - 4) { len--; _tcsncpy(titlebuff, alarm.szTitle, len); titlebuff[len] = 0; mir_tstrcat(titlebuff, _T("...")); GetTextExtentPoint32(dis->hDC,titlebuff,(int)mir_tstrlen(titlebuff),&textSize); } TextOut(dis->hDC,dis->rcItem.left + 16 + 4,(dis->rcItem.top + dis->rcItem.bottom - textSize.cy)>>1,titlebuff,(int)mir_tstrlen(titlebuff)); TextOut(dis->hDC,dis->rcItem.right - timeSize.cx - 2,(dis->rcItem.top + dis->rcItem.bottom - timeSize.cy)>>1, buff,(int)mir_tstrlen(buff)); } else {
BOOL CTaskbarNotifier::LoadConfiguration(LPCTSTR szFileName) { TCHAR szConfigDir[MAX_PATH]; int nRed, nGreen, nBlue, sRed, sGreen, sBlue; int rcLeft, rcTop, rcRight, rcBottom; int bmpTrasparentRed, bmpTrasparentGreen, bmpTrasparentBlue; int fontSize; CString fontType, bmpFullPath, strBmpFileName; Hide(); m_strConfigFilePath = szFileName; CIni ini(szFileName, _T("CONFIG")); _tcsncpy(szConfigDir, szFileName, _countof(szConfigDir)); szConfigDir[_countof(szConfigDir)-1] = _T('\0'); LPTSTR pszFileName = _tcsrchr(szConfigDir, _T('\\')); if (pszFileName == NULL) return FALSE; *(pszFileName + 1) = _T('\0'); nRed = ini.GetInt(_T("TextNormalRed"),255); nGreen = ini.GetInt(_T("TextNormalGreen"),255); nBlue = ini.GetInt(_T("TextNormalBlue"),255); sRed = ini.GetInt(_T("TextSelectedRed"),255); sGreen = ini.GetInt(_T("TextSelectedGreen"),255); sBlue = ini.GetInt(_T("TextSelectedBlue"),255); bmpTrasparentRed = ini.GetInt(_T("bmpTrasparentRed"),255); bmpTrasparentGreen = ini.GetInt(_T("bmpTrasparentGreen"),0); bmpTrasparentBlue = ini.GetInt(_T("bmpTrasparentBlue"),255); fontType = ini.GetString(_T("FontType"), _T("MS Shell Dlg")); fontSize = ini.GetInt(_T("FontSize"), 8) * 10; m_dwTimeToStay = ini.GetInt(_T("TimeToStay"), 4000); m_dwTimeToShow = ini.GetInt(_T("TimeToShow"), 500); m_dwTimeToHide = ini.GetInt(_T("TimeToHide"), 200); strBmpFileName = ini.GetString(_T("bmpFileName"), _T("")); if (!strBmpFileName.IsEmpty()) { if (PathIsRelative(strBmpFileName)) bmpFullPath.Format(_T("%s%s"), szConfigDir, strBmpFileName); else bmpFullPath = strBmpFileName; } // get text rectangle coordinates rcLeft = ini.GetInt(_T("rcTextLeft"),5); rcTop = ini.GetInt(_T("rcTextTop"),45); rcRight = ini.GetInt(_T("rcTextRight"),220 ); rcBottom = ini.GetInt(_T("rcTextBottom"), 85); if (rcLeft<=0) rcLeft=1; if (rcTop<=0) rcTop=1; if (rcRight<=0) rcRight=1; if (rcBottom<=0) rcBottom=1; SetTextRect(CRect(rcLeft,rcTop,rcRight,rcBottom)); // get close button rectangle coordinates rcLeft = ini.GetInt(_T("rcCloseBtnLeft"),286); rcTop = ini.GetInt(_T("rcCloseBtnTop"),40); rcRight = ini.GetInt(_T("rcCloseBtnRight"), 300); rcBottom = ini.GetInt(_T("rcCloseBtnBottom"), 54); if (rcLeft<=0) rcLeft=1; if (rcTop<=0) rcTop=1; if (rcRight<=0) rcRight=1; if (rcBottom<=0) rcBottom=1; SetCloseBtnRect(CRect(rcLeft,rcTop,rcRight,rcBottom)); // get history button rectangle coordinates rcLeft = ini.GetInt(_T("rcHistoryBtnLeft"),283); rcTop = ini.GetInt(_T("rcHistoryBtnTop"),14); rcRight = ini.GetInt(_T("rcHistoryBtnRight"), 299); rcBottom = ini.GetInt(_T("rcHistoryBtnBottom"), 39); if (rcLeft<=0) rcLeft=1; if (rcTop<=0) rcTop=1; if (rcRight<=0) rcRight=1; if (rcBottom<=0) rcBottom=1; SetHistoryBtnRect(CRect(rcLeft,rcTop,rcRight,rcBottom)); if (bmpFullPath.IsEmpty() || !SetBitmap(bmpFullPath, bmpTrasparentRed, bmpTrasparentGreen, bmpTrasparentBlue)) { CEnBitmap imgTaskbar; if (imgTaskbar.LoadImage(IDR_TASKBAR, _T("GIF"))) { if (!SetBitmap(&imgTaskbar, bmpTrasparentRed, bmpTrasparentGreen, bmpTrasparentBlue)) return FALSE; } } SetTextFont(fontType, fontSize, TN_TEXT_NORMAL,TN_TEXT_UNDERLINE); SetTextColor(RGB(nRed, nGreen, nBlue), RGB(sRed, sGreen, sBlue)); return TRUE; }
BOOL CSystemTray::Create(CWnd* pParent, UINT uCallbackMessage, LPCTSTR szToolTip, HICON icon, UINT uID, BOOL bHidden /*=FALSE*/, LPCTSTR szBalloonTip /*=NULL*/, LPCTSTR szBalloonTitle /*=NULL*/, DWORD dwBalloonIcon /*=NIIF_NONE*/, UINT uBalloonTimeout /*=10*/, BOOL bShowToolTip) { #ifdef _WIN32_WCE m_bEnabled = TRUE; #else // this is only for Windows 95 (or higher) m_bEnabled = (GetVersion() & 0xff) >= 4; if (!m_bEnabled) { ASSERT(FALSE); return FALSE; } #endif m_nMaxTooltipLength = _countof(m_tnd.szTip); // Make sure we avoid conflict with other messages ASSERT(uCallbackMessage >= WM_APP); // Tray only supports tooltip text up to m_nMaxTooltipLength) characters ASSERT(AfxIsValidString(szToolTip)); ASSERT(_tcslen(szToolTip) <= m_nMaxTooltipLength); // Create an invisible window CWnd::CreateEx(0, AfxRegisterWndClass(0), _T(""), WS_POPUP, 0,0,0,0, NULL, 0); // load up the NOTIFYICONDATA structure m_tnd.cbSize = sizeof(NOTIFYICONDATA); m_tnd.hWnd = pParent->GetSafeHwnd()? pParent->GetSafeHwnd() : m_hWnd; m_tnd.uID = uID; m_tnd.hIcon = icon; OSVERSIONINFO versionInfo; versionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&versionInfo); if (versionInfo.dwMajorVersion >= 6) m_tnd.uFlags = NIF_MESSAGE | NIF_ICON | (bShowToolTip ? NIF_TIP : 0); else m_tnd.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP; m_tnd.uCallbackMessage = uCallbackMessage; _tcsncpy(m_tnd.szTip, szToolTip, m_nMaxTooltipLength-1); #ifdef SYSTEMTRAY_USEW2K if (m_bWin2K && szBalloonTip) { // The balloon tooltip text can be up to 255 chars long. ASSERT(AfxIsValidString(szBalloonTip)); ASSERT(lstrlen(szBalloonTip) < 256); // The balloon title text can be up to 63 chars long. if (szBalloonTitle) { ASSERT(AfxIsValidString(szBalloonTitle)); ASSERT(lstrlen(szBalloonTitle) < 64); } // dwBalloonIcon must be valid. ASSERT(NIIF_NONE == dwBalloonIcon || NIIF_INFO == dwBalloonIcon || NIIF_WARNING == dwBalloonIcon || NIIF_ERROR == dwBalloonIcon); // The timeout must be between 10 and 30 seconds. ASSERT(uBalloonTimeout >= 1 && uBalloonTimeout <= 30); m_tnd.uFlags |= NIF_INFO; _tcsncpy(m_tnd.szInfo, szBalloonTip, 255); if (szBalloonTitle) _tcsncpy(m_tnd.szInfoTitle, szBalloonTitle, 63); else m_tnd.szInfoTitle[0] = _T('\0'); m_tnd.uTimeout = uBalloonTimeout * 1000; // convert time to ms m_tnd.dwInfoFlags = dwBalloonIcon; } #endif m_bHidden = bHidden; #ifdef SYSTEMTRAY_USEW2K if (m_bWin2K && m_bHidden) { m_tnd.uFlags = NIF_STATE; m_tnd.dwState = NIS_HIDDEN; m_tnd.dwStateMask = NIS_HIDDEN; } #endif m_uCreationFlags = m_tnd.uFlags; // Store in case we need to recreate in OnTaskBarCreate BOOL bResult = TRUE; if (!m_bHidden || m_bWin2K) { bResult = Shell_NotifyIcon(NIM_ADD, &m_tnd); m_bShowIconPending = m_bHidden = m_bRemoved = !bResult; } #ifdef SYSTEMTRAY_USEW2K if (m_bWin2K && szBalloonTip) { // Zero out the balloon text string so that later operations won't redisplay // the balloon. m_tnd.szInfo[0] = _T('\0'); } #endif return bResult; }
static char * getpythonregpath(HKEY keyBase, int skipcore) { HKEY newKey = 0; DWORD dataSize = 0; DWORD numKeys = 0; LONG rc; char *retval = NULL; TCHAR *dataBuf = NULL; static const TCHAR keyPrefix[] = _T("Software\\Python\\PythonCore\\"); static const TCHAR keySuffix[] = _T("\\PythonPath"); size_t versionLen; DWORD index; TCHAR *keyBuf = NULL; TCHAR *keyBufPtr; TCHAR **ppPaths = NULL; /* Tried to use sysget("winver") but here is too early :-( */ versionLen = _tcslen(PyWin_DLLVersionString); /* Space for all the chars, plus one \0 */ keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) + sizeof(TCHAR)*(versionLen-1) + sizeof(keySuffix)); if (keyBuf==NULL) goto done; memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(TCHAR)); keyBufPtr += sizeof(keyPrefix)/sizeof(TCHAR) - 1; memcpy(keyBufPtr, PyWin_DLLVersionString, versionLen * sizeof(TCHAR)); keyBufPtr += versionLen; /* NULL comes with this one! */ memcpy(keyBufPtr, keySuffix, sizeof(keySuffix)); /* Open the root Python key */ rc=RegOpenKeyEx(keyBase, keyBuf, /* subkey */ 0, /* reserved */ KEY_READ, &newKey); if (rc!=ERROR_SUCCESS) goto done; /* Find out how big our core buffer is, and how many subkeys we have */ rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL, NULL, NULL, &dataSize, NULL, NULL); if (rc!=ERROR_SUCCESS) goto done; if (skipcore) dataSize = 0; /* Only count core ones if we want them! */ /* Allocate a temp array of char buffers, so we only need to loop reading the registry once */ ppPaths = malloc( sizeof(TCHAR *) * numKeys ); if (ppPaths==NULL) goto done; memset(ppPaths, 0, sizeof(TCHAR *) * numKeys); /* Loop over all subkeys, allocating a temp sub-buffer. */ for(index=0;index<numKeys;index++) { TCHAR keyBuf[MAX_PATH+1]; HKEY subKey = 0; DWORD reqdSize = MAX_PATH+1; /* Get the sub-key name */ DWORD rc = RegEnumKeyEx(newKey, index, keyBuf, &reqdSize, NULL, NULL, NULL, NULL ); if (rc!=ERROR_SUCCESS) goto done; /* Open the sub-key */ rc=RegOpenKeyEx(newKey, keyBuf, /* subkey */ 0, /* reserved */ KEY_READ, &subKey); if (rc!=ERROR_SUCCESS) goto done; /* Find the value of the buffer size, malloc, then read it */ RegQueryValueEx(subKey, NULL, 0, NULL, NULL, &reqdSize); if (reqdSize) { ppPaths[index] = malloc(reqdSize); if (ppPaths[index]) { RegQueryValueEx(subKey, NULL, 0, NULL, (LPBYTE)ppPaths[index], &reqdSize); dataSize += reqdSize + 1; /* 1 for the ";" */ } } RegCloseKey(subKey); } /* return null if no path to return */ if (dataSize == 0) goto done; /* original datasize from RegQueryInfo doesn't include the \0 */ dataBuf = malloc((dataSize+1) * sizeof(TCHAR)); if (dataBuf) { TCHAR *szCur = dataBuf; DWORD reqdSize = dataSize; /* Copy our collected strings */ for (index=0;index<numKeys;index++) { if (index > 0) { *(szCur++) = _T(';'); dataSize--; } if (ppPaths[index]) { Py_ssize_t len = _tcslen(ppPaths[index]); _tcsncpy(szCur, ppPaths[index], len); szCur += len; assert(dataSize > (DWORD)len); dataSize -= (DWORD)len; } } if (skipcore) *szCur = '\0'; else { /* If we have no values, we dont need a ';' */ if (numKeys) { *(szCur++) = _T(';'); dataSize--; } /* Now append the core path entries - this will include the NULL */ rc = RegQueryValueEx(newKey, NULL, 0, NULL, (LPBYTE)szCur, &dataSize); } /* And set the result - caller must free If MBCS, it is fine as is. If Unicode, allocate new buffer and convert. */ #ifdef UNICODE retval = (char *)malloc(reqdSize+1); if (retval) WideCharToMultiByte(CP_ACP, 0, dataBuf, -1, /* source */ retval, reqdSize+1, /* dest */ NULL, NULL); free(dataBuf); #else retval = dataBuf; #endif } done: /* Loop freeing my temp buffers */ if (ppPaths) { for(index=0;index<numKeys;index++) if (ppPaths[index]) free(ppPaths[index]); free(ppPaths); } if (newKey) RegCloseKey(newKey); if (keyBuf) free(keyBuf); return retval; }
/////////////////////////////////////////////////////////////////////////////// // // 函数功能描述:标准日志打印 // 输入:日志级别、类型、源文件名、代码行,格式字串 // 输出:向窗口或文件写日志 // 返回值: // 其它说明: // /////////////////////////////////////////////////////////////////////////////// void CLogTrace::Trace(BYTE cLevel, BYTE cType, const TCHAR * pszSourceFile, DWORD dwLine, LPCTSTR lpszFormat, ...) { if (! IsLogFileEnable()) return; //指定类型级别以下的日志不打印; if ( m_nOutLogLevel < cType ) { return; } //合法性检测 if (!pszSourceFile || !lpszFormat) { OutputDebugString(_T("Error: pszSourceFile or lpszFormat is NULL\r\n")); return; } //读取参数 va_list args; va_start(args, lpszFormat); CLocalLock localLock(&m_lock); //锁 //打入字串 m_szBuffer[0][0] = 0; int nBuf = -1; if(cType == LOGT_COMPRESS) //对打印的日志进行压缩 { TCHAR *tmp = new TCHAR[200000]; memset(tmp,0,200000 * sizeof(TCHAR)); int nBuf = _vsntprintf(tmp,200000-1,lpszFormat,args); CString strSource,strZipData; strSource.Format(_T("%s"),tmp); if (strSource.GetLength() < 100) { strZipData = strSource; } else { ZipEecodeStdString(strSource,strZipData); } _tcsncpy(m_szBuffer[0],strZipData.GetBuffer(strZipData.GetLength()),MAX_LEN_OF_LOG_LINE-128); strZipData.ReleaseBuffer(); delete []tmp; } else { nBuf = _vsntprintf(m_szBuffer[0], MAX_LEN_OF_LOG_LINE - 128, lpszFormat, args); } va_end(args); if (nBuf < 0) //出错 { //有可能是字符串太长 m_szBuffer[0][MAX_LEN_OF_LOG_LINE - 128] = 0; } //取系统日期、时间 TCHAR szData[12], szTime[12]; _tstrdate(szData); _tstrtime(szTime); //类型字串及颜色 CString strType; DWORD dwColor = 0; //获取日志的类型文本及颜色 GetLogType(strType,dwColor,cType); //源文件名缩短处理 TCHAR * pszSourceShort = NULL; TCHAR szSourceShort[MAX_PATH]; WORD wSourceNameLen = lstrlen(pszSourceFile); if (wSourceNameLen > LEN_SHORT_SOURCEFILE_NAME) //太长 { wsprintf(szSourceShort, _T("...%s"), pszSourceFile + (wSourceNameLen - LEN_SHORT_SOURCEFILE_NAME)); pszSourceShort = szSourceShort; } else { pszSourceShort = (TCHAR *)pszSourceFile; } //形成结果字串 nBuf = _sntprintf(m_szBuffer[1], MAX_LEN_OF_LOG_LINE, _T("%s %s [%d]%s: %s at %d in %s\r\n"), szData, szTime, GetCurrentThreadId(), strType.GetBuffer(), m_szBuffer[0], dwLine, pszSourceShort); if (nBuf < 0) //出错 { //有可能是字符串太长 m_szBuffer[1][MAX_LEN_OF_LOG_LINE - 1] = 0; } strType.ReleaseBuffer(); //打印 TraceColor(cLevel, dwColor); }