int CALLBACK CKLPopupDlgProc(HWND hWnd, UINT uiMessage, WPARAM wParam, LPARAM lParam) { LPTSTR ptszPopupText = (LPTSTR)CallService(MS_POPUP_GETPLUGINDATA, (WPARAM)hWnd, (LPARAM)&ptszPopupText); switch (uiMessage) { case WM_COMMAND: if (HIWORD(wParam) == STN_CLICKED) { if (!IsBadStringPtr(ptszPopupText, MaxTextSize)) CopyTextToClipboard(ptszPopupText); PUDeletePopup(hWnd); } break; case WM_CONTEXTMENU: PUDeletePopup(hWnd); break; case UM_POPUPACTION: if ((lParam == 0) && (!IsBadStringPtr(ptszPopupText, MaxTextSize))) CopyTextToClipboard(ptszPopupText); break; case UM_FREEPLUGINDATA: mir_free(ptszPopupText); return TRUE; } return DefWindowProc(hWnd, uiMessage, wParam, lParam); }
// Copies the text to the clipboard. BOOL CopyTextToClipboard ( LPCTSTR szMem , HWND hWndOwner ) { ASSERT ( FALSE == IsBadStringPtr ( szMem , MAX_PATH ) ) ; if ( TRUE == IsBadStringPtr ( szMem , MAX_PATH ) ) { return ( FALSE ) ; } BOOL bRet = TRUE ; BOOL bOpenedCB = FALSE ; if ( TRUE == ::OpenClipboard ( hWndOwner ) ) { bOpenedCB = TRUE ; if ( TRUE == ::EmptyClipboard ( ) ) { // Do the goofy memory stuff. HGLOBAL hGlob = ::GlobalAlloc ( GMEM_MOVEABLE , (_tcslen ( szMem ) + 1) * sizeof ( TCHAR ) ); if ( NULL != hGlob ) { TCHAR * szClipMem = (TCHAR*)GlobalLock ( hGlob ) ; ASSERT ( NULL != szMem ) ; _tcscpy ( szClipMem , szMem ) ; GlobalUnlock ( hGlob ) ; if ( NULL == ::SetClipboardData ( CLIPBOARDFMT , hGlob ) ) { ASSERT ( !"SetClipboardData failed!!" ) ; } } else { ASSERT ( !"Unable to GlobalAlloc memory!!" ) ; bRet = FALSE ; } } else { ASSERT ( !"Unable to empty the clipboard!!" ) ; bRet = FALSE ; } } else { ASSERT ( !"Unable to open the clipboard!!" ) ; bRet = FALSE ; } if ( TRUE == bOpenedCB ) { CloseClipboard ( ) ; } return ( bRet ) ; }
HRESULT CCompositorStatistics::SetDocumentDescriptions( LPCTSTR szDoc1, LPCTSTR szDoc2) { if (szDoc1 == NULL || szDoc2 == NULL) return E_INVALIDARG; if (IsBadStringPtr(szDoc1, 0x8000) || IsBadStringPtr(szDoc1, 0x8000)) return E_INVALIDARG; m_csDoc1Description = szDoc1; m_csDoc2Description = szDoc2; return S_OK; }
BOOL Win32Error(DWORD err, LPSTR str1) { LPVOID temp; LPVOID local; if(FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &temp, 0, NULL)) { if(IsBadStringPtr(str1,sizeof(str1)+1)) return(-1); local = (char *)malloc(strlen(str1)+strlen(temp)+1); if(!local) return(-1); strcpy(local,str1); strcat(local,temp); MessageBox(NULL,local,"UWIN Setuid Service",0x00200000L| 0x00040000L |MB_OK|MB_ICONSTOP); LocalFree(temp); free(local); return(1); } else return(-1); }
BOOL minidump_createcrashdump(LPCTSTR lpFileName, EXCEPTION_POINTERS * pExPtrs) { BOOL bRet = FALSE; if (IsBadStringPtr(lpFileName,MAX_PATH)) return bRet; // Create the file HANDLE hMiniDumpFile = CreateFile( lpFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hMiniDumpFile != INVALID_HANDLE_VALUE) { // Write minidump to the file. // If the function succeeds, the return value is TRUE; // otherwise, the return value is FALSE bRet = minidump_dumpminidump(hMiniDumpFile, pExPtrs); // Close file CloseHandle(hMiniDumpFile); } return bRet; }
///////////////////////////////////////////////////////////////////////////// // GetStringCopyAmount // // delete after use. ///////////////////////////////////////////////////////////////////////////// TCHAR* GetStringCopyAmount( LPCTSTR SourceString, size_t Amount) { TCHAR* StringCopy = NULL; if (NULL != SourceString) { BOOL BadString = IsBadStringPtr(SourceString,(UINT_PTR)-1); if (FALSE == BadString) { size_t SourceStringLength = (_tcslen(SourceString) + 1) * sizeof(TCHAR); StringCopy = new TCHAR[Amount+1]; if (NULL != StringCopy) { _tcsncpy_s( StringCopy, Amount+1, SourceString, Amount); } } } return StringCopy; }
TCHAR* StringSprintfInt( TCHAR* OriginalString, int Number) { TCHAR* StringCopy = NULL; if (NULL != OriginalString) { BOOL BadString = IsBadStringPtr(OriginalString,(UINT_PTR)-1); if (FALSE == BadString) { size_t SourceStringLength = (_tcslen(OriginalString) + 1) * sizeof(TCHAR) + 16; StringCopy = new TCHAR[SourceStringLength]; if (NULL != StringCopy) { _stprintf_s(StringCopy, SourceStringLength, OriginalString, Number); } } } return StringCopy; }
LRESULT AwtMenuItem::WinThreadExecProc(ExecuteArgs * args) { switch( args->cmdId ) { case MENUITEM_SETLABEL: { LPCTSTR sb = (LPCTSTR)args->param1; DASSERT(!IsBadStringPtr(sb, 20)); this->SetLabel(sb); } break; case MENUITEM_ENABLE: { BOOL isEnabled = (BOOL)args->param1; this->Enable(isEnabled); } break; case MENUITEM_SETSTATE: { BOOL isChecked = (BOOL)args->param1; this->SetState(isChecked); } break; default: AwtObject::WinThreadExecProc(args); break; } return 0L; }
static BOOL pConvertStringToDeviceId( LPCTSTR szAddressString, NDAS_DEVICE_ID* pDeviceId) { _ASSERTE(!IsBadStringPtr(szAddressString,-1)); _ASSERTE(!IsBadWritePtr(pDeviceId, sizeof(NDAS_DEVICE_ID))); static CONST size_t CCH_ADDR = 17; size_t cch = 0; HRESULT hr = StringCchLength(szAddressString, STRSAFE_MAX_CCH, &cch); if (FAILED(hr) || cch != CCH_ADDR) { return FALSE; } for (DWORD i = 0; i < 6; ++i) { CONST TCHAR* psz = szAddressString + i * 3; DWORD v1 = 0, v2 = 0; BOOL fSuccess = pCharToHex(psz[0], &v1) && pCharToHex(psz[1], &v2); if (!fSuccess) { return FALSE; } pDeviceId->Node[i] = v1 * 0x10 + v2; } return TRUE; }
void AssertValidStringPtr(const char *ptr, int maxchar) { #ifdef _WIN32 Assert(!IsBadStringPtr(ptr, maxchar)); #else Assert(ptr); #endif }
HRESULT CCompositorStatistics::SetRenderingSet (LPCTSTR szRenderingSet) { if (IsBadStringPtr(szRenderingSet, 0x8000)) return E_INVALIDARG; m_csRenderingSet = szRenderingSet; return S_OK; }
bool tUtil::IsValidString(LPCTSTR string) { bool return_value = string != NULL && !IsBadStringPtr(string, MAX_VALID_STRING_SIZE); assert(return_value); return return_value; }
DBG_INTERFACE void AssertValidStringPtr( const tchar* ptr, int maxchar/* = 0xFFFFFF */ ) { #if defined( _WIN32 ) && !defined( _X360 ) #ifdef TCHAR_IS_CHAR Assert( !IsBadStringPtr( ptr, maxchar ) ); #else Assert( !IsBadStringPtrW( ptr, maxchar ) ); #endif #else Assert( ptr ); #endif }
HRESULT CCompositorStatistics::SetProgramName (LPCTSTR szProgramName) { if (szProgramName == NULL) return E_INVALIDARG; if (IsBadStringPtr(szProgramName, 0x8000)) return E_INVALIDARG; m_csProgramName = szProgramName; return S_OK; }
unsigned CPerfTitleDatabase::GetIndexFromTitleString( PCTSTR pszTitleString ) { if ( IsBadStringPtr(pszTitleString, 0xFFFFFFFF) ) return 0; // Loop through all the non-null string array entries, doing a case- // insensitive comparison. If found, return the correpsonding index for ( unsigned i = 1; i <= m_nLastIndex; i++ ) { if ( m_TitleStrings[i] ) if ( 0 == _tcsicmp( pszTitleString, m_TitleStrings[i] ) ) return i; } return 0; }
void Font::Print(GLdouble X, GLdouble Y, const char *fmt, ...) { static char text[512]; // Место для нашей строки //memset(text,0,256); va_list ap; // Указатель на список аргументов if (fmt == NULL || IsBadStringPtr(fmt,200)) // Если нет текста return; // Ничего не делать va_start(ap, fmt); // Разбор строки переменных vsprintf(text, fmt, ap); // И конвертирование символов в реальные коды va_end(ap); // Результат помещается в строку glPushAttrib(GL_LIST_BIT|GL_DEPTH_BUFFER_BIT|GL_ENABLE_BIT|GL_CURRENT_BIT); // Сохранение настроек glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); T->bind(); glDisable(GL_DEPTH_TEST); // Disables Depth Testing glEnable(GL_TEXTURE_2D); glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glPushMatrix(); // Store The Projection Matrix glLoadIdentity(); // Reset The Projection Matrix glOrtho(0,Font::scr_width,480,0,-1,1); // Set Up An Ortho Screen glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glPushMatrix(); // Store The Modelview Matrix glLoadIdentity(); // Reset The Modelview Matrix glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(Color.d.c.x,Color.d.c.y,Color.d.c.z,alfa);// Установка цвета шрифта glTranslated(X*Font::scr_width,Y*480.0,0); // Position The Text (0,0 - Bottom Left) switch(this->ha) { case Text::center: { size_t strl = strlen (text); GLdouble shift = 0.0; for (size_t i = 0 ; i < strl ; i++ ) { shift += lfg [(unsigned char)text[i]].A + lfg [(unsigned char)text[i]].B; } glTranslated(-shift/2 * ( float ) Size * 30 / Globals.VP.ScreenStrings ,0.0,0.0); } break; case Text::right: { size_t strl = strlen (text); GLdouble shift = 0.0; for (size_t i = 0 ; i < strl ; i++ ) { shift += lfg [(unsigned char)text[i]].A + lfg [(unsigned char)text[i]].B; } glTranslated(-shift * ( float ) Size * 30 / Globals.VP.ScreenStrings,0.0,0.0); } break; } glScaled(Size*30/Globals.VP.ScreenStrings,Size*30/Globals.VP.ScreenStrings,1.0); glListBase(this->Base); // Choose The Font Base glCallLists((GLsizei)strlen(text),GL_UNSIGNED_BYTE,text); // Write The Text To The Screen glMatrixMode(GL_PROJECTION); // Select The Projection Matrix glPopMatrix(); // Restore The Old Projection Matrix glMatrixMode(GL_MODELVIEW); // Select The Modelview Matrix glPopMatrix(); // Restore The Old Projection Matrix glEnable(GL_DEPTH_TEST); // Enables Depth Testing glPopAttrib(); // Возврат }
BOOL ResizeDlg::SetData(const DialogSizerSizingItem *psd, BOOL bShowSizingGrip, HKEY hkRootSave, LPCTSTR pcszName, SIZE *psizeMax) // // Setting a dialog sizeable involves subclassing the window and handling it's // WM_SIZE messages, if we have a hkRootSave and pcszName then we will also be loading/saving // the size and position of the window from the registry. We load from the registry when we // subclass the window and we save to the registry when we get a WM_DESTROY. // // It will return non-zero for success and zero if it fails { R_ASSERT( psd ); R_ASSERT( ( hkRootSave != NULL && pcszName != NULL ) || ( hkRootSave == NULL && pcszName == NULL ) ); // // Make sure all of the parameters are valid. if( ::IsWindow( *this ) && psd && ( ( hkRootSave != NULL && pcszName != NULL && !IsBadStringPtr( pcszName, 0xFFFF ) ) || ( hkRootSave == NULL && pcszName == NULL ) ) && ( psizeMax == NULL || !IsBadReadPtr( psizeMax, sizeof( SIZE ) ) ) ) { DialogData *pdd = (DialogData *)AddDialogData(); if( pdd ) { pdd->hkRootSave = hkRootSave; pdd->pcszName = pcszName; pdd->m_bShowSizingGrip = bShowSizingGrip; pdd->nItemCount = ResizeDlgGetItemCount( psd ) + 1; pdd->psd = (DialogSizerSizingItem *) calloc(pdd->nItemCount, sizeof(DialogSizerSizingItem )); if( pdd->psd ) { // // Copy all of the user controls etc. for later, this way the user can quite happily // let the structure go out of scope. ResizeDlgCopyItems( pdd->psd, psd ); if( psizeMax ) { pdd->m_ptLargest.x = psizeMax->cx; pdd->m_ptLargest.y = psizeMax->cy; pdd->m_bLargestSet = true; } // // If the there was save info passed in then we need to make damn good use of it // by attempting to load the RegistryData structure if( hkRootSave && pcszName ) { RegistryData rd; DWORD dwSize = sizeof( RegistryData ); DWORD dwType = REG_BINARY; if( RegQueryValueExRecursive( hkRootSave, pcszName, NULL, &dwType, reinterpret_cast<LPBYTE>( &rd ), &dwSize ) == ERROR_SUCCESS && dwSize == sizeof( rd ) ) { if( !(GetWindowLong( *this, GWL_STYLE ) & WS_VISIBLE) ) rd.m_wpl.showCmd = SW_HIDE; VAPI( SetWindowPlacement( &rd.m_wpl ) ); } } return TRUE; } else { free(pdd); } } } return FALSE; }
BOOL WINAPI NdasDmGetNdasLogDevSlotNoOfScsiPort( LPCWSTR wszDbccName, LPDWORD lpdwSlotNo) { _ASSERTE(!IsBadWritePtr(lpdwSlotNo, sizeof(DWORD))); _ASSERTE(!IsBadStringPtr(wszDbccName, _MAX_PATH)); DPInfo(_FT("NdasDmGetNdasLogDevSlotNoOfScsiPort got %s.\n"), wszDbccName); // // extract the last string between '&' and '#', which has slot number and unitdisk numer // // example of dbcc_name at logical device slot no 10 // // \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b} // ^^^^ if (!NdasDmIsLANSCSIPortInterface(wszDbccName)) { DPInfo(_FT("Non-LANSCSI Port Interface Name.\n")); return FALSE; } // skip LANSCSIIDDEV_IFDW LPCWSTR pwszLeftBound = &wszDbccName[LANSCSI_DEV_IFIDW_LEN]; // pwszLeftBound now points to // \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b} // ^ // left bound while (*pwszLeftBound != L'#') { if (*pwszLeftBound == L'\0') { DPError(_FT("Slot Number Parse Error at left bound!\n")); return FALSE; // invalid! } ++pwszLeftBound; } // pwszpwszLeftBound now points to // \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b} // ^ // left bound LPCWSTR pwszRightBound = pwszLeftBound + 1; while (*pwszRightBound != L'#') { if (*pwszRightBound == L'\0') { DPError(_FT("Slot Number Parse Error at right bound!\n")); return FALSE; // invalid! } ++pwszRightBound; } // pwszRightBound now points to // \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b} // ^ ^ // left bound right bound LPCWSTR pwszSlotStart = pwszRightBound - 1; while (*pwszSlotStart != L'&') { if (pwszSlotStart <= pwszLeftBound) { DPError(_FT("Slot Number Parse Error at slot start bound!\n")); return FALSE; } --pwszSlotStart; } // pwszRightBound now points to // \\?\lanscsibus#netdisk_v0#1&1a590e2c&5&10#{2accfe60-c130-11d2-b082-00a0c91efb8b} // ^ ^ ^ // left bound | right bound // slot start if (pwszSlotStart + 1 == pwszRightBound) { // &# -> no slot number DPError(_FT("Slot Number Parse Error at slot start bound!\n")); return FALSE; } WCHAR szSlotNo[10]; LPCWSTR pch = pwszSlotStart + 1; DWORD i(0); for (; pch < pwszRightBound && i < 9; ++i, ++pch) { szSlotNo[i] = *pch; } szSlotNo[i] = L'\0'; DWORD dwSlotNo = _wtoi(szSlotNo); if (dwSlotNo == 0) { DPError(_FT("Invalid slot number (%s) -> (%d)\n"), szSlotNo, dwSlotNo); return FALSE; } *lpdwSlotNo = dwSlotNo; DPInfo(_FT("Slot no is %d.\n"), dwSlotNo); return TRUE; }
NDASDI_API BOOL WINAPI NdasDiRemoveLegacyDevice( IN HWND hwndParent, IN LPCTSTR ServiceName, IN BOOL PresentOnly, OUT LPDWORD pdwRemovedDeviceCount OPTIONAL, OUT LPBOOL pbRebootRequired OPTIONAL, IN NDASDIREMOVEDEVICEERRCALLBACKPROC ErrorCallbackProc OPTIONAL, IN LPVOID Context OPTIONAL) { _ASSERTE(!IsBadStringPtr(ServiceName, LINE_LEN)); _ASSERTE(NULL == pbRebootRequired || !IsBadWritePtr(pbRebootRequired, sizeof(BOOL))); _ASSERTE(NULL == ErrorCallbackProc || !IsBadCodePtr((FARPROC)ErrorCallbackProc)); BOOL fReturn = FALSE; BOOL fSuccess = FALSE; HDEVINFO DeviceInfoSet = INVALID_HANDLE_VALUE; SP_DEVINFO_DATA DeviceInfoData = {0}; DWORD Flags = DIGCF_ALLCLASSES; if (PresentOnly) { Flags |= DIGCF_PRESENT; } // // Create a Device Information Set with all present devices. // DeviceInfoSet = SetupDiGetClassDevs( NULL, // All Classes 0, hwndParent, Flags); // All devices present on system if (INVALID_HANDLE_VALUE == DeviceInfoSet) { goto cleanup; } if (NULL != pbRebootRequired) { *pbRebootRequired = FALSE; } // // Enumerate through all Devices. // DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA); if (NULL != pdwRemovedDeviceCount) { *pdwRemovedDeviceCount = 0; } for (DWORD i = 0; SetupDiEnumDeviceInfo(DeviceInfoSet,i,&DeviceInfoData); ++i) { DWORD DataT; LPTSTR buffer = NULL; DWORD buffersize = 0; // // We won't know the size of the HardwareID buffer until we call // this function. So call it with a null to begin with, and then // use the required buffer size to Alloc the nessicary space. // Keep calling we have success or an unknown failure. // while (TRUE) { fSuccess = SetupDiGetDeviceRegistryProperty( DeviceInfoSet, &DeviceInfoData, SPDRP_SERVICE, &DataT, (PBYTE)buffer, buffersize, &buffersize); if (fSuccess) { break; } if (ERROR_INVALID_DATA == GetLastError()) { // // May be a Legacy Device with no HardwareID. Continue. // break; } else if (ERROR_INSUFFICIENT_BUFFER == GetLastError()) { // // We need to change the buffer size. // if (buffer) { LocalFree(buffer); } buffer = (LPTSTR) LocalAlloc(LPTR,buffersize); } else { // // Unknown Failure. // if (ErrorCallbackProc) { BOOL fCont = ErrorCallbackProc( NDIRD_ERROR_GetDeviceRegistryProperty, DeviceInfoSet, &DeviceInfoData, GetLastError(), Context); if (fCont) { } fReturn = FALSE; goto cleanup; } } } // // May be a Legacy Device with no HardwareID. Continue. // if (GetLastError() == ERROR_INVALID_DATA) { continue; } // // Service Name is REG_SZ (Not MultiSZ) // LPCTSTR p = buffer; DPNoise(_T("%s\n"), p); if (0 == lstrcmpi(ServiceName,p)) { DPNoise(_T("\n>>> %s <<<\n"), p); // // Worker function to remove device. // fSuccess = SetupDiCallClassInstaller( DIF_REMOVE, DeviceInfoSet, &DeviceInfoData); if (!fSuccess && ErrorCallbackProc) { BOOL fCont = ErrorCallbackProc( NDIRD_ERROR_CallRemoveToClassInstaller, DeviceInfoSet, &DeviceInfoData, GetLastError(), Context); if (buffer) { LocalFree(buffer); } fReturn = FALSE; goto cleanup; } // // Get the installation param // if (NULL != pbRebootRequired) { SP_DEVINSTALL_PARAMS diParams = {0}; diParams.cbSize = sizeof(SP_DEVINSTALL_PARAMS); fSuccess = SetupDiGetDeviceInstallParams( DeviceInfoSet, &DeviceInfoData, &diParams); _ASSERTE(fSuccess); *pbRebootRequired |= (diParams.Flags & DI_NEEDREBOOT) || (diParams.Flags & DI_NEEDRESTART); } if (NULL != pdwRemovedDeviceCount) { ++(*pdwRemovedDeviceCount); } break; } if (buffer) { LocalFree(buffer); } } if ((NO_ERROR != GetLastError()) && (ERROR_NO_MORE_ITEMS != GetLastError())) { fReturn = FALSE; } else { fReturn = TRUE; } // // Cleanup. // cleanup: DWORD err = GetLastError(); if (INVALID_HANDLE_VALUE != DeviceInfoSet) { SetupDiDestroyDeviceInfoList(DeviceInfoSet); } SetLastError(err); return fReturn; }
static MAP_OPEN_ERROR MapFileOpen(IN LPCSTR lpszFileName, OUT LPSTR &lpMapAddr, OUT DWORD &dwSize) { // Set default values for output parameters lpMapAddr = NULL; dwSize = INVALID_FILE_SIZE; // Validate all input pointer parameters _ASSERTE(NULL != lpszFileName); _ASSERTE(FALSE == IsBadStringPtr(lpszFileName, (UINT_PTR) -1)); if ((NULL == lpszFileName) || IsBadStringPtr(lpszFileName, (UINT_PTR) -1)) { SetLastError(ERROR_INVALID_PARAMETER); return WIN32_ERROR; } // Open the file HANDLE hFile = CreateFile(lpszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE == hFile) { return WIN32_ERROR; } dwSize = GetFileSize(hFile, NULL); if ((INVALID_FILE_SIZE == dwSize) || (0 == dwSize)) { // File too large or empty WIN32CHECK(CloseHandle(hFile)); return ((0 == dwSize) ? FILE_EMPTY_ERROR : WIN32_ERROR); } HANDLE hMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if (NULL == hMap) { WIN32CHECK(CloseHandle(hFile)); return WIN32_ERROR; } // Mapping creation successful, do not need file handle anymore WIN32CHECK(CloseHandle(hFile)); lpMapAddr = (LPSTR) MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, dwSize); if (NULL == lpMapAddr) { WIN32CHECK(CloseHandle(hMap)); return WIN32_ERROR; } // Map View successful, do not need the map handle anymore WIN32CHECK(CloseHandle(hMap)); if (NULL != memchr(lpMapAddr, 0, dwSize)) { // File is binary or Unicode file WIN32CHECK(UnmapViewOfFile(lpMapAddr)); lpMapAddr = NULL; return FILE_BINARY_ERROR; } return OPEN_NO_ERROR; }
BOOL INTERNAL RgIsBadSubKey( LPCSTR lpSubKey ) { LPCSTR lpString; UINT SubSubKeyLength; BYTE Char; if (IsNullPtr(lpSubKey)) return FALSE; if (!IsBadStringPtr(lpSubKey, (UINT) -1)) { lpString = lpSubKey; SubSubKeyLength = 0; while (TRUE) { Char = *((LPBYTE) lpString); if (Char == '\0') return FALSE; else if (Char == '\\') { // Catch double-backslashes and leading backslashes. One // leading backslash is acceptable... if (SubSubKeyLength == 0 && lpString != lpSubKey) break; SubSubKeyLength = 0; } else { if (IsDBCSLeadByte(Char)) { SubSubKeyLength++; // Catch an unpaired DBCS pair... if (*lpString++ == '\0') break; } // Win95 compatibility: don't accept strings with control // characters. else if (Char < ' ') break; if (++SubSubKeyLength >= MAXIMUM_SUB_KEY_LENGTH) break; } lpString++; } } return TRUE; }
SnapCurrentProcessMiniDumpW ( MINIDUMP_TYPE eType , LPCWSTR szDumpName ) { // Where the registers coming into this function are stored. CONTEXT stInitialCtx ; // Where the final registers are stored. CONTEXT stFinalCtx ; // The return value. BSUMDRET eRet ; // Boolean return value local. BOOL bRetVal ; // Do the prolog. SNAPPROLOG ( stInitialCtx ) ; eRet = eDUMP_SUCCEEDED ; // Check the string parameter. ASSERT ( FALSE == IsBadStringPtr ( szDumpName , MAX_PATH ) ) ; if ( TRUE == IsBadStringPtr ( szDumpName , MAX_PATH ) ) { eRet = eBAD_PARAM ; } if ( eDUMP_SUCCEEDED == eRet ) { // Zero out the final context structure. ZeroMemory ( &stFinalCtx , sizeof ( CONTEXT ) ) ; // Inicate I want everything in the context. stFinalCtx.ContextFlags = CONTEXT_FULL | CONTEXT_CONTROL | CONTEXT_DEBUG_REGISTERS | CONTEXT_EXTENDED_REGISTERS | CONTEXT_FLOATING_POINT ; // Get all the groovy context registers and such for this // thread. bRetVal = GetThreadContext ( GetCurrentThread ( ) ,&stFinalCtx); ASSERT ( TRUE == bRetVal ) ; if ( TRUE == bRetVal ) { COPYKEYCONTEXTREGISTERS ( stFinalCtx , stInitialCtx ) ; // Get the return address and hunt down the call instruction // that got us into this function. All the rest of the // registers are set up before the call so I'll ensure the // instruction pointer is set that way too. UINT_PTR dwRetAddr = (UINT_PTR)_ReturnAddress ( ) ; bRetVal = CalculateBeginningOfCallInstruction ( dwRetAddr ); ASSERT ( TRUE == bRetVal ) ; if ( TRUE == bRetVal ) { // Set the instruction pointer to the beginning of the // call instruction. stFinalCtx.Eip = (DWORD)dwRetAddr ; // Call the common function that does the actual write. eRet = CommonSnapCurrentProcessMiniDump ( eType , szDumpName , &stFinalCtx ); } else { eRet = eGETTHREADCONTEXT_FAILED ; } } } // Do the epilog. SNAPEPILOG ( eRet ) ; }
// Registers a window class. You can specify the class name in // szClassName. If the string is empty, the library will generate a // name for you automagically. BOOL JfxRegisterClass ( UINT nClassStyle , LPTSTR szClassName , UINT nSizeOfName , HCURSOR hCursor , HBRUSH hbrBackground , HICON hIconBig , HICON hIconSmall , HINSTANCE hInst ) { ASSERT ( FALSE == IsBadStringPtr ( szClassName , nSizeOfName ) ) ; if ( TRUE == IsBadStringPtr ( szClassName , nSizeOfName ) ) { return ( FALSE ) ; } // If the name is empty, generate one. if ( _T ( '\0' ) == szClassName[ 0 ] ) { if ( ( NULL == hCursor ) && ( NULL == hbrBackground ) && ( NULL == hIconBig ) ) { wsprintf ( szClassName , _T ( "JFX:%x:%x" ) , hInst , nClassStyle ) ; } else { wsprintf ( szClassName , _T ( "JFX:%x:%x:%x:%x:%x" ) , hInst , nClassStyle , hCursor , hbrBackground , hIconBig ) ; } } // Does the class already exist? WNDCLASSEX wndClass ; wndClass.cbSize = sizeof ( WNDCLASSEX ) ; if ( TRUE == ::GetClassInfoEx ( hInst , szClassName , &wndClass ) ) { ASSERT ( wndClass.style == nClassStyle ) ; return ( TRUE ) ; } wndClass.cbClsExtra = 0 ; wndClass.hbrBackground = hbrBackground ; wndClass.hCursor = hCursor ; wndClass.hIcon = hIconBig ; wndClass.hIconSm = hIconSmall ; wndClass.hInstance = hInst ; wndClass.lpfnWndProc = (WNDPROC)JWnd::CommonWndProc ; wndClass.lpszClassName = szClassName ; wndClass.lpszMenuName = NULL ; wndClass.style = nClassStyle ; wndClass.cbWndExtra = 0 ; return ( 0 != ::RegisterClassEx ( &wndClass ) ) ; }
// Launch ErrorReporter Application LONG minidump_launcherrorreporter(LPCTSTR pszDumpFile) { LONG lReturnVal = EXCEPTION_CONTINUE_SEARCH; TCHAR szModuleName[MAX_PATH]; TCHAR szCommandLine[MAX_PATH]; TCHAR szCrashReportExe[MAX_PATH]; ZeroMemory(szModuleName, sizeof(szModuleName)); if (GetModuleFileName(0, szModuleName, _countof(szModuleName) - sizeof(TCHAR)) <= 0) lstrcpy(szModuleName, _T("Unknown")); TCHAR *pszFilePart = lstrrchr(szModuleName, _T('\\')); if (pszFilePart) pszFilePart++; else pszFilePart = (TCHAR *)szModuleName; lstrcpy(pszFilePart, "ErrorReporter.exe"); ZeroMemory(szCrashReportExe, sizeof(szCrashReportExe)); lstrcpy(szCrashReportExe, szModuleName); // Append dump file name wrapped with quotes lstrcat(szCommandLine, _T(" \"")); if (FALSE == IsBadStringPtr(pszDumpFile, MAX_PATH)) lstrcat(szCommandLine, pszDumpFile); else lstrcat(szCommandLine, MINIDUMP_FILE); lstrcat(szCommandLine, _T("\"")); STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_SHOW; PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); if (CreateProcess( szCrashReportExe, // name of executable module szCommandLine, // command line string NULL, // process attributes NULL, // thread attributes FALSE, // handle inheritance option 0, // creation flags NULL, // new environment block NULL, // current directory name &si, // startup information &pi)) // process information { // CrashReport.exe was successfully started, so // suppress the standard crash dialog lReturnVal = EXCEPTION_EXECUTE_HANDLER; } else { // CrashReport.exe was not started - let // the standard crash dialog appear lReturnVal = EXCEPTION_CONTINUE_SEARCH; } return lReturnVal; }
BOOL __stdcall HookOrdinalExport ( HMODULE hModule , LPCTSTR szImportMod , DWORD dwOrdinal , PROC pHookFunc , PROC * ppOrigAddr ) { // Assert the parameters. ASSERT ( NULL != hModule ) ; ASSERT ( FALSE == IsBadStringPtr ( szImportMod , MAX_PATH ) ) ; ASSERT ( 0 != dwOrdinal ) ; ASSERT ( FALSE == IsBadCodePtr ( pHookFunc ) ) ; // Perform the error checking for the parameters. if ( ( NULL == hModule ) || ( TRUE == IsBadStringPtr ( szImportMod , MAX_PATH ) ) || ( 0 == dwOrdinal ) || ( TRUE == IsBadCodePtr ( pHookFunc ) ) ) { SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ; return ( FALSE ) ; } if ( NULL != ppOrigAddr ) { ASSERT ( FALSE == IsBadWritePtr ( ppOrigAddr , sizeof ( PROC ) ) ) ; if ( TRUE == IsBadWritePtr ( ppOrigAddr , sizeof ( PROC ) ) ) { SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ; return ( FALSE ) ; } } // Get the specific import descriptor. PIMAGE_IMPORT_DESCRIPTOR pImportDesc = GetNamedImportDescriptor ( hModule , szImportMod ) ; if ( NULL == pImportDesc ) { // The requested module wasn't imported. Don't return an error. return ( TRUE ) ; } // Get the original thunk information for this DLL. I can't use // the thunk information stored in pImportDesc->FirstThunk // because the loader has already changed that array to fix up // all the imports. The original thunk gives me access to the // function names. PIMAGE_THUNK_DATA pOrigThunk = MakePtr ( PIMAGE_THUNK_DATA , hModule , pImportDesc->OriginalFirstThunk ) ; // Get the array that pImportDesc->FirstThunk points to because I'll // do the actual hooking there. PIMAGE_THUNK_DATA pRealThunk = MakePtr ( PIMAGE_THUNK_DATA , hModule , pImportDesc->FirstThunk ); // The flag is going to be set from the thunk, so make it // easier to look up. DWORD dwCompareOrdinal = IMAGE_ORDINAL_FLAG | dwOrdinal ; // Loop through and find the function to hook. while ( NULL != pOrigThunk->u1.Function ) { // Look only at functions that are imported by ordinal value, // not those that are imported by name. if ( IMAGE_ORDINAL_FLAG == ( pOrigThunk->u1.Ordinal & IMAGE_ORDINAL_FLAG )) { // Did I find the function to hook? if ( dwCompareOrdinal == pOrigThunk->u1.Ordinal ) { // I found the function to hook. Now I need to change // the memory protection to writable before I overwrite // the function pointer. Note that I'm now writing into // the real thunk area! MEMORY_BASIC_INFORMATION mbi_thunk ; VirtualQuery ( pRealThunk , &mbi_thunk , sizeof ( MEMORY_BASIC_INFORMATION ) ) ; if ( FALSE == VirtualProtect ( mbi_thunk.BaseAddress , mbi_thunk.RegionSize , PAGE_READWRITE , &mbi_thunk.Protect )) { ASSERT ( !"VirtualProtect failed!" ) ; // There's nothing I can do but fail the function. SetLastErrorEx ( ERROR_INVALID_PARAMETER , SLE_ERROR ) ; return ( FALSE ) ; } // Save the original address if requested. if ( NULL != ppOrigAddr ) { *ppOrigAddr = (PROC)pRealThunk->u1.Function ; } // Microsoft has two different definitions of the // PIMAGE_THUNK_DATA fields as they are moving to // support Win64. The W2K RC2 Platform SDK is the // latest header, so I'll use that one and force the // Visual C++ 6 Service Pack 3 headers to deal with it. // Hook the function. DWORD * pTemp = (DWORD*)&pRealThunk->u1.Function ; *pTemp = (DWORD)(pHookFunc) ; DWORD dwOldProtect ; // Change the protection back to what it was before I // overwrote the function pointer. VERIFY ( VirtualProtect ( mbi_thunk.BaseAddress , mbi_thunk.RegionSize , mbi_thunk.Protect , &dwOldProtect ) ) ; // Life is good. SetLastError ( ERROR_SUCCESS ) ; return ( TRUE ) ; } } // Increment both tables. pOrigThunk++ ; pRealThunk++ ; } // Nothing was hooked. Technically, this isn't an error. It just // means that the module is imported but the function isn't. SetLastError ( ERROR_SUCCESS ) ; return ( FALSE ) ; }
LONG REGAPI VMMRegQueryMultipleValues( HKEY hKey, PVALENT val_list, DWORD num_vals, LPSTR lpValueBuffer, LPDWORD lpdwTotalSize ) { int ErrorCode; PVALENT pCurrentValent; DWORD Counter; DWORD BufferSize; DWORD RequiredSize; LPKEY_RECORD lpKeyRecord; LPVALUE_RECORD lpValueRecord; LPSTR lpCurrentBuffer; #ifdef WANT_DYNKEY_SUPPORT PVALCONTEXT pValueContext; PINTERNAL_PROVIDER pProvider; PPVALUE pProviderValue; #endif if (IsBadHugeReadPtr(val_list, sizeof(VALENT) * num_vals)) return ERROR_INVALID_PARAMETER; if (IsBadHugeWritePtr(lpdwTotalSize, sizeof(DWORD))) return ERROR_INVALID_PARAMETER; if (IsBadHugeWritePtr(lpValueBuffer, *lpdwTotalSize)) return ERROR_INVALID_PARAMETER; for (Counter = num_vals, pCurrentValent = val_list; Counter > 0; Counter--, pCurrentValent++) { if (IsBadStringPtr(pCurrentValent-> ve_valuename, (UINT) -1)) return ERROR_INVALID_PARAMETER; } if (!RgLockRegistry()) return ERROR_LOCK_FAILED; if ((ErrorCode = RgValidateAndConvertKeyHandle(&hKey)) != ERROR_SUCCESS) goto ReturnErrorCode; #ifdef WANT_DYNKEY_SUPPORT // Check if this a dynamic key that has a "get all" atomic callback. If // the dynamic key just has "get one" callback, then we'll fall into the // non-dynamic case. if ((hKey-> PredefinedKeyIndex == INDEX_DYN_DATA) && !IsNullPtr(hKey-> pProvider-> ipi_R0_allvals)) { pProvider = hKey-> pProvider; pValueContext = RgSmAllocMemory(sizeof(struct val_context) * num_vals); if (IsNullPtr(pValueContext)) { ErrorCode = ERROR_OUTOFMEMORY; goto ReturnErrorCode; } // // Compute the required buffer size to hold all the value data and // check it against the provided buffer size. // RequiredSize = 0; for (Counter = 0, pCurrentValent = val_list; Counter < num_vals; Counter++, pCurrentValent++) { if ((ErrorCode = RgLookupValueByName(hKey, pCurrentValent-> ve_valuename, &lpKeyRecord, &lpValueRecord)) != ERROR_SUCCESS) goto ReturnErrorCode; // The value data contains only part of a PROVIDER structure. pProviderValue = CONTAINING_RECORD(&lpValueRecord-> Name + lpValueRecord-> NameLength, PVALUE, pv_valuelen); pValueContext[Counter].value_context = pProviderValue-> pv_value_context; pCurrentValent-> ve_type = pProviderValue-> pv_type; if (hKey-> Flags & KEYF_PROVIDERHASVALUELENGTH) { // Must zero it so that some providers don't try to stomp on // lpData. pCurrentValent-> ve_valuelen = 0; ErrorCode = pProvider-> ipi_R0_1val(pProvider-> ipi_key_context, &pValueContext[Counter], 1, NULL, &(pCurrentValent-> ve_valuelen), 0); // Providers should really be returning either of these errors // to us. ASSERT((ErrorCode == ERROR_SUCCESS) || (ErrorCode == ERROR_MORE_DATA)); } else { pCurrentValent-> ve_valuelen = pProviderValue-> pv_valuelen; } RgUnlockDatablock(hKey-> lpFileInfo, hKey-> BlockIndex, FALSE); pCurrentValent-> ve_valueptr = (DWORD) NULL; RequiredSize += pCurrentValent-> ve_valuelen; } BufferSize = *lpdwTotalSize; *lpdwTotalSize = RequiredSize; if (BufferSize < RequiredSize) ErrorCode = ERROR_MORE_DATA; else if (pProvider-> ipi_R0_allvals(pProvider-> ipi_key_context, pValueContext, num_vals, lpValueBuffer, lpdwTotalSize, 0) != ERROR_SUCCESS) ErrorCode = ERROR_CANTREAD; else { ErrorCode = ERROR_SUCCESS; // Copy the pointers to the value data back to the user's buffer. // Don't ask me why, but the Win95 code copies the value length // back again if the provider is maintaining it. for (Counter = 0, pCurrentValent = val_list; Counter < num_vals; Counter++, pCurrentValent++) { pCurrentValent-> ve_valueptr = (DWORD) pValueContext[Counter].val_buff_ptr; if (hKey-> Flags & KEYF_PROVIDERHASVALUELENGTH) pCurrentValent-> ve_valuelen = pValueContext[Counter].valuelen; } } RgSmFreeMemory(pValueContext); goto ReturnErrorCode; } #endif // // First pass over the value names checks for the existence of the value // and its size. We check the total size against the provided buffer size // and bail out if necessary. // RequiredSize = 0; for (Counter = num_vals, pCurrentValent = val_list; Counter > 0; Counter--, pCurrentValent++) { if ((ErrorCode = RgLookupValueByName(hKey, pCurrentValent-> ve_valuename, &lpKeyRecord, &lpValueRecord)) != ERROR_SUCCESS) goto ReturnErrorCode; ErrorCode = RgCopyFromValueRecord(hKey, lpValueRecord, NULL, NULL, &(pCurrentValent-> ve_type), NULL, &(pCurrentValent-> ve_valuelen)); RgUnlockDatablock(hKey-> lpFileInfo, hKey-> BlockIndex, FALSE); if (ErrorCode != ERROR_SUCCESS) goto ReturnErrorCode; pCurrentValent-> ve_valueptr = (DWORD) NULL; RequiredSize += pCurrentValent-> ve_valuelen; } BufferSize = *lpdwTotalSize; *lpdwTotalSize = RequiredSize; if (BufferSize < RequiredSize) { ErrorCode = ERROR_MORE_DATA; goto ReturnErrorCode; } // // Second pass copies the value data back to the user's buffer now that we // know the buffer is large enough to contain the data. // lpCurrentBuffer = lpValueBuffer; for (Counter = num_vals, pCurrentValent = val_list; Counter > 0; Counter--, pCurrentValent++) { if ((ErrorCode = RgLookupValueByName(hKey, pCurrentValent-> ve_valuename, &lpKeyRecord, &lpValueRecord)) != ERROR_SUCCESS) goto ReturnErrorReading; ErrorCode = RgCopyFromValueRecord(hKey, lpValueRecord, NULL, NULL, NULL, lpCurrentBuffer, &(pCurrentValent-> ve_valuelen)); RgUnlockDatablock(hKey-> lpFileInfo, hKey-> BlockIndex, FALSE); if (ErrorCode != ERROR_SUCCESS) { ReturnErrorReading: TRAP(); // Registry is internally inconsistent? ErrorCode = ERROR_CANTREAD; goto ReturnErrorCode; } pCurrentValent-> ve_valueptr = (DWORD) lpCurrentBuffer; lpCurrentBuffer += pCurrentValent-> ve_valuelen; } ErrorCode = ERROR_SUCCESS; ReturnErrorCode: RgUnlockRegistry(); return ErrorCode; }
int ChangeLayout(HWND hTextWnd, BYTE TextOperation, BOOL CurrentWord) { HKL hklCurLay, hklToLay; LPTSTR ptszInText, ptszOutText, ptszMBox, ptszPopupText, ptszTemp; CHARRANGE crSelection, crTemp; DWORD dwStartWord, dwEndWord; int i, iRes; BYTE WindowType = WTYPE_Unknown; BOOL WindowIsReadOnly, TwoWay; if (hTextWnd == NULL) hTextWnd = GetFocus(); if (hTextWnd == NULL) return 0; //--------------Определяем тип окна----------------- IEVIEWEVENT ieEvent = { 0 }; ieEvent.cbSize = sizeof(IEVIEWEVENT); ieEvent.iType = IEE_GET_SELECTION; if (ServiceExists(MS_HPP_EG_EVENT)) { // То же самое для History++ ieEvent.hwnd = hTextWnd; ptszInText = (TCHAR*)CallService(MS_HPP_EG_EVENT, 0, (LPARAM)&ieEvent); if (!IsBadStringPtr(ptszInText, MaxTextSize)) WindowType = WTYPE_HistoryPP; } if ((WindowType == WTYPE_Unknown) && (ServiceExists(MS_IEVIEW_EVENT))) { // Извращенное определение хэндла IEView ieEvent.hwnd = GetParent(GetParent(hTextWnd)); ptszInText = (TCHAR*)CallService(MS_IEVIEW_EVENT, 0, (LPARAM)&ieEvent); if (!IsBadStringPtr(ptszInText, MaxTextSize)) WindowType = WTYPE_IEView; } if (WindowType == WTYPE_Unknown) { ptszTemp = (LPTSTR)mir_alloc(255 * sizeof(TCHAR)); i = GetClassName(hTextWnd, ptszTemp, 255); ptszTemp[i] = 0; if (_tcsstr(CharUpper(ptszTemp), _T("RICHEDIT")) != NULL) { WindowType = WTYPE_RichEdit; SendMessage(hTextWnd, EM_EXGETSEL, 0, (LPARAM)&crSelection); } mir_free(ptszTemp); } if (WindowType == WTYPE_Unknown) { SendMessage(hTextWnd, EM_GETSEL, (WPARAM)&crSelection.cpMin, (LPARAM)&crSelection.cpMax); if ((SendMessage(hTextWnd, WM_GETDLGCODE, 0, 0)&(DLGC_HASSETSEL)) && (crSelection.cpMin >= 0)) WindowType = WTYPE_Edit; } // Получим текст из Рича или обычного Едита if (WindowType == WTYPE_RichEdit || WindowType == WTYPE_Edit) { dwStartWord = dwEndWord = -1; SendMessage(hTextWnd, WM_SETREDRAW, FALSE, 0); // Бэкап выделения crTemp = crSelection; // Если имеется выделенный текст, то получим его if (crSelection.cpMin != crSelection.cpMax) { if (WindowType == WTYPE_RichEdit) { EditStreamData esdData; EDITSTREAM esStream = { 0 }; esStream.dwCookie = (DWORD)&esdData; esStream.pfnCallback = EditStreamOutRtf; if (SendMessage(hTextWnd, EM_STREAMOUT, SF_TEXT | SF_UNICODE | SFF_SELECTION, (LPARAM)&esStream) > 0) ptszInText = GeTStringFromStreamData(&esdData); else { SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crSelection); SendMessage(hTextWnd, WM_SETREDRAW, TRUE, 0); InvalidateRect(hTextWnd, NULL, FALSE); return 1; } } if (WindowType == WTYPE_Edit) { ptszTemp = (LPTSTR)mir_alloc(MaxTextSize*sizeof(TCHAR)); ptszInText = (LPTSTR)mir_alloc(MaxTextSize*sizeof(TCHAR)); iRes = SendMessage(hTextWnd, WM_GETTEXT, (WPARAM)MaxTextSize, (LPARAM)ptszTemp); if (!IsBadStringPtr(ptszInText, MaxTextSize) && (iRes > 0)) { _tcsncpy(ptszInText, &ptszTemp[crSelection.cpMin], crSelection.cpMax - crSelection.cpMin); ptszInText[crSelection.cpMax - crSelection.cpMin] = 0; mir_free(ptszTemp); } else { SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crSelection); SendMessage(hTextWnd, WM_SETREDRAW, TRUE, 0); InvalidateRect(hTextWnd, NULL, FALSE); return 1; } } } // Если выделения нет, то получим нужный текст else { // Получаем весь текст в поле if (WindowType == WTYPE_RichEdit) { crTemp.cpMin = 0; crTemp.cpMax = -1; SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crTemp); EditStreamData esdData; EDITSTREAM esStream = { 0 }; esStream.dwCookie = (DWORD)&esdData; esStream.pfnCallback = EditStreamOutRtf; if (SendMessage(hTextWnd, EM_STREAMOUT, SF_TEXT | SF_UNICODE | SFF_SELECTION, (LPARAM)&esStream) != 0) ptszInText = GeTStringFromStreamData(&esdData); else { SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crSelection); SendMessage(hTextWnd, WM_SETREDRAW, TRUE, 0); InvalidateRect(hTextWnd, NULL, FALSE); return 1; } } if (WindowType == WTYPE_Edit) { ptszInText = (LPTSTR)mir_alloc(MaxTextSize*sizeof(TCHAR)); iRes = SendMessage(hTextWnd, WM_GETTEXT, (WPARAM)MaxTextSize, (LPARAM)ptszInText); if (!IsBadStringPtr(ptszInText, MaxTextSize) && (iRes > 0)) { crTemp.cpMin = 0; crTemp.cpMax = (int)_tcslen(ptszInText); } else { SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crSelection); SendMessage(hTextWnd, WM_SETREDRAW, TRUE, 0); InvalidateRect(hTextWnd, NULL, FALSE); return 1; } } // Получаем текущее слово if (CurrentWord) { for (dwStartWord = crSelection.cpMin; (dwStartWord > 0) && (_tcschr(ptszSeparators, ptszInText[dwStartWord - 1]) == NULL); dwStartWord--); for (dwEndWord = crSelection.cpMin; (dwEndWord < (_tcslen(ptszInText))) && (_tcschr(ptszSeparators, ptszInText[dwEndWord]) == NULL); dwEndWord++); crTemp.cpMin = dwStartWord; crTemp.cpMax = dwEndWord; if (WindowType == WTYPE_RichEdit) { SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crTemp); EditStreamData esdData; EDITSTREAM esStream = { 0 }; esStream.dwCookie = (DWORD)&esdData; esStream.pfnCallback = EditStreamOutRtf; if (SendMessage(hTextWnd, EM_STREAMOUT, SF_TEXT | SF_UNICODE | SFF_SELECTION, (LPARAM)&esStream) != 0) ptszInText = GeTStringFromStreamData(&esdData); else { SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crSelection); SendMessage(hTextWnd, WM_SETREDRAW, TRUE, 0); InvalidateRect(hTextWnd, NULL, FALSE); return 1; } } if (WindowType == WTYPE_Edit) { ptszTemp = (LPTSTR)mir_alloc(MaxTextSize*sizeof(TCHAR)); _tcsncpy(ptszTemp, &ptszInText[crTemp.cpMin], crTemp.cpMax - crTemp.cpMin); ptszTemp[crTemp.cpMax - crTemp.cpMin] = 0; _tcscpy(ptszInText, ptszTemp); mir_free(ptszTemp); if (_tcslen(ptszInText) == 0) { mir_free(ptszInText); SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crSelection); SendMessage(hTextWnd, WM_SETREDRAW, TRUE, 0); InvalidateRect(hTextWnd, NULL, FALSE); return 1; } } } } } //---------------Выдаем результаты-------------------- WindowIsReadOnly = FALSE; if (WindowType == WTYPE_IEView || WindowType == WTYPE_HistoryPP) WindowIsReadOnly = TRUE; // if ((SendMessage(hTextWnd, EM_GETOPTIONS, 0, 0)&ECO_READONLY)) if (WindowType == WTYPE_RichEdit || WindowType == WTYPE_Edit) if (GetWindowLongPtr(hTextWnd, GWL_STYLE) & ES_READONLY) WindowIsReadOnly = TRUE; // Лог Иевью и ХисториПП в режиме эмуляции Иевью и поля только для чтения. if (WindowType != WTYPE_Unknown && !IsBadStringPtr(ptszInText, MaxTextSize)) if (WindowIsReadOnly) { ptszMBox = (LPTSTR)mir_alloc(MaxTextSize*sizeof(TCHAR)); ptszMBox[0] = 0; if (TextOperation == TOT_Layout) { hklCurLay = GetLayoutOfText(ptszInText); hklToLay = GetNextLayout(hklCurLay); TwoWay = (moOptions.TwoWay) && (bLayNum == 2); if (bLayNum == 2) { ptszMBox = ChangeTextLayout(ptszInText, hklCurLay, hklToLay, TwoWay); } else { for (i = 0; i < bLayNum; i++) if (hklLayouts[i] != hklCurLay) { if (_tcslen(ptszMBox) != 0) _tcscat(ptszMBox, _T("\n\n")); ptszTemp = GetShortNameOfLayout(hklLayouts[i]); _tcscat(ptszMBox, ptszTemp); _tcscat(ptszMBox, _T(":\n")); ptszOutText = ChangeTextLayout(ptszInText, hklCurLay, hklLayouts[i], FALSE); _tcscat(ptszMBox, ptszOutText); mir_free(ptszTemp); mir_free(ptszOutText); } } } else if (TextOperation == TOT_Case) { ptszMBox = ChangeTextCase(ptszInText); } mir_free(ptszInText); if ((WindowType == WTYPE_Edit) || (WindowType == WTYPE_RichEdit)) { SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crSelection); SendMessage(hTextWnd, WM_SETREDRAW, TRUE, 0); InvalidateRect(hTextWnd, NULL, FALSE); } if (TextOperation == TOT_Layout) SkinPlaySound(SND_ChangeLayout); else if (TextOperation == TOT_Case) SkinPlaySound(SND_ChangeCase); if (moOptions.CopyToClipboard) CopyTextToClipboard(ptszMBox); //-------------------------------Покажем попапы------------------------------------------ if (moOptions.ShowPopup) { ptszPopupText = (LPTSTR)mir_alloc(MaxTextSize*sizeof(TCHAR)); _tcscpy(ptszPopupText, ptszMBox); POPUPDATAT_V2 pdtData = { 0 }; pdtData.cbSize = sizeof(pdtData); _tcsncpy(pdtData.lptzContactName, TranslateT(ModuleName), MAX_CONTACTNAME); _tcsncpy(pdtData.lptzText, ptszPopupText, MAX_SECONDLINE); switch (poOptions.bColourType) { case PPC_POPUP: pdtData.colorBack = pdtData.colorText = 0; break; case PPC_WINDOWS: pdtData.colorBack = GetSysColor(COLOR_BTNFACE); pdtData.colorText = GetSysColor(COLOR_WINDOWTEXT); break; case PPC_CUSTOM: pdtData.colorBack = poOptions.crBackColour; pdtData.colorText = poOptions.crTextColour; break; } switch (poOptions.bTimeoutType) { case PPT_POPUP: pdtData.iSeconds = 0; break; case PPT_PERMANENT: pdtData.iSeconds = -1; break; case PPC_CUSTOM: pdtData.iSeconds = poOptions.bTimeout; break; } pdtData.PluginData = ptszPopupText; pdtData.PluginWindowProc = (WNDPROC)CKLPopupDlgProc; pdtData.lchIcon = hPopupIcon; poOptions.paActions[0].lchIcon = hCopyIcon; pdtData.lpActions = poOptions.paActions; pdtData.actionCount = 1; if (CallService(MS_POPUP_ADDPOPUPT, (WPARAM)&pdtData, APF_NEWDATA) < 0) { mir_free(ptszPopupText); MessageBox(NULL, ptszMBox, TranslateT(ModuleName), MB_ICONINFORMATION); } } mir_free(ptszMBox); } //------------------Редактируемые поля ---------------------------- else { if (TextOperation == TOT_Layout) { hklCurLay = GetLayoutOfText(ptszInText); hklToLay = GetNextLayout(hklCurLay); TwoWay = (moOptions.TwoWay) && (bLayNum == 2); ptszOutText = ChangeTextLayout(ptszInText, hklCurLay, hklToLay, TwoWay); } else if (TextOperation == TOT_Case) { ptszOutText = ChangeTextCase(ptszInText); } if (WindowType == WTYPE_RichEdit) { SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crTemp); SendMessage(hTextWnd, EM_REPLACESEL, FALSE, (LPARAM)ptszOutText); SendMessage(hTextWnd, EM_EXSETSEL, 0, (LPARAM)&crSelection); } else { ptszTemp = (LPTSTR)mir_alloc(MaxTextSize*sizeof(TCHAR)); SendMessage(hTextWnd, WM_GETTEXT, (WPARAM)MaxTextSize, (LPARAM)ptszTemp); for (i = crTemp.cpMin; i < crTemp.cpMax; i++) ptszTemp[i] = ptszOutText[i - crTemp.cpMin]; SendMessage(hTextWnd, WM_SETTEXT, 0, (LPARAM)ptszTemp); SendMessage(hTextWnd, EM_SETSEL, crSelection.cpMin, crSelection.cpMax); mir_free(ptszTemp); } // Переключим раскладку или изменим состояние Caps Lock if (TextOperation == TOT_Layout && hklToLay != NULL && moOptions.ChangeSystemLayout) ActivateKeyboardLayout(hklToLay, KLF_SETFORPROCESS); else if (TextOperation == TOT_Case) { // Если нужно инвертнуть if (moOptions.bCaseOperations == 0) { keybd_event(VK_CAPITAL, 0x45, 0, 0); keybd_event(VK_CAPITAL, 0x45, KEYEVENTF_KEYUP, 0); } // Если нужно отключить else if (moOptions.bCaseOperations == 1) { if (GetKeyState(VK_CAPITAL) & 0x0001) { keybd_event(VK_CAPITAL, 0x45, 0, 0); keybd_event(VK_CAPITAL, 0x45, KEYEVENTF_KEYUP, 0); } } } SendMessage(hTextWnd, WM_SETREDRAW, TRUE, 0); InvalidateRect(hTextWnd, NULL, FALSE); if (TextOperation == TOT_Layout) SkinPlaySound(SND_ChangeLayout); else if (TextOperation == TOT_Case) SkinPlaySound(SND_ChangeCase); mir_free(ptszInText); mir_free(ptszOutText); } return 0; }