Тема: Просмотр текста в окне
Лабораторная работа № 2 ПО ДИСЦИПЛИНЕ: " ПРОГРАММИРОВАНИЕ ПОД WINDOWS " Тема: Просмотр текста в окне
Выполнил: Студент группы КСоз-11 Внуков А.С. Проверил: Теплинский С.В.
ДонНТУ 2012 г. Листинг программы: #include "WinAPI_Lab3.h"
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { char szAppName[] = "WinAPI_Lab3"; HWND hwnd; MSG msg; WNDCLASSEX wndclass;
wndclass.cbSize = sizeof (wndclass); wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon (NULL, IDI_WINLOGO); wndclass.hCursor = LoadCursor (NULL, IDC_WAIT); wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szAppName; wndclass.hIconSm = LoadIcon (NULL, IDI_WINLOGO);
RegisterClassEx (&wndclass);
hwnd = CreateWindow (szAppName, "WinAPI Lab #3 Sample", WS_OVERLAPPEDWINDOW | WS_VSCROLL | WS_HSCROLL, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
ShowWindow (hwnd, iCmdShow); UpdateWindow (hwnd);
while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage (&msg); DispatchMessage (&msg); } return msg.wParam; }
LRESULT CALLBACK WndProc (HWND hwnd, UINT iMsg, WPARAM wParam, LPARAM lParam) { static int cxChar, cxCaps, cyChar, cxClient, cyClient, iVscrollPos, iVscrollMax, iHscrollPos, iHscrollMax, iMaxWidth, // максимальная длина строчки вывода iBufLines; // общее количество строчек текста для вывода HDC hdc; int i, i2 = 0, x, y, iPaintBeg, iPaintEnd, iVscrollInc, iHscrollInc; int cur_len = 0, max_len = 0; FILE *stream = NULL; char *szBuf, *szClipboard = NULL; PAINTSTRUCT ps; TEXTMETRIC tm;
switch (iMsg) { case WM_CREATE: hdc = GetDC (hwnd);
GetTextMetrics (hdc, &tm); cxChar = tm.tmAveCharWidth; cxCaps = (tm.tmPitchAndFamily & 1? 3: 2) * cxChar / 2; cyChar = tm.tmHeight + tm.tmExternalLeading;
iBufLines = iMaxWidth = 0;
// установка параметров для примера вывода sysmetrics #ifdef VAR0
iBufLines = NUMLINES; iMaxWidth = 40 * cxChar + 22 * cxCaps;
// установка параметров для вывода содержимого текстового файла #elif defined VAR1
// считаем файл в буфер if ((stream = fopen("test.txt", "rt")) == NULL) { MessageBox(hwnd, "Невозможно открыть файл 'test.txt'!", "Ошибка!", MB_OK | MB_ICONERROR); } else { max_len = 0; while (!feof(stream)) { // считываем строку из файла szBuf = new char[80]; if (fgets(szBuf, 80, stream)!= NULL) { cur_len = strlen(szBuf);
// забиваем символ конца строки if ((cur_len > 0) && (szBuf[cur_len - 1] == '\n')) szBuf[--cur_len] = 0;
// определяем максимальную длину строки в файле if (cur_len > max_len) max_len = cur_len;
// заносим строку в буфер fileBuf.push_back(szBuf); } else delete[] szBuf; } // закрываем файл fclose(stream);
iBufLines = fileBuf.size(); iMaxWidth = (int)(max_len / 1.3) * cxChar + (max_len >> 1 + 2) * cxCaps; }
// установка параметров для вывода содержимого буфера обмена #elif defined VAR2
// начинаем работу с буфером обмена if (OpenClipboard(hwnd)!= NULL) { // считываем содержимое буфера обмена как текст szClipboard = (char*)GetClipboardData(CF_TEXT); if (szClipboard!= NULL) { i = i2 = max_len = 0; // разделяем текст буфера обмена на подстроки while (i2 < strlen(szClipboard)) { if ((szClipboard[i2] == '\n') || (i2 == (strlen(szClipboard) - 1))) { if (szClipboard[i2] == '\n') cur_len = i2 - i; else cur_len = i2 - i + 2; szBuf = new char[cur_len]; strncpy(szBuf, &szClipboard[i], cur_len - 1); szBuf[cur_len - 1] = 0; clipBuf.push_back(szBuf); i = i2 + 1;
// определяем максимальную длину строки в буфере обмена if (cur_len > max_len) max_len = cur_len; } i2++; }
iBufLines = clipBuf.size(); iMaxWidth = (int)(max_len / 1.3) * cxChar + (max_len >> 1 + 2) * cxCaps; }
// заканчиваем работу с буфером обмена CloseClipboard(); }
#endif
ReleaseDC (hwnd, hdc);
return 0;
case WM_SIZE: cxClient = LOWORD (lParam); cyClient = HIWORD (lParam);
iVscrollMax = max (0, iBufLines + 2 - cyClient / cyChar); iVscrollPos = min (iVscrollPos, iVscrollMax);
SetScrollRange (hwnd, SB_VERT, 0, iVscrollMax, FALSE); SetScrollPos (hwnd, SB_VERT, iVscrollPos, TRUE);
iHscrollMax = max (0, 2 + (iMaxWidth - cxClient) / cxChar); iHscrollPos = min (iHscrollPos, iHscrollMax);
SetScrollRange (hwnd, SB_HORZ, 0, iHscrollMax, FALSE); SetScrollPos (hwnd, SB_HORZ, iHscrollPos, TRUE);
return 0;
case WM_VSCROLL: switch (LOWORD (wParam)) { case SB_TOP: iVscrollInc = -iVscrollPos; break;
case SB_BOTTOM: iVscrollInc = iVscrollMax - iVscrollPos; break;
case SB_LINEUP: iVscrollInc = -1; break;
case SB_LINEDOWN: iVscrollInc = 1; break;
case SB_PAGEUP: iVscrollInc = min (-1, -cyClient / cyChar); break;
case SB_PAGEDOWN: iVscrollInc = max (1, cyClient / cyChar); break;
case SB_THUMBTRACK: iVscrollInc = HIWORD (wParam) - iVscrollPos; break;
default: iVscrollInc = 0; } iVscrollInc = max (-iVscrollPos, min (iVscrollInc, iVscrollMax - iVscrollPos));
if (iVscrollInc!= 0) { iVscrollPos += iVscrollInc; ScrollWindow (hwnd, 0, -cyChar * iVscrollInc, NULL, NULL); SetScrollPos (hwnd, SB_VERT, iVscrollPos, TRUE); UpdateWindow (hwnd); } return 0;
case WM_HSCROLL: switch (LOWORD (wParam)) { case SB_LINEUP: iHscrollInc = -1; break;
case SB_LINEDOWN: iHscrollInc = 1; break;
case SB_PAGEUP: iHscrollInc = -8; break;
case SB_PAGEDOWN: iHscrollInc = 8; break;
case SB_THUMBPOSITION: iHscrollInc = HIWORD (wParam) - iHscrollPos; break;
default: iHscrollInc = 0; } iHscrollInc = max (-iHscrollPos, min (iHscrollInc, iHscrollMax - iHscrollPos));
if (iHscrollInc!= 0) { iHscrollPos += iHscrollInc; ScrollWindow (hwnd, -cxChar * iHscrollInc, 0, NULL, NULL); SetScrollPos (hwnd, SB_HORZ, iHscrollPos, TRUE); } return 0;
case WM_PAINT: hdc = BeginPaint (hwnd, &ps);
iPaintBeg = max (0, iVscrollPos + ps.rcPaint.top / cyChar - 1); iPaintEnd = min (iBufLines, iVscrollPos + ps.rcPaint.bottom / cyChar);
for (i = iPaintBeg; i < iPaintEnd; i++) { x = cxChar * (1 - iHscrollPos); y = cyChar * (1 - iVscrollPos + i);
// вывод строчки из sysmetrics #ifdef VAR0
szBuf = new char[80];
SetTextAlign (hdc, TA_LEFT | TA_TOP); TextOut (hdc, x, y, sysmetrics[i].szLabel, strlen (sysmetrics[i].szLabel)); TextOut (hdc, x + 22 * cxCaps, y, sysmetrics[i].szDesc, strlen (sysmetrics[i].szDesc)); SetTextAlign (hdc, TA_RIGHT | TA_TOP); TextOut (hdc, x + 22 * cxCaps + 40 * cxChar, y, szBuf, wsprintf (szBuf, "%5d", GetSystemMetrics (sysmetrics[i].iIndex)));
delete szBuf;
// вывод строчки из буферированного текстового файла #elif defined VAR1
SetTextAlign (hdc, TA_LEFT | TA_TOP); TextOut (hdc, x, y, fileBuf[i], strlen(fileBuf[i]));
// вывод строчки из буфера обмена #elif defined VAR2
SetTextAlign (hdc, TA_LEFT | TA_TOP); TextOut (hdc, x, y, clipBuf[i], strlen(clipBuf[i]));
#endif }
EndPaint (hwnd, &ps); return 0;
case WM_DESTROY: // удаляем содержимое вектора буфера файла #ifdef VAR1 for (i = 0; i < fileBuf.size(); i++) delete[] fileBuf[i]; fileBuf.clear();
// удаляем содержимое вектора строчек буфера обмена #elif defined VAR2 for (i = 0; i < clipBuf.size(); i++) delete[] clipBuf[i]; clipBuf.clear();
#endif
PostQuitMessage (0); return 0; }
return DefWindowProc (hwnd, iMsg, wParam, lParam); }
#include <windows.h> #include <stdio.h> #include <vector> using namespace std; // выбор варианта лабораторной: VAR0 - пример (вывод массива sysmetrics) // VAR1 - вывод содержимого текстового файла // VAR2 - вывод содержимого буфера обмена #define VAR2 #ifdef VAR0 #define NUMLINES ((int) (sizeof sysmetrics / sizeof sysmetrics [0])) struct { int iIndex; char *szLabel; char *szDesc; } sysmetrics [] = { SM_CXSCREEN, "SM_CXSCREEN", "Screen width in pixels", SM_CYSCREEN, "SM_CYSCREEN", "Screen height in pixels", SM_CXVSCROLL, "SM_CXVSCROLL", "Vertical scroll arrow width", SM_CYHSCROLL, "SM_CYHSCROLL", "Horizontal scroll arrow height", SM_CYCAPTION, "SM_CYCAPTION", "Caption bar height", SM_CXBORDER, "SM_CXBORDER", "Window border width", SM_CYBORDER, "SM_CYBORDER", "Window border height", SM_CXDLGFRAME, "SM_CXDLGFRAME", "Dialog window frame width", SM_CYDLGFRAME, "SM_CYDLGFRAME", "Dialog window frame height", SM_CYVTHUMB, "SM_CYVTHUMB", "Vertical scroll thumb height", SM_CXHTHUMB, "SM_CXHTHUMB", "Horizontal scroll thumb width", SM_CXICON, "SM_CXICON", "Icon width", SM_CYICON, "SM_CYICON", "Icon height", SM_CXCURSOR, "SM_CXCURSOR", "Cursor width", SM_CYCURSOR, "SM_CYCURSOR", "Cursor height", SM_CYMENU, "SM_CYMENU", "Menu bar height", SM_CXFULLSCREEN, "SM_CXFULLSCREEN", "Full screen client area width", SM_CYFULLSCREEN, "SM_CYFULLSCREEN", "Full screen client area height", SM_CYKANJIWINDOW, "SM_CYKANJIWINDOW", "Kanji window height", SM_MOUSEPRESENT, "SM_MOUSEPRESENT", "Mouse present flag", SM_CYVSCROLL, "SM_CYVSCROLL", "Vertical scroll arrow height", SM_CXHSCROLL, "SM_CXHSCROLL", "Horizontal scroll arrow width", SM_DEBUG, "SM_DEBUG", "Debug version flag", SM_SWAPBUTTON, "SM_SWAPBUTTON", "Mouse buttons swapped flag", SM_RESERVED1, "SM_RESERVED1", "Reserved", SM_RESERVED2, "SM_RESERVED2", "Reserved", SM_RESERVED3, "SM_RESERVED3", "Reserved", SM_RESERVED4, "SM_RESERVED4", "Reserved", SM_CXMIN, "SM_CXMIN", "Minimum window width", SM_CYMIN, "SM_CYMIN", "Minimum window height", SM_CXSIZE, "SM_CXSIZE", "Minimize/Maximize icon width", SM_CYSIZE, "SM_CYSIZE", "Minimize/Maximize icon height", SM_CXFRAME, "SM_CXFRAME", "Window frame width", SM_CYFRAME, "SM_CYFRAME", "Window frame height", SM_CXMINTRACK, "SM_CXMINTRACK", "Minimum window tracking width", SM_CYMINTRACK, "SM_CYMINTRACK", "Minimum window tracking height", SM_CXDOUBLECLK, "SM_CXDOUBLECLK", "Double click x tolerance", SM_CYDOUBLECLK, "SM_CYDOUBLECLK", "Double click y tolerance", SM_CXICONSPACING, "SM_CXICONSPACING", "Horizontal icon spacing", SM_CYICONSPACING, "SM_CYICONSPACING", "Vertical icon spacing", SM_MENUDROPALIGNMENT, "SM_MENUDROPALIGNMENT", "Left or right menu drop", SM_PENWINDOWS, "SM_PENWINDOWS", "Pen extensions installed", SM_DBCSENABLED, "SM_DBCSENABLED", "Double-Byte Char Set enabled", SM_CMOUSEBUTTONS, "SM_CMOUSEBUTTONS", "Number of mouse buttons", SM_SHOWSOUNDS, "SM_SHOWSOUNDS", "Present sounds visually" }; #elif defined VAR1 vector<char*> fileBuf; #elif defined VAR2 vector<char*> clipBuf; #endif LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM); Результат:
|