void CEditUI::DoEvent(TEventUI& event) { if( !IsMouseEnabled() && event.Type > UIEVENT__MOUSEBEGIN && event.Type < UIEVENT__MOUSEEND ) { if( m_pParent != NULL ) m_pParent->DoEvent(event); else CLabelUI::DoEvent(event); return; } if( event.Type == UIEVENT_SETCURSOR && IsEnabled() ) { ::SetCursor(::LoadCursor(NULL, IDC_IBEAM)); return; } if( event.Type == UIEVENT_WINDOWSIZE ) { if( m_pWindow != NULL ) m_pManager->SetFocusNeeded(this); } if( event.Type == UIEVENT_SCROLLWHEEL ) { if( m_pWindow != NULL ) return; } if( event.Type == UIEVENT_SETFOCUS && IsEnabled() ) { if( m_pWindow ) return; m_pWindow = new CEditWnd(); ASSERT(m_pWindow); m_pWindow->Init(this); Invalidate(); } if( event.Type == UIEVENT_KILLFOCUS && IsEnabled() ) { Invalidate(); } if( event.Type == UIEVENT_BUTTONDOWN || event.Type == UIEVENT_DBLCLICK || event.Type == UIEVENT_RBUTTONDOWN) { if( IsEnabled() ) { GetManager()->ReleaseCapture(); if( IsFocused() && m_pWindow == NULL ) { m_pWindow = new CEditWnd(); ASSERT(m_pWindow); m_pWindow->Init(this); if( PtInRect(&m_rcItem, event.ptMouse) ) { int nSize = GetWindowTextLength(*m_pWindow); if( nSize == 0 ) nSize = 1; Edit_SetSel(*m_pWindow, 0, nSize); } } else if( m_pWindow != NULL ) { #if 1 int nSize = GetWindowTextLength(*m_pWindow); if( nSize == 0 ) nSize = 1; Edit_SetSel(*m_pWindow, 0, nSize); #else POINT pt = event.ptMouse; pt.x -= m_rcItem.left + m_rcTextPadding.left; pt.y -= m_rcItem.top + m_rcTextPadding.top; ::SendMessage(*m_pWindow, WM_LBUTTONDOWN, event.wParam, MAKELPARAM(pt.x, pt.y)); #endif } } return; } if( event.Type == UIEVENT_MOUSEMOVE ) { return; } if( event.Type == UIEVENT_BUTTONUP ) { return; } if( event.Type == UIEVENT_CONTEXTMENU ) { return; } if( event.Type == UIEVENT_MOUSEENTER ) { if( IsEnabled() ) { m_uButtonState |= UISTATE_HOT; Invalidate(); } return; } if( event.Type == UIEVENT_MOUSELEAVE ) { if( IsEnabled() ) { m_uButtonState &= ~UISTATE_HOT; Invalidate(); } return; } CLabelUI::DoEvent(event); }
static INT_PTR LinkList_Main(WPARAM wParam, LPARAM) { HANDLE hContact = (HANDLE)wParam; HWND hWnd = WindowList_Find(hWindowList, hContact); if ( hWnd != NULL ) { int len; SetForegroundWindow(hWnd); SetFocus(hWnd); len = GetWindowTextLength(GetDlgItem(hWnd, IDC_MAIN)); PostMessage(GetDlgItem(hWnd, IDC_MAIN), EM_SETSEL, (WPARAM)len, (LPARAM)len); return 0; } HANDLE hEvent = db_event_first(hContact); if (hEvent == NULL) { MessageBox(NULL, TXT_EMPTYHISTORY, TXT_PLUGINNAME, MB_OK | MB_ICONINFORMATION ); return 0; } int histCount = db_event_count(hContact), actCount = 0; DBEVENTINFO dbe = { sizeof(dbe) }; dbe.cbBlob = db_event_getBlobSize(hEvent); dbe.pBlob = (PBYTE)malloc(dbe.cbBlob+1); db_event_get(hEvent, &dbe); dbe.pBlob[dbe.cbBlob] = 0; RECT DesktopRect; GetWindowRect(GetDesktopWindow(), &DesktopRect); HWND hWndProgress = CreateWindow(_T("Progressbar"), TranslateT("Processing history..."), WS_OVERLAPPED, CW_USEDEFAULT, CW_USEDEFAULT, 350, 45, NULL, NULL, hInst, NULL); if ( hWndProgress == 0 ) { free(dbe.pBlob); MessageBox(NULL, TranslateT("Could not create window!"), TranslateT("Error"), MB_OK | MB_ICONEXCLAMATION ); return -1; } SetWindowPos(hWndProgress, HWND_TOP, (int)(DesktopRect.right*0.5)-175, (int)(DesktopRect.bottom*0.5)-22, 0, 0, SWP_NOSIZE); ShowWindow(hWndProgress, SW_SHOW); SetForegroundWindow(hWndProgress); LISTELEMENT *listStart = (LISTELEMENT*)malloc(sizeof(LISTELEMENT)); ZeroMemory(listStart, sizeof(LISTELEMENT)); while( 1 ) { if ( dbe.eventType == EVENTTYPE_URL || dbe.eventType == EVENTTYPE_MESSAGE ) { // Call function to find URIs if ( ExtractURI(&dbe, hEvent, listStart) < 0 ) { free(dbe.pBlob); RemoveList(listStart); MessageBox(NULL, TranslateT("Could not allocate memory!"), TranslateT("Error"), MB_OK | MB_ICONEXCLAMATION); return -1; } } actCount++; if ( ((int)(((float)actCount/histCount)*100.00)) % 10 == 0 ) SendMessage(hWndProgress, WM_COMMAND, 100, ((int)(((float)actCount/histCount)*100.00))); hEvent = db_event_next(hEvent); if ( hEvent == NULL ) break; free(dbe.pBlob); dbe.cbBlob = db_event_getBlobSize(hEvent); dbe.pBlob = (PBYTE)malloc(dbe.cbBlob+1); db_event_get(hEvent, &dbe); dbe.pBlob[dbe.cbBlob] = 0; } free(dbe.pBlob); SendMessage(hWndProgress, WM_CLOSE, 0, 0); if ( ListCount(listStart) <= 0 ) { RemoveList(listStart); MessageBox(NULL, TXT_NOLINKINHISTORY, TXT_PLUGINNAME, MB_OK | MB_ICONINFORMATION); return 0; } DIALOGPARAM *DlgParam = (DIALOGPARAM*)malloc(sizeof(DIALOGPARAM)); DlgParam->hContact = hContact; DlgParam->listStart = listStart; DlgParam->findMessage = 0; DlgParam->chrg.cpMax = -1; DlgParam->chrg.cpMin = -1; HWND hWndMain = CreateDialogParam(hInst, MAKEINTRESOURCE(IDD_MAIN_DLG), NULL, MainDlgProc, (LPARAM)DlgParam); if (hWndMain == 0) { RemoveList(listStart); MessageBox(NULL, TranslateT("Could not create window!"), TranslateT("Error"), MB_OK | MB_ICONEXCLAMATION ); return -1; } ShowWindow(hWndMain, SW_SHOW); return 0; }
int CxEdit::GotoEnd(BOOL bScroll /*= TRUE*/) { const int length = GetWindowTextLength(); SetSel(length, length, !bScroll); // end of edit text return LineFromChar(length); }
INT_PTR CALLBACK SelectContainerDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { HWND hwndMsgDlg = 0; hwndMsgDlg = (HWND) GetWindowLongPtr(hwndDlg, GWLP_USERDATA); switch (msg) { case WM_INITDIALOG: { TCHAR szNewTitle[128]; RECT rc, rcParent; struct TContainerData *pContainer = 0; SetWindowLongPtr(hwndDlg, GWLP_USERDATA, (LONG_PTR) lParam); hwndMsgDlg = (HWND) lParam; TranslateDialogDefault(hwndDlg); if (lParam) { struct TWindowData *dat = (struct TWindowData *)GetWindowLongPtr((HWND)lParam, GWLP_USERDATA); if (dat) { mir_sntprintf(szNewTitle, safe_sizeof(szNewTitle), CTranslator::get(CTranslator::CNT_SELECT_FOR), dat->cache->getNick()); SetWindowText(hwndDlg, szNewTitle); } } SendMessage(hwndDlg, DM_SC_BUILDLIST, 0, 0); SendDlgItemMessage(hwndDlg, IDC_NEWCONTAINERNAME, EM_LIMITTEXT, (WPARAM)CONTAINER_NAMELEN, 0); SendDlgItemMessage(hwndDlg, IDC_NEWCONTAINER, EM_LIMITTEXT, (WPARAM)CONTAINER_NAMELEN, 0); GetWindowRect(hwndDlg, &rc); GetWindowRect(GetParent(hwndDlg), &rcParent); SetWindowPos(hwndDlg, 0, (rcParent.left + rcParent.right - (rc.right - rc.left)) / 2, (rcParent.top + rcParent.bottom - (rc.bottom - rc.top)) / 2, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW); return TRUE; } case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: { TCHAR szName[CONTAINER_NAMELEN]; LRESULT iItem; if ((iItem = SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETCURSEL, 0, 0)) != LB_ERR) { SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETTEXT, (WPARAM) iItem, (LPARAM) szName); if (IsWindow(hwndMsgDlg)) SendMessage(hwndMsgDlg, DM_CONTAINERSELECTED, 0, (LPARAM) szName); } if (IsWindow(hwndDlg)) DestroyWindow(hwndDlg); break; } case IDCANCEL: DestroyWindow(hwndDlg); break; case IDC_DELETECONTAINER: { TCHAR szName[CONTAINER_NAMELEN + 1]; LRESULT iItem; if ((iItem = SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETCURSEL, 0, 0)) != LB_ERR) { SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETTEXT, (WPARAM) iItem, (LPARAM) szName); if (!_tcsncmp(szName, _T("default"), CONTAINER_NAMELEN) || !_tcsncmp(szName, CTranslator::get(CTranslator::GEN_DEFAULT_CONTAINER_NAME), CONTAINER_NAMELEN)) MessageBox(hwndDlg, CTranslator::get(CTranslator::CNT_SELECT_DELETEERROR), _T("Error"), MB_OK | MB_ICONERROR); else { int iIndex = SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETITEMDATA, (WPARAM)iItem, 0); DeleteContainer(iIndex); SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_RESETCONTENT, 0, 0); SendMessage(hwndDlg, DM_SC_BUILDLIST, 0, 0); BuildContainerMenu(); } } break; } case IDC_RENAMECONTAINER: { TCHAR szNewName[CONTAINER_NAMELEN], szName[CONTAINER_NAMELEN + 1]; int iLen, iItem; struct TContainerData *pCurrent = pFirstContainer; iLen = GetWindowTextLength(GetDlgItem(hwndDlg, IDC_NEWCONTAINERNAME)); if (iLen) { GetWindowText(GetDlgItem(hwndDlg, IDC_NEWCONTAINERNAME), szNewName, CONTAINER_NAMELEN); if(!_tcsncmp(szNewName, CGlobals::m_default_container_name, CONTAINER_NAMELEN) || !_tcsncmp(szNewName, CTranslator::get(CTranslator::GEN_DEFAULT_CONTAINER_NAME), CONTAINER_NAMELEN)) { MessageBox(hwndDlg, CTranslator::get(CTranslator::CNT_SELECT_RENAMEERROR), _T("Error"), MB_OK | MB_ICONERROR); break; } iItem = SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_FINDSTRING, (WPARAM) - 1, (LPARAM) szNewName); if (iItem != LB_ERR) { TCHAR szOldName[CONTAINER_NAMELEN + 1]; SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETTEXT, (WPARAM) iItem, (LPARAM) szOldName); if (lstrlen(szOldName) == lstrlen(szNewName)) { MessageBox(0, CTranslator::get(CTranslator::CNT_SELECT_INUSE), _T("Error"), MB_OK | MB_ICONERROR); SetFocus(GetDlgItem(hwndDlg, IDC_NEWCONTAINERNAME)); break; } } if ((iItem = SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETCURSEL, 0, 0)) != LB_ERR) { SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETTEXT, (WPARAM) iItem, (LPARAM) szName); if (!_tcsncmp(szName, _T("default"), CONTAINER_NAMELEN) || !_tcsncmp(szName, CTranslator::get(CTranslator::GEN_DEFAULT_CONTAINER_NAME), CONTAINER_NAMELEN)) MessageBox(hwndDlg, CTranslator::get(CTranslator::CNT_SELECT_RENAMEERROR), _T("Error"), MB_OK | MB_ICONERROR); else { int iIndex = SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETITEMDATA, (WPARAM)iItem, 0); RenameContainer(iIndex, szNewName); SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_RESETCONTENT, 0, 0); while (pCurrent) { if (!_tcsncmp(pCurrent->szName, szName, CONTAINER_NAMELEN) && lstrlen(pCurrent->szName) == lstrlen(szName)) { _tcsncpy(pCurrent->szName, szNewName, CONTAINER_NAMELEN); SendMessage(pCurrent->hwnd, DM_CONFIGURECONTAINER, 0, 0); } pCurrent = pCurrent->pNextContainer; } SendMessage(hwndDlg, DM_SC_BUILDLIST, 0, 0); BuildContainerMenu(); } } } break; } case IDC_CREATENEW: { int iLen, iItem; TCHAR szNewName[CONTAINER_NAMELEN], szName[CONTAINER_NAMELEN + 1]; iLen = GetWindowTextLength(GetDlgItem(hwndDlg, IDC_NEWCONTAINER)); if (iLen) { GetWindowText(GetDlgItem(hwndDlg, IDC_NEWCONTAINER), szNewName, CONTAINER_NAMELEN); iItem = SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_FINDSTRING, (WPARAM) - 1, (LPARAM) szNewName); if (iItem != LB_ERR || !_tcsncmp(szNewName, CGlobals::m_default_container_name, CONTAINER_NAMELEN)) { SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_GETTEXT, (WPARAM)iItem, (LPARAM)szName); if (lstrlen(szName) == lstrlen(szNewName) || !_tcsncmp(szNewName, CGlobals::m_default_container_name, CONTAINER_NAMELEN)) { MessageBox(0, CTranslator::get(CTranslator::CNT_SELECT_INUSE), _T("Error"), MB_OK | MB_ICONERROR); SetFocus(GetDlgItem(hwndDlg, IDC_NEWCONTAINER)); break; } } if (IsWindow(hwndMsgDlg)) { SendMessage(hwndMsgDlg, DM_CONTAINERSELECTED, 0, (LPARAM) szNewName); if (IsWindow(hwndDlg)) DestroyWindow(hwndDlg); } } break; } case IDC_CNTLIST: if (HIWORD(wParam) == LBN_DBLCLK) SendMessage(hwndDlg, WM_COMMAND, IDOK, 0); break; } break; /* * fill the list box... */ case DM_SC_BUILDLIST: { DBVARIANT dbv; int iCounter = 0, iItemNew; char *szKey = "TAB_ContainersW"; char szValue[10]; struct TContainerData *pContainer = 0; do { _snprintf(szValue, 8, "%d", iCounter); if (M->GetTString(NULL, szKey, szValue, &dbv)) break; // end of list if (dbv.type == DBVT_ASCIIZ || dbv.type == DBVT_WCHAR) { if (_tcsncmp(dbv.ptszVal, _T("**free**"), CONTAINER_NAMELEN)) { iItemNew = SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_ADDSTRING, 0, (LPARAM)(!_tcscmp(dbv.ptszVal, _T("default")) ? CTranslator::get(CTranslator::GEN_DEFAULT_CONTAINER_NAME) : dbv.ptszVal)); if (iItemNew != LB_ERR) SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_SETITEMDATA, (WPARAM)iItemNew, (LPARAM)iCounter); } DBFreeVariant(&dbv); } } while (++iCounter); /* * highlight the name of the container to which the message window currently is assigned */ SendMessage(hwndMsgDlg, DM_QUERYCONTAINER, 0, (LPARAM)&pContainer); if (pContainer) { LRESULT iItem; iItem = SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_FINDSTRING, (WPARAM) - 1, (LPARAM)(!_tcscmp(pContainer->szName, _T("default")) ? CTranslator::get(CTranslator::GEN_DEFAULT_CONTAINER_NAME) : pContainer->szName)); if (iItem != LB_ERR) SendDlgItemMessage(hwndDlg, IDC_CNTLIST, LB_SETCURSEL, (WPARAM) iItem, 0); } } break; } return FALSE; }
static BOOL CALLBACK ConsoleProc(HWND hDlg,UINT Msg,WPARAM wParam,LPARAM lParam) { switch(Msg) { case SERMSG_CREATE: { SIOPCB * work; void * DefWndProc; HWND hConsole; hConsole = GetDlgItem(hDlg, IDC_CONSOLE); /* テキストボックスのWndProcにフックをかける */ DefWndProc = (void *)GetWindowLong(hConsole,GWL_WNDPROC); SetWindowLong(hConsole, GWL_USERDATA, (LONG) DefWndProc); work = (SIOPCB *)lParam; SetWindowLong(hDlg,GWL_USERDATA,lParam); SetWindowLong(hConsole, GWL_WNDPROC, (long)KeyEventTrapper); SetTimer(hDlg, 100, 300, NULL); ShowWindow(hDlg,SW_SHOWNA); break; } case WM_DESTROY: { SIOPCB * scope; KillTimer(hDlg, 100); scope = (SIOPCB *)GetWindowLong(hDlg,GWL_USERDATA); if(scope != 0) scope->Handle = NULL; break; } case WM_CLOSE: /* ユーザによるウィンドウクローズを抑止 */ break; case WM_CHAR: { SIOPCB * scope; scope = (SIOPCB *)GetWindowLong(hDlg,GWL_USERDATA); if(scope != 0) { scope->ReceiveBuffer = (char)wParam; BITSET(scope->Flag, SIO_STA_INTRCV); HALInterruptRequest(INHNO_SERIAL); } break; } case WM_SETFONT: return TRUE; case WM_INITDIALOG: case WM_SIZE: { RECT client; GetClientRect(hDlg,&client); MoveWindow(GetDlgItem(hDlg,IDC_CONSOLE),0,0,client.right,client.bottom,TRUE); break; } case WM_COMMAND: return ConsoleCommandHandler(hDlg, LOWORD(wParam), HIWORD(wParam), lParam); //一定時間たったら改行がこなくても出力する case WM_TIMER: if(wParam == 100) { SIOPCB * scope; struct tagSerialConsoleParameters * param; scope = (SIOPCB *)GetWindowLong(hDlg, GWL_USERDATA); if(scope != 0) { param = (struct tagSerialConsoleParameters *)scope->versatile; if(param->position == 0) break; lParam = TRUE; } else break; //まだ初期化が終わってないので何もしない } //lParam : 送信が終わった後に割込みをかけるかどうか (FALSE:かけない TRUE:かける) case SERMSG_UPDATE: { LRESULT result; int textlength; HANDLE console; SIOPCB * scope; struct tagSerialConsoleParameters * param; scope = (SIOPCB *)GetWindowLong(hDlg, GWL_USERDATA); if(scope != 0) { param = (struct tagSerialConsoleParameters *)scope->versatile; console = GetDlgItem(hDlg, IDC_CONSOLE); textlength = GetWindowTextLength(console); if(textlength > BUFSZ_UPPERBOUND) { /* 古い情報を消す */ SendMessage(console,EM_SETSEL,0,textlength - BUFSZ_LOWERBOUND); SendMessage(console,EM_REPLACESEL,(WPARAM)FALSE,(LPARAM)""); textlength = GetWindowTextLength(console); } /* 末尾に文字を置く */ result = SendMessage(console,EM_SETSEL,textlength,textlength); EnterCriticalSection(¶m->cs); param->buffer[param->position] = '\x0'; result = SendMessage(console,EM_REPLACESEL,(WPARAM)FALSE,(LPARAM)param->buffer); param->position = 0; LeaveCriticalSection(¶m->cs); if(lParam == TRUE) { BITSET(scope->Flag, SIO_STA_INTSND); HALInterruptRequest(INHNO_SERIAL); } } else PostMessage(hDlg, Msg, wParam, lParam); //まだ初期化が終わってないので末尾につけなおす break; } default: return FALSE; } return TRUE; }
////////////////////////////////////////////////////////////////////////////// // This function is based on Daniel Lohmann's article "CEditLog - fast logging // into an edit control with cout" at http://www.codeproject.com void CLogEditCtrl::AddLine(LPCTSTR pszMsg, int iLen) { int iMsgLen = (iLen == -1) ? _tcslen(pszMsg) : iLen; if (iMsgLen == 0) return; #ifdef _DEBUG if (pszMsg[iMsgLen - 1] == _T('\n')) ASSERT( iMsgLen >= 2 && pszMsg[iMsgLen - 2] == _T('\r') ); #endif // Get Edit contents dimensions and cursor position int iStartChar, iEndChar; GetSel(iStartChar, iEndChar); int iWndTxtLen = GetWindowTextLength(); if (iStartChar == iWndTxtLen && iWndTxtLen == iEndChar) { // The cursor resides at the end of text SCROLLINFO si; si.cbSize = sizeof si; si.fMask = SIF_ALL; if (m_bAutoScroll && GetScrollInfo(SB_VERT, &si) && si.nPos >= (int)(si.nMax - si.nPage + 1)) { // Not scrolled away SafeAddLine(iWndTxtLen, iMsgLen, pszMsg, iStartChar, iEndChar); if (m_bAutoScroll && !IsWindowVisible()) ScrollToLastLine(); } else { // Reduce flicker by ignoring WM_PAINT m_bNoPaint = true; BOOL bIsVisible = IsWindowVisible(); if (bIsVisible) SetRedraw(FALSE); // Remember where we are int nFirstLine = !m_bAutoScroll ? GetFirstVisibleLine() : 0; // Select at the end of text and replace the selection // This is a very fast way to add text to an edit control SafeAddLine(iWndTxtLen, iMsgLen, pszMsg, iStartChar, iEndChar); SetSel(iStartChar, iEndChar, TRUE); // Restore our previous selection if (!m_bAutoScroll) LineScroll(nFirstLine - GetFirstVisibleLine()); else ScrollToLastLine(); m_bNoPaint = false; if (bIsVisible){ SetRedraw(); if (m_bRichEdit) Invalidate(); } } } else { // We should add the text anyway... // Reduce flicker by ignoring WM_PAINT m_bNoPaint = true; BOOL bIsVisible = IsWindowVisible(); if (bIsVisible) SetRedraw(FALSE); // Remember where we are int nFirstLine = !m_bAutoScroll ? GetFirstVisibleLine() : 0; if (iStartChar != iEndChar) { // If we are currently selecting some text, we have to find out // if the caret is near the beginning of this block or near the end. // Note that this does not always work. Because of the EM_CHARFROMPOS // message returning only 16 bits this will fail if the user has selected // a block with a length dividable by 64k. // NOTE: This may cause a lot of terrible CRASHES within the RichEdit control when used for a RichEdit control!? // To reproduce the crash: click in the RE control while it's drawing a line an start a selection! if (!m_bRichEdit){ CPoint pt; ::GetCaretPos(&pt); int nCaretPos = CharFromPos(pt); if (abs((iStartChar % 0xffff - nCaretPos)) < abs((iEndChar % 0xffff - nCaretPos))) { nCaretPos = iStartChar; iStartChar = iEndChar; iEndChar = nCaretPos; } } } // Note: This will flicker, if someone has a good idea how to prevent this - let me know // Select at the end of text and replace the selection // This is a very fast way to add text to an edit control SafeAddLine(iWndTxtLen, iMsgLen, pszMsg, iStartChar, iEndChar); SetSel(iStartChar, iEndChar, TRUE); // Restore our previous selection if (!m_bAutoScroll) LineScroll(nFirstLine - GetFirstVisibleLine()); else ScrollToLastLine(); m_bNoPaint = false; if (bIsVisible){ SetRedraw(); if (m_bRichEdit) Invalidate(); } } }
//-------------------------------------------------------------------------- // WindowProc() -> Processa as mensagens enviadas para o programa //-------------------------------------------------------------------------- LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { // Variáveis para manipulação da parte gráfica do programa HDC hDC = NULL; PAINTSTRUCT psPaint; // Identificador do arquivo static HANDLE hFile = NULL; // Identificador da caixa de texto e do botão static HWND hWndTexto = NULL; static HWND hWndBotao = NULL; // Verifica qual foi a mensagem enviada switch(uMsg) { case WM_CREATE: // Janela foi criada { // Retorna 0, significando que a mensagem foi processada corretamente return(0); } break; case WM_PAINT: // Janela (ou parte dela) precisa ser atualizada { /* Devemos avisar manualmente ao Windows que a janela já foi atualizada, pois não é um processo automático. Se isso não for feito, o Windows não irá parar de enviar a mensagem WM_PAINT ao programa. */ // O código abaixo avisa o Windows que a janela já foi atualizada. hDC = BeginPaint(hWnd, &psPaint); EndPaint(hWnd, &psPaint); return(0); } break; case WM_CLOSE: // Janela foi fechada { // Destrói a janela DestroyWindow(hWnd); return(0); } break; case WM_DESTROY: // Janela foi destruída { // Se arquivo está aberto, fecha antes de sair if(hFile) CloseHandle(hFile); // Destrói caixa de texto e botão if(hWndTexto) DestroyWindow(hWndTexto); if(hWndBotao) DestroyWindow(hWndBotao); // Envia mensagem WM_QUIT para o loop de mensagens PostQuitMessage(WM_QUIT); return(0); } break; case WM_SIZE: { // Muda tamanho da caixa de texto conforme o tamanho da área cliente MoveWindow(hWndTexto, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE); return(0); } break; case WM_COMMAND: // Item do menu, tecla de atalho ou controle ativado { // Verifica bit menos significativo de wParam (ID’s) switch(LOWORD(wParam)) { case IDM_ABRIR: { // Se arquivo ainda não foi aberto if(hFile == NULL) { // Abre/cria arquivo hFile = CreateFile("dados.txt", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // Verifica se identificador do arquivo é válido if(hFile == INVALID_HANDLE_VALUE) MessageBox(hWnd, "Erro ao abrir/criar arquivo.", "Erro!", MB_ICONERROR | MB_OK); else // Arquivo é válido { MessageBox(hWnd, "Arquivo aberto/criado.", "Aviso!", MB_ICONINFORMATION | MB_OK); SendMessage(hWnd, WM_SETTEXT, (WPARAM)0, (LPARAM)"Arquivo aberto/criado."); // Cria botões para usuário selecionar opção hWndBotao = CreateWindowEx(WS_EX_CLIENTEDGE, "BUTTON", "Clique aqui!", WS_CHILD | WS_VISIBLE, 10, 10, 100, 30, hWnd, (HMENU)IDC_BOTAO, NULL, NULL); } } } break; case IDM_SALVAR: { if(hFile != INVALID_HANDLE_VALUE) // Arquivo está aberto { // Obtém quantidade de caracteres da caixa de texto int tam = GetWindowTextLength(hWndTexto); // Obtém conteúdo da caixa de texto, alocando memória para os dados // (alocação no modo Windows) LPSTR lpstrBuffer = (LPSTR)GlobalAlloc(GPTR, tam + 1); GetWindowText(hWndTexto, lpstrBuffer, tam + 1); // Armazena quantos bytes foram escritos no arquivo DWORD dwBytesEscritos; // Modifica posição do arquivo para o início SetFilePointer(hFile, NULL, NULL, FILE_BEGIN); // Grava conteúdo da caixa de texto no arquivo WriteFile(hFile, lpstrBuffer, tam, &dwBytesEscritos, NULL); // Define fim do arquivo SetEndOfFile(hFile); // Libera memória dos dados GlobalFree(lpstrBuffer); MessageBox(hWnd, "Conteúdo escrito no arquivo.", "Aviso!", MB_ICONINFORMATION | MB_OK); } else // Arquivo não foi aberto MessageBox(hWnd, "Erro ao escrever no arquivo.", "Erro!", MB_ICONERROR | MB_OK); } break; case IDM_FECHAR: { // Se o arquivo está aberto, fecha if(hFile) { CloseHandle(hFile); hFile = NULL; MessageBox(hWnd, "Arquivo fechado.", "Aviso", MB_ICONINFORMATION | MB_OK); } // Destrói caixa de texto e botão if(hWndTexto) { DestroyWindow(hWndTexto); hWndTexto = NULL; } if(hWndBotao) { DestroyWindow(hWndBotao); hWndBotao = NULL; } } break; case IDM_EXCLUIR: { // Tenta excluir arquivo e mostra resultado para usuário if(DeleteFile("dados.txt")) MessageBox(hWnd, "Arquivo excluído.", "Aviso!", MB_ICONINFORMATION | MB_OK); else MessageBox(hWnd, "Arquivo não pode ser excluído.", "Erro!", MB_ICONERROR | MB_OK); } break; case IDM_SAIR: { // Destrói a janela DestroyWindow(hWnd); } break; case IDC_BOTAO: { // Destrói botão if(hWndBotao) { DestroyWindow(hWndBotao); hWndBotao = NULL; } // Cria caixa de texto para o usuário entrar com os dados hWndTexto = CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL, 0, 0, 312, 194, hWnd, NULL, NULL, NULL); if(hFile != INVALID_HANDLE_VALUE) // Arquivo está aberto { // Obtém tamanho do arquivo int tam = GetFileSize(hFile, NULL); // Obtém conteúdo do arquivo, alocando memória para os dados // (alocação no modo Windows) LPSTR lpstrBuffer = (LPSTR)GlobalAlloc(GPTR, tam + 1); // Armazena quantos bytes foram escritos no arquivo DWORD dwBytesEscritos; // Lê conteúdo do arquivo ReadFile(hFile, lpstrBuffer, tam, &dwBytesEscritos, NULL); // Coloca conteúdo do arquivo na caixa de texto SetWindowText(hWndTexto, lpstrBuffer); // Libera memória dos dados GlobalFree(lpstrBuffer); MessageBox(hWnd, "Conteúdo lido do arquivo.", "Aviso!", MB_ICONINFORMATION | MB_OK); // Define cursor na caixa de texto SetFocus(hWndTexto); } else // Arquivo não foi aberto MessageBox(hWnd, "Erro ao ler o arquivo.", "Erro!", MB_ICONERROR | MB_OK); } break; } return(0); } break; default: // Outra mensagem { /* Deixa o Windows processar as mensagens que não foram verificadas na função */ return(DefWindowProc(hWnd, uMsg, wParam, lParam)); } break; } }
void CHexEdit::OnContextMenu(CWnd* pWnd, CPoint point) { int start,end; GetSel(start,end); CString text; this->GetWindowText(text); char head=0,second=0; bool bCut=true; SetFocus(); CMenu menu; menu.CreatePopupMenu(); //No problems with default undo BOOL bReadOnly = GetStyle() & ES_READONLY; DWORD flags = CanUndo() && !bReadOnly ? 0 : MF_GRAYED; menu.InsertMenu(0, MF_BYPOSITION | flags, EM_UNDO, MES_UNDO); menu.InsertMenu(1, MF_BYPOSITION | MF_SEPARATOR); //No problem with default Copy DWORD sel = GetSel(); flags = LOWORD(sel) == HIWORD(sel) ? MF_GRAYED : 0; menu.InsertMenu(2, MF_BYPOSITION | flags, WM_COPY, MES_COPY); //Cut and delete should be modified if(text.GetLength()>0) head=text.GetAt(0); if(text.GetLength()>1) second=text.GetAt(1); if(second=='X'||second=='x'){ //does not allow cut first char if(start==0&&end==1) bCut=false; } flags = (flags == MF_GRAYED || bReadOnly||!bCut) ? MF_GRAYED : 0; menu.InsertMenu(2, MF_BYPOSITION | flags, WM_CUT, MES_CUT); menu.InsertMenu(4, MF_BYPOSITION | flags, WM_CLEAR, MES_DELETE); //Paste should be modified flags = IsClipboardFormatAvailable(CF_TEXT) && !bReadOnly ? 0 : MF_GRAYED; if(!this->OpenClipboard()) ::AfxMessageBox("Cannot open clipboard!"); HGLOBAL hglb; LPTSTR lptstr; hglb=GetClipboardData(CF_TEXT); if (hglb != NULL) { lptstr =(LPTSTR) GlobalLock(hglb); //Check invalid hex string if(!this->IsHexConvertableText(lptstr)) { flags=MF_GRAYED; } } CloseClipboard(); menu.InsertMenu(4, MF_BYPOSITION | flags, WM_PASTE, MES_PASTE); menu.InsertMenu(6, MF_BYPOSITION | MF_SEPARATOR); //No problem with default Sel All int len = GetWindowTextLength(); flags = (!len || (LOWORD(sel) == 0 && HIWORD(sel) == len)) ? MF_GRAYED : 0; menu.InsertMenu(7, MF_BYPOSITION | flags, ME_SELECTALL, MES_SELECTALL); flags=0; if(text.GetLength()==0||(text.GetLength()==2&&text.Find("0x")==0)) flags=MF_GRAYED; menu.InsertMenu(8, MF_BYPOSITION | MF_SEPARATOR); menu.InsertMenu(9, MF_BYPOSITION | flags, ME_CONVERT, MES_CONVERT); menu.TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, point.x, point.y, this); }
/* Main Dialog */ BOOL CALLBACK DlgProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { int ret_code = 0; switch(Message) { case WM_INITDIALOG: { int statwidths[] = {130, -1}; HMENU hMenu, hSubMenu; UINT menuflags = MF_STRING; if(config_inst.admin_access == 0) { menuflags = MF_STRING|MF_GRAYED; } hMenu = CreateMenu(); /* Creating management menu */ hSubMenu = CreatePopupMenu(); AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_START,"&Start OSSEC"); AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_STOP,"&Stop OSSEC"); AppendMenu(hSubMenu, MF_SEPARATOR, UI_MENU_NONE,""); AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_RESTART,"&Restart"); AppendMenu(hSubMenu, menuflags, UI_MENU_MANAGE_STATUS,"&Status"); AppendMenu(hSubMenu, MF_SEPARATOR, UI_MENU_NONE,""); AppendMenu(hSubMenu, MF_STRING,UI_MENU_MANAGE_EXIT,"&Exit"); AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu,"&Manage"); /* Create view menu */ hSubMenu = CreatePopupMenu(); AppendMenu(hSubMenu, MF_STRING, UI_MENU_VIEW_LOGS, "&View Logs"); AppendMenu(hSubMenu, MF_STRING, UI_MENU_VIEW_CONFIG,"V&iew Config"); AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu,"&View"); hSubMenu = CreatePopupMenu(); AppendMenu(hSubMenu, MF_STRING, UI_MENU_HELP_ABOUT, "A&bout"); AppendMenu(hSubMenu, MF_STRING, UI_MENU_HELP_HELP, "Help"); AppendMenu(hMenu, MF_STRING | MF_POPUP, (UINT)hSubMenu, "&Help"); AppendMenu(hMenu, MF_SEPARATOR, 0, NULL); SetMenu(hwnd, hMenu); hStatus = CreateWindowEx(0, STATUSCLASSNAME, NULL, WS_CHILD|WS_VISIBLE|SBARS_SIZEGRIP, 0, 0, 0, 0, hwnd, (HMENU)IDC_MAIN_STATUS, GetModuleHandle(NULL), NULL); SendMessage(hStatus, SB_SETPARTS, sizeof(statwidths)/sizeof(int), (LPARAM)statwidths); SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"http://www.ossec.net"); /* Initializing config */ config_read(hwnd); gen_server_info(hwnd); /* Setting the icons */ SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_OSSECICON))); SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)LoadIcon(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_OSSECICON))); if(config_inst.admin_access == 0) { MessageBox(hwnd, "Admin access required. Some features may not work properly. \n\n" "**If on Vista (or Server 2008), choose the \"Run as administrator\" option.", "Admin access required.", MB_OK); break; } } break; case WM_COMMAND: switch(LOWORD(wParam)) { /* In case of SAVE */ case IDC_ADD: { int chd = 0; int len; if(config_inst.admin_access == 0) { MessageBox(hwnd, "Unable to edit configuration. " "Admin access required.", "Error Saving.", MB_OK); break; } /** Getting values from the user (if chosen save) * We should probably create another function for it... **/ /* Getting server ip */ len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_TEXT)); if(len > 0) { char *buf; /* Allocating buffer */ buf = (char*)GlobalAlloc(GPTR, len + 1); if(!buf) { exit(-1); } GetDlgItemText(hwnd, UI_SERVER_TEXT, buf, len + 1); /* If auth key changed, set it */ if(strcmp(buf, config_inst.server) != 0) { if(set_ossec_server(buf, hwnd)) { chd = 1; } } else { GlobalFree(buf); } } /* Getting auth key */ len = GetWindowTextLength(GetDlgItem(hwnd, UI_SERVER_AUTH)); if(len > 0) { char *buf; /* Allocating buffer */ buf = (char*)GlobalAlloc(GPTR, len + 1); if(!buf) { exit(-1); } GetDlgItemText(hwnd, UI_SERVER_AUTH, buf, len + 1); /* If auth key changed, set it */ if(strcmp(buf, config_inst.key) != 0) { int ret; char *tmp_str; char *decd_buf = NULL; char *decd_to_write = NULL; char *id = NULL; char *name = NULL; char *ip = NULL; /* Getting new fields */ decd_buf = decode_base64(buf); if(decd_buf) { decd_to_write = strdup(decd_buf); /* Getting id, name and ip */ id = decd_buf; name = strchr(id, ' '); if(name) { *name = '\0'; name++; ip = strchr(name, ' '); if(ip) { *ip = '\0'; ip++; tmp_str = strchr(ip, ' '); if(tmp_str) { *tmp_str = '\0'; } } } } /* If ip isn't set, it is because we have an invalid * auth key. */ if(!ip) { MessageBox(hwnd, "Unable to import " "authentication key. Invalid.", "Error Saving.", MB_OK); } else { char mbox_msg[1024 +1]; mbox_msg[1024] = '\0'; snprintf(mbox_msg, 1024, "Adding key for:\r\n\r\n" "Agent ID: %s\r\n" "Agent Name: %s\r\n" "IP Address: %s\r\n", id, name, ip); ret = MessageBox(hwnd, mbox_msg, "Confirm Importing Key", MB_OKCANCEL); if(ret == IDOK) { FILE *fp; fp = fopen(AUTH_FILE, "w"); if(fp) { chd+=2; fprintf(fp, "%s", decd_to_write); fclose(fp); } } } /* Free used memory */ if(decd_buf) { free(decd_to_write); free(decd_buf); } } else { GlobalFree(buf); } } /* Finished adding AUTH KEY */ /* Re-printing messages */ if(chd) { config_read(hwnd); /* Set status to restart */ if(strcmp(config_inst.status,ST_RUNNING) == 0) { config_inst.status = ST_RUNNING_RESTART; } gen_server_info(hwnd); if(chd == 1) { SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Server IP Saved .."); } else if(chd == 2) { SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Auth key imported .."); } else { SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Auth key and server ip saved .."); } } } break; case UI_MENU_MANAGE_EXIT: PostMessage(hwnd, WM_CLOSE, 0, 0); break; case UI_MENU_VIEW_LOGS: _spawnlp( _P_NOWAIT, "notepad", "notepad " OSSECLOGS, NULL ); break; case UI_MENU_VIEW_CONFIG: _spawnlp( _P_NOWAIT, "notepad", "notepad " CONFIG, NULL ); break; case UI_MENU_HELP_HELP: _spawnlp( _P_NOWAIT, "notepad", "notepad " HELPTXT, NULL ); break; case UI_MENU_HELP_ABOUT: { DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_ABOUT), hwnd, AboutDlgProc); } break; case IDC_CANCEL: config_read(hwnd); gen_server_info(hwnd); break; case UI_MENU_MANAGE_START: /* Starting OSSEC -- must have a valid config before. */ if((strcmp(config_inst.key, FL_NOKEY) != 0) && (strcmp(config_inst.server, FL_NOSERVER) != 0)) { ret_code = os_start_service(); } else { ret_code = 0; } if(ret_code == 0) { MessageBox(hwnd, "Unable to start OSSEC (check config).", "Error -- Unable to start", MB_OK); } else if(ret_code == 1) { config_read(hwnd); gen_server_info(hwnd); SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Started.."); MessageBox(hwnd, "OSSEC Agent Started.", "Started..", MB_OK); } else { MessageBox(hwnd, "Agent already running (try restart).", "Already running..", MB_OK); } break; case UI_MENU_MANAGE_STOP: /* Stopping OSSEC */ ret_code = os_stop_service(); if(ret_code == 1) { config_read(hwnd); gen_server_info(hwnd); SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Stopped.."); MessageBox(hwnd, "OSSEC Agent Stopped.", "Stopped..", MB_OK); } else { MessageBox(hwnd, "Agent already stopped.", "Already stopped..", MB_OK); } break; case UI_MENU_MANAGE_STATUS: if(CheckServiceRunning()) { MessageBox(hwnd, "OSSEC Agent running.", "Agent running..", MB_OK); } else { MessageBox(hwnd, "OSSEC Agent stopped.", "Agent stopped.", MB_OK); } break; case UI_MENU_MANAGE_RESTART: if((strcmp(config_inst.key, FL_NOKEY) == 0) || (strcmp(config_inst.server, FL_NOSERVER) == 0)) { MessageBox(hwnd, "Unable to restart OSSEC (check config).", "Error -- Unable to restart", MB_OK); break; } ret_code = os_stop_service(); /* Starting OSSEC */ ret_code = os_start_service(); if(ret_code == 0) { MessageBox(hwnd, "Unable to restart OSSEC (check config).", "Error -- Unable to restart", MB_OK); } else { config_read(hwnd); gen_server_info(hwnd); SendMessage(hStatus, SB_SETTEXT, 0, (LPARAM)"Restarted.."); MessageBox(hwnd, "OSSEC Agent Restarted.", "Restarted..", MB_OK); } break; } break; case WM_CLOSE: EndDialog(hwnd, 0); break; default: return FALSE; } return TRUE; }
LRESULT CALLBACK MainWindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { // Initialize our window and create our child controls. case WM_CREATE: { hwnd = hWnd; HWND hWndChild; CenterWindow(hWnd, NULL); // Create the info text at the the top. hWndChild = CreateWindowEx(0, WC_STATIC, TEXT("RakSAMP " RAKSAMP_VERSION), SS_LEFT | WS_CHILD | WS_VISIBLE, 0, 0, 0, 0, hWnd, (HMENU)(IDC_LBLINFO), g_hInst, NULL); if(!hWndChild) return -1; SendMessage(hWndChild, WM_SETFONT, (WPARAM)g_hfText, FALSE); texthwnd = hWndChild; // Create the custom/owner drawn listbox hWndChild = CreateWindowEx(WS_EX_CLIENTEDGE, WC_LISTBOX, NULL, LBS_NOINTEGRALHEIGHT | LBS_OWNERDRAWFIXED | LBS_EXTENDEDSEL | WS_VSCROLL | WS_CHILD | WS_TABSTOP | WS_VISIBLE, 0, 0, 0, 0, hWnd, (HMENU)(IDC_LSTCUSTOM), g_hInst, NULL); if(!hWndChild) return -1; SendMessage(hWndChild, WM_SETFONT, (WPARAM)g_hfText, FALSE); loghwnd = hWndChild; // Create the input box. hWndChild = CreateWindowEx(0, WC_EDIT, NULL, WS_CHILD | WS_TABSTOP | WS_VISIBLE | WS_BORDER, 0, 0, 0, 0, hWnd, (HMENU)IDC_INPUTBOX, g_hInst, NULL); if(!hWndChild) return -1; SendMessage(hWndChild, WM_SETFONT, (WPARAM)g_hfText, FALSE); inputhwnd = hWndChild; // Create the send button. hWndChild = CreateWindowEx(0, WC_BUTTON, TEXT("&Send"), BS_DEFPUSHBUTTON | BS_TEXT | WS_CHILD | WS_TABSTOP | WS_VISIBLE, 0, 0, 0, 0, hWnd, (HMENU)IDCANCEL, g_hInst, NULL); if(!hWndChild) return -1; SendMessage(hWndChild, WM_SETFONT, (WPARAM)g_hfText, FALSE); HICON hIcon = LoadIcon(g_hInst, MAKEINTRESOURCE(IDI_MAIN)); SendMessage(hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon); SendMessage(hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon); SetFocus(inputhwnd); } return 0; // This message is sent for each owner drawn child and only once for LBS_OWNERDRAWFIXED. // If we had used LBS_OWNERDRAWVARIABLE it is sent for each item. case WM_MEASUREITEM: { LPMEASUREITEMSTRUCT lpMeasureItem = (LPMEASUREITEMSTRUCT)lParam; // Is this measure request for our control? if(lpMeasureItem->CtlID == IDC_LSTCUSTOM) { TEXTMETRIC tm; HWND hWndItem = GetDlgItem(hWnd, IDC_LSTCUSTOM); HDC hdcItem = GetDC(hWndItem); if(GetTextMetrics(hdcItem, &tm)) // Set the item height to that of the font + 10px padding lpMeasureItem->itemHeight = tm.tmInternalLeading + tm.tmHeight + tm.tmExternalLeading + 10; ReleaseDC(hWndItem, hdcItem); return TRUE; } } break; // This message is sent for each owner drawn child when it needs to be rendered. case WM_DRAWITEM: { LPDRAWITEMSTRUCT lpDrawItem = (LPDRAWITEMSTRUCT)lParam; // Is this draw request for our control? if(lpDrawItem->CtlID == IDC_LSTCUSTOM) { // Get the text pointer LPTSTR lpText = (LPTSTR)lpDrawItem->itemData; COLORREF textColor = RGB(0, 0, 0); COLORREF bkColor = RGB(255, 255, 255); if(!strncmp(lpText, "[CHAT] ", 7)) textColor = RGB(settings.bChatColorRed, settings.bChatColorGreen, settings.bChatColorBlue); if(!strncmp(lpText, "[CMSG] ", 7)) textColor = RGB(settings.bCMsgRed, settings.bCMsgGreen, settings.bCMsgBlue); if(settings.iFind) { for(int i = 0; i < MAX_FIND_ITEMS; i++) { if(!settings.findItems[i].iExists) continue; if(strstr(lpText, settings.findItems[i].szFind)) { textColor = RGB(settings.findItems[i].bTextRed, settings.findItems[i].bTextGreen, settings.findItems[i].bTextBlue); bkColor = RGB(settings.findItems[i].bBkRed, settings.findItems[i].bBkGreen, settings.findItems[i].bBkBlue); } } } // Set colors based on selected state if(lpDrawItem->itemState & ODS_SELECTED) { SetBkColor(lpDrawItem->hDC, RGB(230, 255, 255)); SetTextColor(lpDrawItem->hDC, textColor); } else { SetBkColor(lpDrawItem->hDC, bkColor); SetTextColor(lpDrawItem->hDC, textColor); } // Draw the text and fill in the background at the same time // with 5px offset for padding ExtTextOut(lpDrawItem->hDC, lpDrawItem->rcItem.left + 5, lpDrawItem->rcItem.top + 5, ETO_OPAQUE | ETO_CLIPPED, &lpDrawItem->rcItem, lpText, lstrlen(lpText), NULL); // If this item has the focus add the focus rect if(lpDrawItem->itemState & ODS_FOCUS) DrawFocusRect(lpDrawItem->hDC, &lpDrawItem->rcItem); return TRUE; } } break; // This message is sent for each item deleted from an owner drawn control so that // you can perform custom clean up. case WM_DELETEITEM: { LPDELETEITEMSTRUCT lpDeleteItem = (LPDELETEITEMSTRUCT)lParam; // Is this delete request for our control? if(lpDeleteItem->CtlID == IDC_LSTCUSTOM) { delete (LPTSTR)lpDeleteItem->itemData; return TRUE; } } break; // We accept this message so we can set a minimum window size. This only sets the users // tracking size. The window itself can always be resized smaller programmatically unless // you restrict it in WM_WINDOWPOSCHANGING/WM_WINDOWPOSCHANGED. case WM_GETMINMAXINFO: { LPMINMAXINFO lpInfo = (LPMINMAXINFO)lParam; if(lpInfo) lpInfo->ptMinTrackSize.x = 250, lpInfo->ptMinTrackSize.y = 300; } return 0; // These next two messages are better to use rather than WM_MOVE/WM_SIZE. // Remember WM_MOVE/WM_SIZE are from 16bit windows. In 32bit windows the window // manager only sends these two messages and the DefWindowProc() handler actually // accepts them and converts them to WM_MOVE/WM_SIZE. // // We accept this so we can scale our controls to the client size. case WM_WINDOWPOSCHANGING: case WM_WINDOWPOSCHANGED: { HDWP hDWP; RECT rc; // Create a deferred window handle. if(hDWP = BeginDeferWindowPos(4)) { // Deferring 4 child controls GetClientRect(hWnd, &rc); // Calculate the size needed for the static text at the top RECT rcText = { 10, 10, rc.right - 20, 0 } ; CalcWindowTextSize(GetDlgItem(hWnd, IDC_LBLINFO), &rcText); // Defer each window move/size until end and do them all at once. hDWP = DeferWindowPos(hDWP, GetDlgItem(hWnd, IDC_LBLINFO), NULL, 10, 10, rc.right - 20, rcText.bottom, SWP_NOZORDER | SWP_NOREDRAW); // Move/Size the listbox hDWP = DeferWindowPos(hDWP, GetDlgItem(hWnd, IDC_LSTCUSTOM), NULL, 10, rcText.bottom + 20, rc.right - 20, rc.bottom - rcText.bottom - 75, SWP_NOZORDER | SWP_NOREDRAW); // Move/Size the input box hDWP = DeferWindowPos(hDWP, GetDlgItem(hWnd, IDC_INPUTBOX), NULL, 10, rc.bottom - 40, rc.right - 90, 30, SWP_NOZORDER | SWP_NOREDRAW); // Move/Size the send button hDWP = DeferWindowPos(hDWP, GetDlgItem(hWnd, IDCANCEL), NULL, (rc.right) - 70, rc.bottom - 40, 60, 30, SWP_NOZORDER | SWP_NOREDRAW); // Resize all windows under the deferred window handled at the same time. EndDeferWindowPos(hDWP); // We told DeferWindowPos not to redraw the controls so we can redraw // them here all at once. RedrawWindow(hWnd, NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN | RDW_ERASE | RDW_NOFRAME | RDW_UPDATENOW); } } return 0; // Handle the notifications of button presses. case WM_COMMAND: // If it was a button press and it came from our button. if(wParam == MAKELONG(IDCANCEL, BN_CLICKED) || (GetFocus() == inputhwnd) && (0x8000 & GetKeyState(VK_RETURN))) { // process typed command if(GetWindowTextLength(inputhwnd) == 0) break; char str[512]; SendMessage(inputhwnd, WM_GETTEXT, (WPARAM)512, (LPARAM)str); SendMessage(inputhwnd, WM_SETTEXT, 0, (LPARAM)""); RunCommand(str, 0); SetFocus(inputhwnd); } else if(HIWORD(wParam) == LBN_DBLCLK) { } break; case WM_DESTROY: // We post a WM_QUIT when our window is destroyed so we break the main message loop. sampDisconnect(0); PostQuitMessage(0); break; } // Not a message we wanted? No problem hand it over to the Default Window Procedure. return DefWindowProc(hWnd, uMsg, wParam, lParam); }
void PrintWindowSettings( FILE * fp ) { int ret ; RECT r ; char buffer[MAX_VALUE_NAME] ; GetOSInfo( buffer ) ; fprintf( fp, "OSVersion=%s\n", buffer ) ; ret = GetWindowText( MainHwnd, buffer, MAX_VALUE_NAME ) ; buffer[ret]='\0'; ret = GetWindowTextLength( MainHwnd ) ; fprintf( fp, "Title (length)=%s (%d)\n", buffer, ret ) ; if( GetWindowRect( MainHwnd, &r ) ) { fprintf( fp, "WindowRect.left=%ld\n", r.left ) ; fprintf( fp, "WindowRect.right=%ld\n", r.right ) ; fprintf( fp, "WindowRect.top=%ld\n", r.top ) ; fprintf( fp, "WindowRect.bottom=%ld\n", r.bottom ) ; } if( GetClientRect( MainHwnd, &r ) ) { fprintf( fp, "ClientRect.left=%ld\n", r.left ) ; fprintf( fp, "ClientRect.right=%ld\n", r.right ) ; fprintf( fp, "ClientRect.top=%ld\n", r.top ) ; fprintf( fp, "ClientRect.bottom=%ld\n", r.bottom ) ; } ret = GetWindowModuleFileName( MainHwnd, buffer, MAX_VALUE_NAME ) ; buffer[ret]='\0'; fprintf( fp, "WindowModuleFileName=%s\n", buffer ) ; WINDOWINFO wi ; wi.cbSize = sizeof( WINDOWINFO ) ; if( GetWindowInfo( MainHwnd, &wi ) ) { fprintf( fp, "WindowInfo.cbSize=%lu\n", wi.cbSize ) ; fprintf( fp, "WindowInfo.rcWindow.left=%ld\n", wi.rcWindow.left ) ; fprintf( fp, "WindowInfo.rcWindow.right=%ld\n", wi.rcWindow.right ) ; fprintf( fp, "WindowInfo.rcWindow.top=%ld\n", wi.rcWindow.top ) ; fprintf( fp, "WindowInfo.rcWindow.bottom=%ld\n", wi.rcWindow.bottom ) ; fprintf( fp, "WindowInfo.rcClient.left=%ld\n", wi.rcWindow.left ) ; fprintf( fp, "WindowInfo.rcClient.right=%ld\n", wi.rcWindow.right ) ; fprintf( fp, "WindowInfo.rcClient.top=%ld\n", wi.rcWindow.top ) ; fprintf( fp, "WindowInfo.rcClient.bottom=%ld\n", wi.rcWindow.bottom ) ; fprintf( fp, "WindowInfo.dwStyle=%lu\n", wi.dwStyle ) ; fprintf( fp, "WindowInfo.dwExStyle=%lu\n", wi.dwExStyle ) ; fprintf( fp, "WindowInfo.dwWindowStatus=%lu\n", wi.dwWindowStatus ) ; fprintf( fp, "WindowInfo.cxWindowBorders=%u\n", wi.cxWindowBorders ) ; fprintf( fp, "WindowInfo.cyWindowBorders=%u\n", wi.cyWindowBorders ) ; fprintf( fp, "WindowInfo.wCreatorVersion=%d\n", wi.wCreatorVersion ) ; } WINDOWPLACEMENT wp; wp.length=sizeof(WINDOWPLACEMENT) ; if( GetWindowPlacement( MainHwnd, &wp ) ) { fprintf( fp, "WindowPlacement.length=%u\n", wp.length ) ; fprintf( fp, "WindowPlacement.flags=%u\n", wp.flags ) ; fprintf( fp, "WindowPlacement.showCmd=%u\n", wp.showCmd ) ; fprintf( fp, "WindowPlacement.ptMinPosition.x=%ld\n", wp.ptMinPosition.x ) ; fprintf( fp, "WindowPlacement.ptMinPosition.y=%ld\n", wp.ptMinPosition.y ) ; fprintf( fp, "WindowPlacement.ptMaxPosition.x=%ld\n", wp.ptMaxPosition.x ) ; fprintf( fp, "WindowPlacement.ptMaxPosition.y=%ld\n", wp.ptMaxPosition.y ) ; fprintf( fp, "WindowPlacement.rcNormalPosition.left=%ld\n", wp.rcNormalPosition.left ) ; fprintf( fp, "WindowPlacement.rcNormalPosition.right=%ld\n", wp.rcNormalPosition.right ) ; fprintf( fp, "WindowPlacement.rcNormalPosition.top=%ld\n", wp.rcNormalPosition.top ) ; fprintf( fp, "WindowPlacement.rcNormalPosition.bottom=%ld\n", wp.rcNormalPosition.bottom ) ; } fprintf( fp, "IsIconic=%d\n", IsIconic( MainHwnd ) ) ; fprintf( fp, "IsWindow=%d\n", IsWindow( MainHwnd ) ) ; fprintf( fp, "IsWindowUnicode=%d\n", IsWindowUnicode( MainHwnd ) ) ; fprintf( fp, "IsWindowVisible=%d\n", IsWindowVisible( MainHwnd ) ) ; fprintf( fp, "IsZoomed=%d\n", IsZoomed( MainHwnd ) ) ; fprintf( fp, "ScaleX=%d\n", GetDeviceCaps(GetDC(MainHwnd),LOGPIXELSX) ) ; fprintf( fp, "ScaleY=%d\n", GetDeviceCaps(GetDC(MainHwnd),LOGPIXELSY) ) ; }
int WinGui::EditBox::length(){ return GetWindowTextLength(hWnd); }
int WinGui::EditBox::getText(char* to){ GetWindowText(hWnd, to, GetWindowTextLength(hWnd) + 1); return 0; }
/* * Dialog-box function for the main PuTTYgen dialog box. */ static int CALLBACK MainDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { static const char generating_msg[] = "Please wait while a key is generated..."; static const char entropy_msg[] = "Please generate some randomness by moving the mouse over the blank area."; struct MainDlgState *state; switch (msg) { case WM_INITDIALOG: if (has_help()) SetWindowLongPtr(hwnd, GWL_EXSTYLE, GetWindowLongPtr(hwnd, GWL_EXSTYLE) | WS_EX_CONTEXTHELP); else { /* * If we add a Help button, this is where we destroy it * if the help file isn't present. */ } #ifdef INTEGRATED_KEYGEN SendMessage(hwnd, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) LoadIcon(hinst, MAKEINTRESOURCE(800))); #else SendMessage(hwnd, WM_SETICON, (WPARAM) ICON_BIG, (LPARAM) LoadIcon(hinst, MAKEINTRESOURCE(200))); #endif state = snew(struct MainDlgState); state->generation_thread_exists = FALSE; state->collecting_entropy = FALSE; state->entropy = NULL; state->key_exists = FALSE; SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) state); { HMENU menu, menu1; menu = CreateMenu(); menu1 = CreateMenu(); AppendMenu(menu1, MF_ENABLED, IDC_LOAD, "&Load private key"); AppendMenu(menu1, MF_ENABLED, IDC_SAVEPUB, "Save p&ublic key"); AppendMenu(menu1, MF_ENABLED, IDC_SAVE, "&Save private key"); AppendMenu(menu1, MF_SEPARATOR, 0, 0); AppendMenu(menu1, MF_ENABLED, IDC_QUIT, "E&xit"); AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "&File"); state->filemenu = menu1; menu1 = CreateMenu(); AppendMenu(menu1, MF_ENABLED, IDC_GENERATE, "&Generate key pair"); AppendMenu(menu1, MF_SEPARATOR, 0, 0); AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH1, "SSH-&1 key (RSA)"); AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2RSA, "SSH-2 &RSA key"); AppendMenu(menu1, MF_ENABLED, IDC_KEYSSH2DSA, "SSH-2 &DSA key"); AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "&Key"); state->keymenu = menu1; menu1 = CreateMenu(); AppendMenu(menu1, MF_ENABLED, IDC_IMPORT, "&Import key"); AppendMenu(menu1, MF_SEPARATOR, 0, 0); AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_OPENSSH, "Export &OpenSSH key"); AppendMenu(menu1, MF_ENABLED, IDC_EXPORT_SSHCOM, "Export &ssh.com key"); AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "Con&versions"); state->cvtmenu = menu1; menu1 = CreateMenu(); AppendMenu(menu1, MF_ENABLED, IDC_ABOUT, "&About"); if (has_help()) AppendMenu(menu1, MF_ENABLED, IDC_GIVEHELP, "&Help"); AppendMenu(menu, MF_POPUP | MF_ENABLED, (UINT) menu1, "&Help"); SetMenu(hwnd, menu); } /* * Centre the window. */ { /* centre the window */ RECT rs, rd; HWND hw; hw = GetDesktopWindow(); if (GetWindowRect(hw, &rs) && GetWindowRect(hwnd, &rd)) MoveWindow(hwnd, (rs.right + rs.left + rd.left - rd.right) / 2, (rs.bottom + rs.top + rd.top - rd.bottom) / 2, rd.right - rd.left, rd.bottom - rd.top, TRUE); } { struct ctlpos cp, cp2; /* Accelerators used: acglops1rbd */ ctlposinit(&cp, hwnd, 4, 4, 4); beginbox(&cp, "Key", IDC_BOX_KEY); cp2 = cp; statictext(&cp2, "No key.", 1, IDC_NOKEY); cp2 = cp; statictext(&cp2, "", 1, IDC_GENERATING); progressbar(&cp2, IDC_PROGRESS); bigeditctrl(&cp, "&Public key for pasting into authorized_keys file:", IDC_PKSTATIC, IDC_KEYDISPLAY, 5); SendDlgItemMessage(hwnd, IDC_KEYDISPLAY, EM_SETREADONLY, 1, 0); staticedit(&cp, "Key f&ingerprint:", IDC_FPSTATIC, IDC_FINGERPRINT, 75); SendDlgItemMessage(hwnd, IDC_FINGERPRINT, EM_SETREADONLY, 1, 0); staticedit(&cp, "Key &comment:", IDC_COMMENTSTATIC, IDC_COMMENTEDIT, 75); staticpassedit(&cp, "Key p&assphrase:", IDC_PASSPHRASE1STATIC, IDC_PASSPHRASE1EDIT, 75); staticpassedit(&cp, "C&onfirm passphrase:", IDC_PASSPHRASE2STATIC, IDC_PASSPHRASE2EDIT, 75); endbox(&cp); beginbox(&cp, "Actions", IDC_BOX_ACTIONS); staticbtn(&cp, "Generate a public/private key pair", IDC_GENSTATIC, "&Generate", IDC_GENERATE); staticbtn(&cp, "Load an existing private key file", IDC_LOADSTATIC, "&Load", IDC_LOAD); static2btn(&cp, "Save the generated key", IDC_SAVESTATIC, "Save p&ublic key", IDC_SAVEPUB, "&Save private key", IDC_SAVE); endbox(&cp); beginbox(&cp, "Parameters", IDC_BOX_PARAMS); radioline(&cp, "Type of key to generate:", IDC_TYPESTATIC, 3, "SSH-&1 (RSA)", IDC_KEYSSH1, "SSH-2 &RSA", IDC_KEYSSH2RSA, "SSH-2 &DSA", IDC_KEYSSH2DSA, NULL); staticedit(&cp, "Number of &bits in a generated key:", IDC_BITSSTATIC, IDC_BITS, 20); endbox(&cp); } CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2DSA, IDC_KEYSSH2RSA); CheckMenuRadioItem(state->keymenu, IDC_KEYSSH1, IDC_KEYSSH2DSA, IDC_KEYSSH2RSA, MF_BYCOMMAND); SetDlgItemInt(hwnd, IDC_BITS, DEFAULT_KEYSIZE, FALSE); /* * Initially, hide the progress bar and the key display, * and show the no-key display. Also disable the Save * buttons, because with no key we obviously can't save * anything. */ ui_set_state(hwnd, state, 0); /* * Load a key file if one was provided on the command line. */ if (cmdline_keyfile) { Filename *fn = filename_from_str(cmdline_keyfile); load_key_file(hwnd, state, fn, 0); filename_free(fn); } return 1; case WM_MOUSEMOVE: state = (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); if (state->collecting_entropy && state->entropy && state->entropy_got < state->entropy_required) { state->entropy[state->entropy_got++] = lParam; state->entropy[state->entropy_got++] = GetMessageTime(); SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, state->entropy_got, 0); if (state->entropy_got >= state->entropy_required) { struct rsa_key_thread_params *params; DWORD threadid; /* * Seed the entropy pool */ random_add_heavynoise(state->entropy, state->entropy_size); smemclr(state->entropy, state->entropy_size); sfree(state->entropy); state->collecting_entropy = FALSE; SetDlgItemText(hwnd, IDC_GENERATING, generating_msg); SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, MAKELPARAM(0, PROGRESSRANGE)); SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, 0, 0); params = snew(struct rsa_key_thread_params); params->progressbar = GetDlgItem(hwnd, IDC_PROGRESS); params->dialog = hwnd; params->keysize = state->keysize; params->is_dsa = state->is_dsa; params->key = &state->key; params->dsskey = &state->dsskey; if (!CreateThread(NULL, 0, generate_rsa_key_thread, params, 0, &threadid)) { MessageBox(hwnd, "Out of thread resources", "Key generation error", MB_OK | MB_ICONERROR); sfree(params); } else { state->generation_thread_exists = TRUE; } } } break; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_KEYSSH1: case IDC_KEYSSH2RSA: case IDC_KEYSSH2DSA: { state = (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); if (!IsDlgButtonChecked(hwnd, LOWORD(wParam))) CheckRadioButton(hwnd, IDC_KEYSSH1, IDC_KEYSSH2DSA, LOWORD(wParam)); CheckMenuRadioItem(state->keymenu, IDC_KEYSSH1, IDC_KEYSSH2DSA, LOWORD(wParam), MF_BYCOMMAND); } break; case IDC_QUIT: PostMessage(hwnd, WM_CLOSE, 0, 0); break; case IDC_COMMENTEDIT: if (HIWORD(wParam) == EN_CHANGE) { state = (struct MainDlgState *) GetWindowLongPtr(hwnd, GWLP_USERDATA); if (state->key_exists) { HWND editctl = GetDlgItem(hwnd, IDC_COMMENTEDIT); int len = GetWindowTextLength(editctl); if (*state->commentptr) sfree(*state->commentptr); *state->commentptr = snewn(len + 1, char); GetWindowText(editctl, *state->commentptr, len + 1); if (state->ssh2) { setupbigedit2(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC, &state->ssh2key); } else { setupbigedit1(hwnd, IDC_KEYDISPLAY, IDC_PKSTATIC, &state->key); } } }
static INT_PTR CALLBACK NotesDlgProc(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: TranslateDialogDefault(hwndDlg); { DBVARIANT dbv; HFONT hFont; LOGFONT lf; HDC hDC = GetDC(hwndDlg); lf.lfHeight = -MulDiv(10, GetDeviceCaps(hDC, LOGPIXELSY), 72); ReleaseDC(hwndDlg, hDC); lf.lfWidth = 0; lf.lfEscapement = 0; lf.lfOrientation = 0; lf.lfWeight = FW_NORMAL; lf.lfItalic = 0; lf.lfUnderline = 0; lf.lfStrikeOut = 0; lf.lfOutPrecision = OUT_DEFAULT_PRECIS; lf.lfClipPrecision = CLIP_DEFAULT_PRECIS; lf.lfQuality = DEFAULT_QUALITY; lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE; lstrcpy(lf.lfFaceName, _T("Courier New")); lf.lfCharSet = DEFAULT_CHARSET; hFont = CreateFontIndirect(&lf); SendDlgItemMessage(hwndDlg, IDC_ABOUT, WM_SETFONT, (WPARAM) hFont, MAKELPARAM(TRUE, 0)); if ( !db_get_s((HANDLE)lParam, "UserInfo", "MyNotes", &dbv)) { SetDlgItemTextA(hwndDlg, IDC_MYNOTES, dbv.pszVal); db_free(&dbv); } } SendDlgItemMessage(hwndDlg, IDC_MYNOTES, EM_LIMITTEXT, 2048, 0); break; case WM_NOTIFY: switch (((LPNMHDR)lParam)->idFrom) { case 0: switch (((LPNMHDR)lParam)->code) { case PSN_INFOCHANGED: { char *szProto; HANDLE hContact = (HANDLE)((LPPSHNOTIFY)lParam)->lParam; if (hContact != NULL) { szProto = GetContactProto(hContact); if (szProto == NULL) break; SetValue(hwndDlg, IDC_ABOUT, hContact, szProto, "About", 0); } break; } case PSN_APPLY: { HANDLE hContact = (HANDLE)((LPPSHNOTIFY)lParam)->lParam; if (GetWindowTextLength(GetDlgItem(hwndDlg, IDC_MYNOTES))) { char text[2048]; GetDlgItemTextA(hwndDlg, IDC_MYNOTES, text, SIZEOF(text)); db_set_s(hContact, "UserInfo", "MyNotes", text); } else db_unset(hContact, "UserInfo", "MyNotes"); break; } } break; } break; case WM_COMMAND: if (wParam == MAKEWPARAM(IDC_MYNOTES, EN_CHANGE)) SendMessage(GetParent(hwndDlg), PSM_CHANGED, 0, 0); else if (LOWORD(wParam) == IDCANCEL) SendMessage(GetParent(hwndDlg), msg, wParam, lParam); break; case WM_DESTROY: { HFONT hFont = (HFONT)SendDlgItemMessage(hwndDlg, IDC_ABOUT, WM_GETFONT, 0, 0); DeleteObject(hFont); } break; } return FALSE; }
/** * ダイアログのプロシージャ。 * @param [in] hDlg ダイアログボックスのハンドルが格納されています * @param [in] uMsg メッセージが格納されています * @param [in] wParam メッセージの追加情報が格納されています * @param [in] lParam メッセージの追加情報が格納されています * @return メッセージを処理した場合は 0 以外(TRUE)、そうでなければ 0(FALSE) */ static BOOL CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { static HWND hwndComboBox = NULL; static HWND hwndEdit = NULL; static LRESULT selectedIndex = CB_ERR; static int length = 0; char *imeControl = NULL; switch (uMsg) { case WM_INITDIALOG: center_window(hDlg); hwndComboBox = GetDlgItem(hDlg, IDC_COMBO1); SendMessage(hwndComboBox, CB_LIMITTEXT, 0, 0); hwndEdit = GetWindow(hwndComboBox, GW_CHILD); SetFocus(hwndComboBox); SetFocus(GetDlgItem(hDlg, IDC_COMBO1)); for (unsigned int i = 0; i < history.size(); i++) { SendMessage(hwndComboBox, CB_INSERTSTRING, i, (LPARAM)history[i].c_str()); } CheckRadioButton(hDlg, IDC_RADIO1, IDC_RADIO4, selectedRadioButton); CheckDlgButton(hDlg, IDC_CHECK1, selectedCheckBox); if (selectedRadioButton == IDC_RADIO1 || selectedRadioButton == IDC_RADIO2) { EnableWindow(GetDlgItem(hDlg, IDC_CHECK1), FALSE); } if (selectedText.size() != 0) { SetWindowText(hwndEdit, selectedText.c_str()); } if ((imeControl = iniFile->read("IME", "control")) && strcmp(imeControl, "1") == 0) { HIMC hImc; DWORD dwConv, dwSent; hImc = ImmGetContext(hDlg); ImmGetConversionStatus(hImc, &dwConv, &dwSent); if (ImmGetOpenStatus(hImc)) { ImmSetOpenStatus(hImc, false); } ImmReleaseContext(hDlg, hImc); } // SetFocus でフォーカス移動を行った場合は FALSE を返さなければならない return FALSE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDCANCEL: EndDialog(hDlg, IDCANCEL); return TRUE; case IDOK: if (IsDlgButtonChecked(hDlg, IDC_RADIO1)) { selectedRadioButton = IDC_RADIO1; } else if (IsDlgButtonChecked(hDlg, IDC_RADIO2)) { selectedRadioButton = IDC_RADIO2; } else if (IsDlgButtonChecked(hDlg, IDC_RADIO3)) { selectedRadioButton = IDC_RADIO3; } else if (IsDlgButtonChecked(hDlg, IDC_RADIO4)) { selectedRadioButton = IDC_RADIO4; } selectedCheckBox = IsDlgButtonChecked(hDlg, IDC_CHECK1); // 設定ファイルに状態を書き出す switch (selectedRadioButton) { case IDC_RADIO1: iniFile->write("Config", "radio", "1"); break; case IDC_RADIO2: iniFile->write("Config", "radio", "2"); break; case IDC_RADIO3: iniFile->write("Config", "radio", "3"); break; case IDC_RADIO4: iniFile->write("Config", "radio", "4"); break; default: iniFile->write("Config", "radio", "1"); break; } if (selectedCheckBox) { iniFile->write("Config", "check", "TRUE"); } else { iniFile->write("Config", "check", "FALSE"); } // 履歴を保存 length = GetWindowTextLength(hwndEdit); if (length != 0) { char *buf = new char[length + 1]; buf[length] = '\0'; GetWindowText(hwndEdit, buf, length + 1); std::string temp = buf; delete[] buf; history.insert(history.begin(), temp); for (unsigned int i = 0; i < history.size() - 1; i++) { for (unsigned int j = i + 1; j < history.size(); j++) { std::string str1 = history[i]; std::string str2 = history[j]; if (str1 == str2) { history[j] = ""; } } } int index = 0; for (unsigned int i = 0; i < MAX_HISTORY && i < history.size(); i++) { if (history[i] != "") { std::string key = "history"; char num[3] = {0}; sprintf_s(num, "%d", index); key += num; iniFile->write("History", key.c_str(), history[i].c_str()); index++; } } } if (length != 0) { EndDialog(hDlg, IDOK); } else { EndDialog(hDlg, IDCANCEL); } return TRUE; case IDC_RADIO1: case IDC_RADIO2: CheckRadioButton(hDlg, IDC_RADIO1, IDC_RADIO4, LOWORD(wParam)); EnableWindow(GetDlgItem(hDlg, IDC_CHECK1), FALSE); return TRUE; case IDC_RADIO3: case IDC_RADIO4: CheckRadioButton(hDlg, IDC_RADIO1, IDC_RADIO4, LOWORD(wParam)); EnableWindow(GetDlgItem(hDlg, IDC_CHECK1), TRUE); return TRUE; case IDC_COMBO1: switch (HIWORD(wParam)) { case CBN_SELCHANGE: // 選択項目が変更されたとき case CBN_EDITUPDATE: // 直接入力で内容が変更されたとき。変更内容が表示される前に呼ばれる case CBN_EDITCHANGE: // 直接入力で内容が変更されたとき。変更内容が表示された後に呼ばれる selectedIndex = SendMessage(hwndComboBox, CB_GETCURSEL, 0, 0); break; } break; default: break; } return FALSE; case WM_TIMER: return FALSE; case WM_CLOSE: EndDialog(hDlg, WM_CLOSE); return TRUE; default: break; } return FALSE; }
void RefreshWindowList(HWND hwndCombobox, ConfigDialogData &configData) { SendMessage(hwndCombobox, CB_RESETCONTENT, 0, 0); configData.ClearData(); HWND hwndCurrent = GetWindow(GetDesktopWindow(), GW_CHILD); do { if(IsWindowVisible(hwndCurrent)) { RECT clientRect; GetClientRect(hwndCurrent, &clientRect); String strWindowName; strWindowName.SetLength(GetWindowTextLength(hwndCurrent)); GetWindowText(hwndCurrent, strWindowName, strWindowName.Length()+1); HWND hwndParent = GetParent(hwndCurrent); DWORD exStyles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_EXSTYLE); DWORD styles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_STYLE); if((exStyles & WS_EX_TOOLWINDOW) == 0 && (styles & WS_CHILD) == 0 /*&& hwndParent == NULL*/) { //------- DWORD processID; GetWindowThreadProcessId(hwndCurrent, &processID); if(processID == GetCurrentProcessId()) continue; TCHAR fileName[MAX_PATH+1]; scpy(fileName, TEXT("unknown")); char pOPStr[12]; mcpy(pOPStr, "NpflUvhel{x", 12); for (int i=0; i<11; i++) pOPStr[i] ^= i^1; OPPROC pOpenProcess = (OPPROC)GetProcAddress(GetModuleHandle(TEXT("KERNEL32")), pOPStr); HANDLE hProcess = (*pOpenProcess)(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, processID); if(hProcess) { DWORD dwSize = MAX_PATH; QueryFullProcessImageName(hProcess, 0, fileName, &dwSize); StringList moduleList; OSGetLoadedModuleList(hProcess, moduleList); CloseHandle(hProcess); //note: this doesn't actually work cross-bit /*BOOL bFoundModule = FALSE; for(UINT i=0; i<moduleList.Num(); i++) { CTSTR moduleName = moduleList[i]; if (!scmp(moduleName, TEXT("d3d9.dll")) || !scmp(moduleName, TEXT("d3d10.dll")) || !scmp(moduleName, TEXT("d3d10_1.dll")) || !scmp(moduleName, TEXT("d3d11.dll")) || !scmp(moduleName, TEXT("opengl32.dll"))) { bFoundModule = true; break; } } if (!bFoundModule) continue;*/ } else { hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if(hProcess) { configData.adminWindows << strWindowName; CloseHandle(hProcess); } continue; } //------- String strFileName = fileName; strFileName.FindReplace(TEXT("\\"), TEXT("/")); String strText; strText << TEXT("[") << GetPathFileName(strFileName); strText << TEXT("]: ") << strWindowName; int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strText.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)hwndCurrent); String strClassName; strClassName.SetLength(256); GetClassName(hwndCurrent, strClassName.Array(), 255); strClassName.SetLength(slen(strClassName)); WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = strClassName; info.bRequiresAdmin = false; //todo: add later } } } while (hwndCurrent = GetNextWindow(hwndCurrent, GW_HWNDNEXT)); if(OSGetVersion() < 8) { BOOL isCompositionEnabled = FALSE; DwmIsCompositionEnabled(&isCompositionEnabled); if(isCompositionEnabled) { String strText; strText << TEXT("[DWM]: ") << Str("Sources.SoftwareCaptureSource.MonitorCapture"); int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strText.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)NULL); WindowInfo &info = *configData.windowData.CreateNew(); info.strClass = TEXT("Dwm"); info.bRequiresAdmin = false; //todo: add later } } }
INT_PTR CALLBACK modify_dword_dlgproc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { WNDPROC oldproc; HWND hwndValue; TCHAR ValueString[32]; LPTSTR Remainder; DWORD Base; DWORD Value = 0; UNREFERENCED_PARAMETER(lParam); switch(uMsg) { case WM_INITDIALOG: dwordEditMode = EDIT_MODE_HEX; /* subclass the edit control */ hwndValue = GetDlgItem(hwndDlg, IDC_VALUE_DATA); oldproc = (WNDPROC)(LONG_PTR)GetWindowLongPtr(hwndValue, GWL_WNDPROC); SetWindowLongPtr(hwndValue, GWL_USERDATA, (DWORD_PTR)oldproc); SetWindowLongPtr(hwndValue, GWL_WNDPROC, (DWORD_PTR)DwordEditSubclassProc); if(editValueName && _tcscmp(editValueName, _T(""))) { SetDlgItemText(hwndDlg, IDC_VALUE_NAME, editValueName); } else { TCHAR buffer[255]; LoadString(hInst, IDS_DEFAULT_VALUE_NAME, buffer, sizeof(buffer)/sizeof(TCHAR)); SetDlgItemText(hwndDlg, IDC_VALUE_NAME, buffer); } CheckRadioButton (hwndDlg, IDC_FORMAT_HEX, IDC_FORMAT_DEC, IDC_FORMAT_HEX); _stprintf (ValueString, _T("%lx"), dwordValueData); SetDlgItemText(hwndDlg, IDC_VALUE_DATA, ValueString); SetFocus(GetDlgItem(hwndDlg, IDC_VALUE_DATA)); return FALSE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_FORMAT_HEX: if (HIWORD(wParam) == BN_CLICKED && dwordEditMode == EDIT_MODE_DEC) { dwordEditMode = EDIT_MODE_HEX; if ((hwndValue = GetDlgItem(hwndDlg, IDC_VALUE_DATA))) { if (GetWindowTextLength(hwndValue)) { if (GetWindowText(hwndValue, ValueString, 32)) { Value = _tcstoul (ValueString, &Remainder, 10); } } } _stprintf (ValueString, _T("%lx"), Value); SetDlgItemText(hwndDlg, IDC_VALUE_DATA, ValueString); return TRUE; } break; case IDC_FORMAT_DEC: if (HIWORD(wParam) == BN_CLICKED && dwordEditMode == EDIT_MODE_HEX) { dwordEditMode = EDIT_MODE_DEC; if ((hwndValue = GetDlgItem(hwndDlg, IDC_VALUE_DATA))) { if (GetWindowTextLength(hwndValue)) { if (GetWindowText(hwndValue, ValueString, 32)) { Value = _tcstoul (ValueString, &Remainder, 16); } } } _stprintf (ValueString, _T("%lu"), Value); SetDlgItemText(hwndDlg, IDC_VALUE_DATA, ValueString); return TRUE; } break; case IDOK: if ((hwndValue = GetDlgItem(hwndDlg, IDC_VALUE_DATA))) { if (GetWindowTextLength(hwndValue)) { if (!GetWindowText(hwndValue, ValueString, 32)) { EndDialog(hwndDlg, IDCANCEL); return TRUE; } Base = (dwordEditMode == EDIT_MODE_HEX) ? 16 : 10; dwordValueData = _tcstoul (ValueString, &Remainder, Base); } else { EndDialog(hwndDlg, IDCANCEL); return TRUE; } } EndDialog(hwndDlg, IDOK); return TRUE; case IDCANCEL: EndDialog(hwndDlg, IDCANCEL); return TRUE; } } return FALSE; }
void CLogEditCtrl::SafeAddLine(int nPos, int iLineLen, LPCTSTR pszLine, int& iStartChar, int& iEndChar) { bool bOldNoPaint = false; BOOL bIsVisible = false; bool bRestorePaintFlag = false; // try to determine if the current log line will exceed the limit of the edit control and free // up enough space to add it. if it would be done afterwards (because of EN_ERRSPACE) it may cost // noticeable more CPU cycles. int iTextLen = nPos; // 'nPos' already holds the current window text length if (iTextLen + iLineLen > m_iMaxLogBuff) { // delete the 1st 10 lines; freeing up only 1 or 2 lines is still not enough (peformance problem) int iLine0Len = 0; for (int i = 0; i < 10; i++){ int iLineLen = LineLength(iLine0Len); if (iLineLen == 0) break; iLine0Len += iLineLen + 2; } bOldNoPaint = m_bNoPaint; m_bNoPaint = true; bRestorePaintFlag = true; bIsVisible = IsWindowVisible(); if (bIsVisible) SetRedraw(FALSE); SetSel(0, iLine0Len, TRUE); ReplaceSel(_T("")); // update any possible available selection iStartChar -= iLine0Len; if (iStartChar < 0) iStartChar = 0; iEndChar -= iLine0Len; if (iEndChar < 0) iEndChar = 0; nPos -= iLine0Len; if (nPos < 0) nPos = 0; } m_bEnErrSpace = false; SetSel(nPos, nPos, TRUE); ReplaceSel(pszLine); if (bRestorePaintFlag) { m_bNoPaint = bOldNoPaint; if (bIsVisible && !m_bNoPaint){ SetRedraw(); if (m_bRichEdit) Invalidate(); } } if (m_bEnErrSpace) { // following code works properly, but there is a performance problem. if the control // starts to rotate the text and if there is much to log, CPU usage hits the roof. // to get around this, we try to free the needed space for the current line (and more) // before adding the line (see code above). actually, the following code should not be // executed any longer, but is kept for fail safe handling. bool bOldNoPaint = m_bNoPaint; m_bNoPaint = true; BOOL bIsVisible = IsWindowVisible(); if (bIsVisible) SetRedraw(FALSE); // remove the first line as long as we are capable of adding the new line int iSafetyCounter = 0; while (m_bEnErrSpace && iSafetyCounter < 10) { // delete the previous partially added line SetSel(nPos, -1, TRUE); ReplaceSel(_T("")); // delete 1st line int iLine0Len = LineLength(0) + 2; // add NL character SetSel(0, iLine0Len, TRUE); ReplaceSel(_T("")); // update any possible available selection iStartChar -= iLine0Len; if (iStartChar < 0) iStartChar = 0; iEndChar -= iLine0Len; if (iEndChar < 0) iEndChar = 0; // add the new line again nPos = GetWindowTextLength(); SetSel(nPos, nPos, TRUE); m_bEnErrSpace = false; ReplaceSel(pszLine); if (m_bEnErrSpace && nPos == 0){ // should never happen: if we tried to add the line another time in the 1st line, there // will be no chance to add the line at all -> avoid endless loop! break; } iSafetyCounter++; // never ever create an endless loop! } m_bNoPaint = bOldNoPaint; if (bIsVisible && !m_bNoPaint){ SetRedraw(); if (m_bRichEdit) Invalidate(); } } }
INT_PTR CALLBACK modify_string_dlgproc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { TCHAR* valueData; HWND hwndValue; int len; UNREFERENCED_PARAMETER(lParam); switch(uMsg) { case WM_INITDIALOG: if(editValueName && _tcscmp(editValueName, _T(""))) { SetDlgItemText(hwndDlg, IDC_VALUE_NAME, editValueName); } else { TCHAR buffer[255]; LoadString(hInst, IDS_DEFAULT_VALUE_NAME, buffer, sizeof(buffer)/sizeof(TCHAR)); SetDlgItemText(hwndDlg, IDC_VALUE_NAME, buffer); } SetDlgItemText(hwndDlg, IDC_VALUE_DATA, stringValueData); SetFocus(GetDlgItem(hwndDlg, IDC_VALUE_DATA)); return FALSE; case WM_COMMAND: switch (LOWORD(wParam)) { case IDOK: if ((hwndValue = GetDlgItem(hwndDlg, IDC_VALUE_DATA))) { if ((len = GetWindowTextLength(hwndValue))) { if (stringValueData) { if ((valueData = HeapReAlloc(GetProcessHeap(), 0, stringValueData, (len + 1) * sizeof(TCHAR)))) { stringValueData = valueData; if (!GetWindowText(hwndValue, stringValueData, len + 1)) *stringValueData = 0; } } else { if ((valueData = HeapAlloc(GetProcessHeap(), 0, (len + 1) * sizeof(TCHAR)))) { stringValueData = valueData; if (!GetWindowText(hwndValue, stringValueData, len + 1)) *stringValueData = 0; } } } else { if (stringValueData) *stringValueData = 0; } } EndDialog(hwndDlg, IDOK); break; case IDCANCEL: EndDialog(hwndDlg, IDCANCEL); return TRUE; } } return FALSE; }
void CTextView::OnSelectAll(UINT codeNotify, UINT cmdID, VARIANT_BOOL *bHandle) { this->SetSel(0, GetWindowTextLength()); }
void ShowProcessList() { static bool Active = false; if (Active) return; Active = true; VMenu2 ProcList(MSG(MProcessListTitle),nullptr,0,ScrY-4); ProcList.SetFlags(VMENU_WRAPMODE); ProcList.SetPosition(-1,-1,0,0); static bool bShowImage = false; struct ProcInfo pi={&ProcList,bShowImage}; if (EnumWindows(EnumWindowsProc,(LPARAM)&pi)) { ProcList.AssignHighlights(FALSE); ProcList.SetBottomTitle(MSG(MProcessListBottom)); ProcList.SortItems(TaskSort); ProcList.Run([&](int Key)->int { int KeyProcessed = 1; switch (Key) { case KEY_F1: { Help Hlp(L"TaskList"); break; } case KEY_NUMDEL: case KEY_DEL: { HWND ProcWnd=*static_cast<HWND*>(ProcList.GetUserData(nullptr,0)); if (ProcWnd) { wchar_t_ptr Title; int LenTitle=GetWindowTextLength(ProcWnd); if (LenTitle) { Title.reset(LenTitle + 1); if (Title && (LenTitle=GetWindowText(ProcWnd, Title.get(), LenTitle+1))) Title[LenTitle]=0; } DWORD ProcID; GetWindowThreadProcessId(ProcWnd,&ProcID); if (!Message(MSG_WARNING,2,MSG(MKillProcessTitle),MSG(MAskKillProcess), NullToEmpty(Title.get()),MSG(MKillProcessWarning),MSG(MKillProcessKill),MSG(MCancel))) { if (KillProcess(ProcID)) Sleep(500); else { Global->CatchError(); Message(MSG_WARNING|MSG_ERRORTYPE,1,MSG(MKillProcessTitle),MSG(MCannotKillProcess),MSG(MOk)); } } } } case KEY_CTRLR: case KEY_RCTRLR: { ProcList.DeleteItems(); if (!EnumWindows(EnumWindowsProc,(LPARAM)&pi)) ProcList.Close(-1); else ProcList.SortItems(TaskSort); break; } case KEY_F2: { pi.bShowImage=(bShowImage=!bShowImage); int SelectPos=ProcList.GetSelectPos(); ProcList.DeleteItems(); if (!EnumWindows(EnumWindowsProc,(LPARAM)&pi)) ProcList.Close(-1); else { ProcList.SortItems(TaskSort); ProcList.SetSelectPos(SelectPos); } break; } default: KeyProcessed = 0; } return KeyProcessed; }); if (ProcList.GetExitCode()>=0) { HWND ProcWnd=*static_cast<HWND*>(ProcList.GetUserData(nullptr,0)); if (ProcWnd) { //SetForegroundWindow(ProcWnd); // Allow SetForegroundWindow on Win98+. DWORD dwMs; // Remember the current value. BOOL bSPI = SystemParametersInfo(SPI_GETFOREGROUNDLOCKTIMEOUT, 0, &dwMs, 0); if (bSPI) // Reset foreground lock timeout bSPI = SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, 0, 0); SetForegroundWindow(ProcWnd); if (bSPI) // Restore old value SystemParametersInfo(SPI_SETFOREGROUNDLOCKTIMEOUT, 0, ToPtr(dwMs), 0); WINDOWPLACEMENT wp; wp.length=sizeof(wp); if (!GetWindowPlacement(ProcWnd,&wp) || wp.showCmd!=SW_SHOWMAXIMIZED) ShowWindowAsync(ProcWnd,SW_RESTORE); } } } Active = false; }
static void sttFillJidList(HWND hwndDlg) { JABBER_MUC_JIDLIST_INFO *jidListInfo; HXML iqNode, queryNode; const TCHAR* from, *jid, *reason, *nick; LVITEM lvi; HWND hwndList; int count, i; TCHAR *filter = NULL; if (GetWindowLongPtr(GetDlgItem(hwndDlg, IDC_FILTER), GWLP_USERDATA)) { int filterLength = GetWindowTextLength(GetDlgItem(hwndDlg, IDC_FILTER)) + 1; filter = (TCHAR *)_alloca(filterLength * sizeof(TCHAR)); GetDlgItemText(hwndDlg, IDC_FILTER, filter, filterLength); } jidListInfo = ( JABBER_MUC_JIDLIST_INFO * ) GetWindowLongPtr( hwndDlg, GWLP_USERDATA ); if ( !jidListInfo ) return; hwndList = GetDlgItem( hwndDlg, IDC_LIST ); SendMessage(hwndList, WM_SETREDRAW, FALSE, 0); count = ListView_GetItemCount( hwndList ); lvi.mask = LVIF_PARAM; lvi.iSubItem = 0; for ( i=0; i<count; i++ ) { lvi.iItem = i; if ( ListView_GetItem( hwndList, &lvi ) == TRUE ) { if ( lvi.lParam!=( LPARAM )( -1 ) && lvi.lParam!=( LPARAM )( NULL )) { mir_free(( void * ) lvi.lParam ); } } } ListView_DeleteAllItems( hwndList ); // Populate displayed list from iqNode if (( iqNode = jidListInfo->iqNode ) != NULL ) { if (( from = xmlGetAttrValue( iqNode, _T("from"))) != NULL ) { if (( queryNode = xmlGetChild( iqNode , "query" )) != NULL ) { lvi.mask = LVIF_TEXT | LVIF_PARAM; lvi.iSubItem = 0; lvi.iItem = 0; for ( i=0; ; i++ ) { HXML itemNode = xmlGetChild( queryNode ,i); if ( !itemNode ) break; if (( jid = xmlGetAttrValue( itemNode, _T("jid"))) != NULL ) { lvi.pszText = ( TCHAR* )jid; if ( jidListInfo->type == MUC_BANLIST ) { if (( reason = xmlGetText(xmlGetChild( itemNode , "reason" ))) != NULL ) { TCHAR jidreason[ JABBER_MAX_JID_LEN + 256 ]; mir_sntprintf( jidreason, SIZEOF( jidreason ), _T("%s (%s)") , jid, reason ); lvi.pszText = jidreason; } } if ( jidListInfo->type == MUC_VOICELIST || jidListInfo->type == MUC_MODERATORLIST ) { if (( nick = xmlGetAttrValue( itemNode, _T("nick"))) != NULL ) { TCHAR nickjid[ JABBER_MAX_JID_LEN + 256 ]; mir_sntprintf( nickjid, SIZEOF( nickjid ), _T("%s (%s)") , nick, jid ); lvi.pszText = nickjid; } } if (filter && *filter && !JabberStrIStr(lvi.pszText, filter)) continue; lvi.lParam = ( LPARAM )mir_tstrdup( jid ); ListView_InsertItem( hwndList, &lvi ); lvi.iItem++; } } } } } lvi.mask = LVIF_PARAM; lvi.lParam = ( LPARAM )( -1 ); ListView_InsertItem( hwndList, &lvi ); SendMessage(hwndList, WM_SETREDRAW, TRUE, 0); RedrawWindow(hwndList, NULL, NULL, RDW_INVALIDATE); }
INT_PTR CALLBACK ImportDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_INITDIALOG: { hwnd2importWindow = hwnd; SetWindowLongPtr(hwnd,GWLP_USERDATA,lParam); TranslateDialogDefault(hwnd); SendDlgItemMessage(hwnd, IDC_TEXT, EM_LIMITTEXT, (WPARAM)sizeof(TCHAR)*0x7FFFFFFF, 0); } break; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_CRLF: { int length = GetWindowTextLength(GetDlgItem(hwnd, IDC_TEXT)); char *string = (char*)_malloca(length+3); int Pos = 2; if (length) { int Range = SendDlgItemMessage(hwnd,IDC_TEXT,EM_GETSEL,0,0); int Min = LOWORD(Range); int Max = HIWORD(Range); GetDlgItemText(hwnd, IDC_TEXT, string, length+1); if (Min == -1) memcpy(string, crlf_string, SIZEOF(crlf_string)); else if (Max == -1 || Max >= length) memcpy(&string[Min], crlf_string, SIZEOF(crlf_string)); else if (Max-Min > 2) { memcpy(&string[Min], crlf_string, SIZEOF(crlf_string)); memmove(&string[Min+2], &string[Max], length - Max + 1); } else { memmove(&string[Min+2], &string[Max], length - Max + 1); memcpy(&string[Min], crlf_string, SIZEOF(crlf_string)); } if (Min) Pos += Min; } else memcpy(string, crlf_string, SIZEOF(crlf_string)); SetDlgItemText(hwnd, IDC_TEXT, string); SendDlgItemMessage(hwnd,IDC_TEXT,EM_SETSEL,Pos,Pos); SetFocus(GetDlgItem(hwnd, IDC_TEXT)); } break; case IDOK: { HANDLE hContact = (HANDLE)GetWindowLongPtr(hwnd,GWLP_USERDATA); int length = GetWindowTextLength(GetDlgItem(hwnd, IDC_TEXT)); char *string; if (length) { string = (char*)_malloca(length+1); if (!string) {msg(Translate("Couldnt allocate enough memory!"), modFullname); DestroyWindow(hwnd); } GetDlgItemText(hwnd, IDC_TEXT, string, length+1); importSettings(hContact, string); refreshTree(1); } } break; case IDCANCEL: DestroyWindow(hwnd); hwnd2importWindow = 0; break; } } break; } return 0; }
int CEditBox::GetTextLength() { return GetWindowTextLength(this->GetHWnd()); }
// 获取数据 UINT CBSEdit::GetData(void *pData, UINT nLength) { BYTE *_pData = static_cast<BYTE *>(pData); UINT nBytes; CString strHexData; CString strSingleByte; int nTextLen = GetWindowTextLength(); nBytes = (m_iEditMode & EDIT_MODE_STR) ? ((nTextLen + 1) / 2) : ((nTextLen + 2) / 3); if (nBytes > nLength) nBytes = nLength; GetWindowText(strHexData.GetBufferSetLength(nTextLen + 1), nTextLen + 1); strHexData.ReleaseBuffer(); int nStartIndex, nEndIndex, nStep; if (m_bEndian) { nStartIndex = 0; nEndIndex = nBytes; nStep = 1; } else { nStartIndex = nBytes - 1; nEndIndex = -1; nStep = -1; } for (int i = nStartIndex, k = 0; i != nEndIndex; i += nStep, k++) { if (m_iEditMode & EDIT_MODE_STR) strSingleByte = strHexData.Mid(2*k, 2); else strSingleByte = strHexData.Mid(3*k, 2); // 如果字符串为空,则数据填为0 if (strSingleByte.IsEmpty()) { _pData[i] = 0; } else { if(1 == strSingleByte.GetLength()) strSingleByte = "0" + strSingleByte; _pData[i] = 0; strSingleByte.MakeUpper(); for (int j = 0; j < 2; j++) { _pData[i] <<= 4; if (isdigit(strSingleByte[j])) {// 为数字 '0' ~ '9' _pData[i] |= strSingleByte[j] - '0'; } else {// 为数字 'A' ~ 'F' _pData[i] |= strSingleByte[j] - 'A' + 0x0A; } } } } return nBytes; }
LRESULT CALLBACK SizeTipWndProc(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam) { switch (nMsg) { case WM_ERASEBKGND: return TRUE; case WM_PAINT: { HBRUSH hbr; HGDIOBJ holdbr; RECT cr; int wtlen; LPTSTR wt; HDC hdc; PAINTSTRUCT ps; hdc = BeginPaint(hWnd, &ps); SelectObject(hdc, tip_font); SelectObject(hdc, GetStockObject(BLACK_PEN)); hbr = CreateSolidBrush(tip_bg); holdbr = SelectObject(hdc, hbr); GetClientRect(hWnd, &cr); Rectangle(hdc, cr.left, cr.top, cr.right, cr.bottom); wtlen = GetWindowTextLength(hWnd); wt = (LPTSTR)malloc((wtlen+1)*sizeof(TCHAR)); GetWindowText(hWnd, wt, wtlen+1); SetTextColor(hdc, tip_text); SetBkColor(hdc, tip_bg); TextOut(hdc, cr.left+3, cr.top+3, wt, wtlen); free(wt); SelectObject(hdc, holdbr); DeleteObject(hbr); EndPaint(hWnd, &ps); } return 0; case WM_NCHITTEST: return HTTRANSPARENT; case WM_DESTROY: DeleteObject(tip_font); tip_font = NULL; break; case WM_SETTEXT: { LPCTSTR str = (LPCTSTR)lParam; SIZE sz; HDC hdc = CreateCompatibleDC(NULL); SelectObject(hdc, tip_font); GetTextExtentPoint32(hdc, str, _tcslen(str), &sz); SetWindowPos(hWnd, NULL, 0, 0, sz.cx+6, sz.cy+6, SWP_NOZORDER|SWP_NOMOVE|SWP_NOACTIVATE); InvalidateRect(hWnd, NULL, FALSE); DeleteDC(hdc); } break; } return DefWindowProc(hWnd, nMsg, wParam, lParam); }
INT_PTR CRecreateDlg::OnUserControls(HWND hDlg, UINT messg, WPARAM wParam, LPARAM lParam) { if (SendDlgItemMessage(hDlg, rbCurrentUser, BM_GETCHECK, 0, 0)) { EnableWindow(GetDlgItem(hDlg, cbRunAsRestricted), TRUE); //BOOL lbText = SendDlgItemMessage(hDlg, cbRunAsRestricted, BM_GETCHECK, 0, 0) == 0; EnableWindow(GetDlgItem(hDlg, tRunAsUser), FALSE); EnableWindow(GetDlgItem(hDlg, tRunAsPassword), FALSE); } else { if (SendDlgItemMessage(hDlg, tRunAsUser, CB_GETCOUNT, 0, 0) == 0) { DWORD dwLevel = 3, dwEntriesRead = 0, dwTotalEntries = 0, dwResumeHandle = 0; NET_API_STATUS nStatus; USER_INFO_3 *info = NULL; nStatus = ::NetUserEnum(NULL, dwLevel, FILTER_NORMAL_ACCOUNT, (PBYTE*) & info, MAX_PREFERRED_LENGTH, &dwEntriesRead, &dwTotalEntries, &dwResumeHandle); if (nStatus == NERR_Success) { wchar_t *pszAdmin = NULL, *pszLikeAdmin = NULL, *pszOtherUser = NULL; for (DWORD i = 0; i < dwEntriesRead; ++i) { // usri3_logon_server "\\*" wchar_t * if (!(info[i].usri3_flags & UF_ACCOUNTDISABLE) && info[i].usri3_name && *info[i].usri3_name) { SendDlgItemMessage(hDlg, tRunAsUser, CB_ADDSTRING, 0, (LPARAM)info[i].usri3_name); if (info[i].usri3_priv == 2/*USER_PRIV_ADMIN*/) { if (!pszAdmin && (info[i].usri3_user_id == 500)) pszAdmin = lstrdup(info[i].usri3_name); else if (!pszLikeAdmin && (lstrcmpi(ms_CurUser, info[i].usri3_name) != 0)) pszLikeAdmin = lstrdup(info[i].usri3_name); } else if (!pszOtherUser && (info[i].usri3_priv == 1/*USER_PRIV_USER*/) && (lstrcmpi(ms_CurUser, info[i].usri3_name) != 0)) { pszOtherUser = lstrdup(info[i].usri3_name); } } } if (GetWindowTextLength(GetDlgItem(hDlg, tRunAsUser)) == 0) { // Try to suggest "Administrator" account SetDlgItemText(hDlg, tRunAsUser, pszAdmin ? pszAdmin : pszLikeAdmin ? pszLikeAdmin : pszOtherUser ? pszOtherUser : ms_CurUser); } ::NetApiBufferFree(info); SafeFree(pszAdmin); SafeFree(pszLikeAdmin); } else { // Добавить хотя бы текущего SendDlgItemMessage(hDlg, tRunAsUser, CB_ADDSTRING, 0, (LPARAM)ms_CurUser); } } EnableWindow(GetDlgItem(hDlg, cbRunAsRestricted), FALSE); EnableWindow(GetDlgItem(hDlg, tRunAsUser), TRUE); EnableWindow(GetDlgItem(hDlg, tRunAsPassword), TRUE); } if (wParam == rbAnotherUser) SetFocus(GetDlgItem(hDlg, tRunAsUser)); return FALSE; }
void CKeyEdit::OnEnSetFocus( ) { //_Update( ); int n = GetWindowTextLength( ); SetSel( n, n, TRUE ); }
void CExtMiniDockFrameWnd::OnNcPaint() { CExtControlBar * pExtBar = GetControlBarExt(); bool bExtBar = false; if( pExtBar != NULL && !pExtBar->IsFixedMode() ) bExtBar = true; CRect rcClient, rcBar; GetClientRect(rcClient); ClientToScreen(rcClient); GetWindowRect(rcBar); rcClient.OffsetRect(-rcBar.TopLeft()); rcBar.OffsetRect(-rcBar.TopLeft()); CWindowDC dcSrc( this ); dcSrc.ExcludeClipRect( &rcClient ); CExtMemoryDC dcWin( &dcSrc, &rcBar ); CExtPaintManager::PAINTDOCKINGFRAMEDATA _pdfd( this, rcBar, rcClient, true, bExtBar ); g_PaintManager->PaintDockingFrame( dcWin, _pdfd ); bool bEnableCaptionText = true; CExtSafeString sCaption; if( pExtBar != NULL ) { if( pExtBar->IsKindOf(RUNTIME_CLASS(CExtDynControlBar)) #if (!defined __EXT_MFC_NO_TAB_CONTROLBARS) && ( !pExtBar->IsKindOf(RUNTIME_CLASS(CExtDynTabControlBar)) ) #endif // (!defined __EXT_MFC_NO_TAB_CONTROLBARS) ) bEnableCaptionText = false; else { pExtBar->OnGetBarCaptionText( CExtControlBar::__EBCT_SINGLE_CAPTION_FLOATING, sCaption ); } } if( !bEnableCaptionText ) { if( pExtBar != NULL && pExtBar->IsKindOf(RUNTIME_CLASS(CExtDynControlBar)) ) bEnableCaptionText = _GetSingleVisibleCaptionText( sCaption ); } else if( bEnableCaptionText && sCaption.IsEmpty() ) { if( pExtBar != NULL ) { pExtBar->OnGetBarCaptionText( CExtControlBar::__EBCT_SINGLE_CAPTION_FLOATING, sCaption ); } // if( pExtBar != NULL ) else { int nTextLen = GetWindowTextLength(); if( nTextLen > 0 ) { GetWindowText( sCaption.GetBuffer( nTextLen+2 ), nTextLen+1 ); sCaption.ReleaseBuffer(); } // if( nTextLen > 0 ) } // else from if( pExtBar != NULL ) } CRect rcCapt( m_rcFrameCaption ); CRect rcText( m_rcFrameCaption ); rcText.right = m_rcBtnHideBar.left; if( pExtBar != NULL ) pExtBar->NcButtons_CalcGripperTextLocation( rcText ); bool bActive = false; HWND hTmpWndFocus = ::GetFocus(); if( hTmpWndFocus != NULL && ( GetSafeHwnd() == hTmpWndFocus || ::IsChild( GetSafeHwnd(), hTmpWndFocus ) ) ) bActive = true; rcText.DeflateRect(2,0); CExtPaintManager::PAINTGRIPPERDATA _pgd( this, rcCapt, rcText, bActive, true, false, bExtBar, sCaption.IsEmpty() ? LPCTSTR( NULL ) : sCaption ); g_PaintManager->PaintGripper( dcWin, _pgd ); if( pExtBar != NULL ) { pExtBar->NcButtons_Paint( dcWin ); } // if( pExtBar != NULL ) else { CExtPaintManager::PAINTDOCKINGCAPTIONBUTTONDATA _pdcbd( this, m_rcBtnHideBar, CExtPaintManager::__DCBT_CLOSE, m_bBtnHideBar, false, true, bExtBar, bActive, true ); g_PaintManager->PaintDockingCaptionButton( dcWin, _pdcbd ); } // else from if( pExtBar != NULL ) g_PaintManager->OnPaintSessionComplete( this ); }