С Новым годом! Форум программистов, компьютерный форум, киберфорум
C/C++: WinAPI
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.57/7: Рейтинг темы: голосов - 7, средняя оценка - 4.57
0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 7

Окно не перерисовывается при разворачивании

02.12.2012, 16:46. Показов 1554. Ответов 8
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Задание
Написать две программы, каждая из которых создает окно. На первом из них должны быть созданы две группы RadioButton. В первой из них имеется выбор из трех цветов: красный, синий, зеленый. Во второй – из четырех типов примитивов: ромб, квадрат, круг, звезда. Также на первом окне должен быть создан Checkbox c надписью «Draw». Информация об изменениях состояния данных Checkbox и RadioButtons должна передаваться во второе окно. При щелчке мышкой по второму окну проверяется переданная информация о состоянии CheckBox. Если он не выбран, ничего не происходит; если он выбран, то в точке щелчка мышки рисуется выбранный во второй группе RadioButtons примитив цветом, выбранным в первой из групп.

само задание я сделал. только вот нету перерисовки при разворачивании. я решил засунуть все фигуры в массив, а когда будет разворачиваться окно, то отрисовать все фигуры из массива. только вот не рисуется((( массив заполнен фигурами, всё норм. не могу понять, почему не отрисовывается. помогите с отрисовкой при развороте. можно любой способ перерисовки.
1е окно
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// GT_HelloWorldWin32.cpp
// compile with: /D_UNICODE /DUNICODE /DWIN32 /D_WINDOWS /c
 
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
 
#define CHECKBOX_DRAW 1
#define RADIOBUTTON_RED_COLOUR 2
#define RADIOBUTTON_BLUE_COLOUR 3
#define RADIOBUTTON_GREEN_COLOUR 4
#define RADIOBUTTON_FIGURE_DIAMOND 5
#define RADIOBUTTON_FIGURE_SQUARE 6
#define RADIOBUTTON_FIGURE_CIRCLE 7
#define RADIOBUTTON_FIGURE_STAR 8
 
static TCHAR szWindowClass[] = _T("1st part");
static TCHAR szTitle[] = _T("1st Part");
 
BYTE isDrawing, colorCode, figureCode;
 
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
 
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    WNDCLASSEX wcex;
 
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
 
    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Win32 Guided Tour"),
            NULL);
 
        return 1;
    }
 
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
        WS_OVERLAPPEDWINDOW & ~(WS_THICKFRAME),
        0, 0,
        178, 158,
        NULL,
        NULL,
        hInstance,
        NULL
    );
 
    //чекбокс
    CreateWindow(
        L"button", L"Draw",
        WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|BS_AUTOCHECKBOX,
        0,0,80,30,
        hWnd,(HMENU)CHECKBOX_DRAW, hInstance, NULL);
 
    // Цвет
    CreateWindow(_T("button"), _T("Red"),
      WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|BS_AUTORADIOBUTTON|
      WS_GROUP,
      0, 30, 80, 30, 
      hWnd, (HMENU)RADIOBUTTON_RED_COLOUR, hInstance, NULL);
   CreateWindow(_T("button"), _T("Blue"),
      WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|BS_AUTORADIOBUTTON,
      0, 60, 80, 30, 
      hWnd, (HMENU)RADIOBUTTON_BLUE_COLOUR, hInstance, NULL);
   CreateWindow(_T("button"), _T("Green"),
      WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|BS_AUTORADIOBUTTON,
      0, 90, 80, 30, 
      hWnd, (HMENU)RADIOBUTTON_GREEN_COLOUR, hInstance, NULL);
   // Примитивы
   CreateWindow(_T("button"), _T("Diamond"),
      WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|BS_AUTORADIOBUTTON|
      WS_GROUP,
      80, 0, 80, 30, 
      hWnd, (HMENU)RADIOBUTTON_FIGURE_DIAMOND, hInstance, NULL);
   CreateWindow(_T("button"), _T("Square"),
      WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|BS_AUTORADIOBUTTON,
      80, 30, 80, 30, 
      hWnd, (HMENU)RADIOBUTTON_FIGURE_SQUARE, hInstance, NULL);
   CreateWindow(_T("button"), _T("Circle"),
      WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|BS_AUTORADIOBUTTON,
      80, 60, 80, 30, 
      hWnd, (HMENU)RADIOBUTTON_FIGURE_CIRCLE, hInstance, NULL);
   CreateWindow(_T("button"), _T("Star"),
      WS_CHILD|WS_VISIBLE|WS_CLIPSIBLINGS|BS_AUTORADIOBUTTON,
      80, 90, 80, 30, 
      hWnd, (HMENU)RADIOBUTTON_FIGURE_STAR, hInstance, NULL);
 
    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Win32 Guided Tour"),
            NULL);
 
        return 1;
    }
 
    ShowWindow(hWnd,
        nCmdShow);
    UpdateWindow(hWnd);
 
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
 
    return (int) msg.wParam;
}
 
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId, wmEvent;
 
    PAINTSTRUCT ps;
    HDC hdc;
    
    UINT code;       // код уведомления
    UINT idCtrl;     // идентификатор дочернего окна
    HWND hChild;      // дескриптор дочернего окна
 
    //copydata message using items
    HWND foundWindow;
    BYTE res[3];
    COPYDATASTRUCT cds;
 
    switch (message)
    {
    case WM_CREATE:
        isDrawing = false;
    case WM_PAINT:
        hdc = BeginPaint(hWnd, &ps);
        EndPaint(hWnd, &ps);
        break;
    case WM_COMMAND:
        code=HIWORD(wParam);       // код уведомления
        idCtrl=LOWORD(wParam);     // идентификатор дочернего окна
        hChild=(HWND)lParam;       // дескриптор дочернего окна
 
        // Получение сообщения о нажатии BN_CLICKED от пары кнопок BS_AUTORADIOBUTTON
            if (code == BN_CLICKED) {
                switch (idCtrl)
                {
                case CHECKBOX_DRAW:
                    isDrawing = !isDrawing;
                    break;
 
                case RADIOBUTTON_RED_COLOUR:
                    colorCode = 1;
                    break;
                case RADIOBUTTON_BLUE_COLOUR:
                    colorCode = 2;
                    break;
                case RADIOBUTTON_GREEN_COLOUR:
                    colorCode = 3;
                    break;
 
                case RADIOBUTTON_FIGURE_DIAMOND:
                    figureCode = 1;
                    break;
                case RADIOBUTTON_FIGURE_SQUARE:
                    figureCode = 2;
                    break;
                case RADIOBUTTON_FIGURE_CIRCLE:
                    figureCode = 3;
                    break;
                case RADIOBUTTON_FIGURE_STAR:
                    figureCode = 4;
                    break;
                }
            }
 
        // Parse the menu selections:
        break;
    case WM_COPYDATA:
        //foundWindow = FindWindow(NULL, L"2ndPart");
        foundWindow = (HWND)wParam;
        if (foundWindow != NULL)
        {
            res[0] = isDrawing;
            res[1] = colorCode;
            res[2] = figureCode;
 
            cds.cbData = sizeof(BYTE)*3;
            cds.lpData = res;
            SendMessage(foundWindow, WM_COPYDATA, 0, (LPARAM)&cds);
        }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }
 
    return 0;
}

2е окно
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <vector>
using namespace std;
 
// Global variables
 
// The main window class name.
static TCHAR szWindowClass[] = _T("2ndpart");
 
// The string that appears in the application's title bar.
static TCHAR szTitle[] = _T("Drawing window");
 
HINSTANCE hInst;
HRGN region;
vector<HRGN> figures;
vector<HBRUSH> brushies;
 
// Forward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
 
//drawing functions
void DrawStar(HWND, HBRUSH);
void DrawDiamond(HWND, HBRUSH);
void DrawSquare(HWND, HBRUSH);
void DrawCircle(HWND, HBRUSH);
 
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    WNDCLASSEX wcex;
 
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
 
    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Win32 Guided Tour"),
            NULL);
 
        return 1;
    }
 
    hInst = hInstance; // Store instance handle in our global variable
 
    // The parameters to CreateWindow explained:
    // szWindowClass: the name of the application
    // szTitle: the text that appears in the title bar
    // WS_OVERLAPPEDWINDOW: the type of window to create
    // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
    // 500, 100: initial size (width, length)
    // NULL: the parent of this window
    // NULL: this application does not have a menu bar
    // hInstance: the first parameter from WinMain
    // NULL: not used in this application
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
        WS_OVERLAPPEDWINDOW & ~(WS_THICKFRAME),
        180, 0,
        320, 240,
        NULL,
        NULL,
        hInstance,
        NULL
    );
 
    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Win32 Guided Tour"),
            NULL);
 
        return 1;
    }
 
    // The parameters to ShowWindow explained:
    // hWnd: the value returned from CreateWindow
    // nCmdShow: the fourth parameter from WinMain
    ShowWindow(hWnd,
        nCmdShow);
    UpdateWindow(hWnd);
 
    // Main message loop:
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
 
    return (int) msg.wParam;
}
 
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    RECT rect;
    int store;
    bool isDraw = false;
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;
    BYTE *res;
 
    //cap for messaging
    bool cap;
    COPYDATASTRUCT cds;
    cds.cbData = sizeof(bool);
    cds.lpData = &cap;
 
    COPYDATASTRUCT* resCDS;
    HBRUSH coloredBrush;
    static int shapeMultiplier = 6;
    HRGN region;
    POINT mouseCoords;
    POINT* pointArray;
    HWND findWindow;
 
    switch (message)
    {
    case WM_RBUTTONDOWN:
        InvalidateRect(hWnd, NULL, true);
        break;
    case WM_LBUTTONDOWN:
        findWindow = FindWindow(NULL, _T("1st part"));
        if (findWindow != NULL)
            SendMessage(findWindow, WM_COPYDATA, (WPARAM)hWnd, (LPARAM)&cds);
        break;
    case WM_COPYDATA:
        resCDS = (COPYDATASTRUCT*)lParam;
        res = (BYTE*)resCDS->lpData;
        if (res[0] == 1)
        {
            isDraw = true;
            switch (res[1])
            {
            case 1:
                coloredBrush = CreateSolidBrush(RGB(255,0,0));
                break;
            case 2:
                coloredBrush = CreateSolidBrush(RGB(0,0,255));
                break;
            case 3:
                coloredBrush = CreateSolidBrush(RGB(0,255,0));
                break;
            }
            
            switch (res[2])
            {
            case 1:
                DrawDiamond(hWnd,coloredBrush);
                break;
            case 2:
                DrawSquare(hWnd, coloredBrush);
                break;
            case 3:
                DrawCircle(hWnd, coloredBrush); 
                break;
            case 4:
                DrawStar(hWnd, coloredBrush);
                break;
            }
 
            DeleteObject(coloredBrush);
        }
        break;
    case WM_SIZE:
        hdc = GetDC(hWnd);
        if(figures.size() != 0)
        {
            for(int i = 0; i < figures.size(); i++)
                FillRgn(hdc, figures[i], brushies[i]);
        }
        ReleaseDC(hWnd, hdc);
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }
 
    return 0;
}
 
void DrawDiamond(HWND hWnd, HBRUSH coloredBrush)
{
    static int shapeMultiplier = 6;
    POINT mouseCoords;
    POINT* pointArray;
 
    GetCursorPos(&mouseCoords);
    ScreenToClient(hWnd, &mouseCoords);
 
    pointArray = (POINT*)malloc(sizeof(POINT)*5);
                
    pointArray[0].x = mouseCoords.x;
    pointArray[0].y = mouseCoords.y + shapeMultiplier*3;
                
    pointArray[1].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[1].y = mouseCoords.y;
                
    pointArray[2].x = mouseCoords.x;
    pointArray[2].y = mouseCoords.y - shapeMultiplier*3;
 
    pointArray[3].x = mouseCoords.x - shapeMultiplier*2;
    pointArray[3].y = mouseCoords.y;
 
    pointArray[4].x = mouseCoords.x;
    pointArray[4].y = mouseCoords.y + shapeMultiplier*3;
 
    region = CreatePolygonRgn(pointArray, (int)5, WINDING);
    figures.push_back(region);
    brushies.push_back(coloredBrush);
 
    HDC hdc = GetDC(hWnd);
    FillRgn(hdc, region, coloredBrush);
    ReleaseDC(hWnd, hdc);
}
 
void DrawSquare(HWND hWnd, HBRUSH coloredBrush)
{
    static int shapeMultiplier = 6;
    HRGN region;
    POINT mouseCoords;
    POINT* pointArray;
 
    GetCursorPos(&mouseCoords);
    ScreenToClient(hWnd, &mouseCoords);
 
    pointArray = (POINT*)malloc(sizeof(POINT)*5);
                
    pointArray[0].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[0].y = mouseCoords.y + shapeMultiplier*2;
                
    pointArray[1].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[1].y = mouseCoords.y - shapeMultiplier*2;
        
    pointArray[2].x = mouseCoords.x - shapeMultiplier*2;
    pointArray[2].y = mouseCoords.y - shapeMultiplier*2;
 
    pointArray[3].x = mouseCoords.x - shapeMultiplier*2;
    pointArray[3].y = mouseCoords.y + shapeMultiplier*2;
    
    pointArray[4].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[4].y = mouseCoords.y + shapeMultiplier*2;
 
    region = CreatePolygonRgn(pointArray, (int)5, WINDING);
    figures.push_back(region);
    brushies.push_back(coloredBrush);
 
    HDC hdc = GetDC(hWnd);
    FillRgn(hdc, region, coloredBrush);
    ReleaseDC(hWnd, hdc);
}
 
void DrawCircle(HWND hWnd, HBRUSH coloredBrush)
{
    static int shapeMultiplier = 6;
    HRGN region;
    POINT mouseCoords;
    POINT* pointArray;
 
    GetCursorPos(&mouseCoords);
    ScreenToClient(hWnd, &mouseCoords);
 
    region = CreateEllipticRgn(mouseCoords.x - shapeMultiplier*2, 
    mouseCoords.y - shapeMultiplier*2, mouseCoords.x + shapeMultiplier*2, 
    mouseCoords.y + shapeMultiplier*2);
    figures.push_back(region);
    brushies.push_back(coloredBrush);
 
    HDC hdc = GetDC(hWnd);
    FillRgn(hdc, region, coloredBrush);
    ReleaseDC(hWnd, hdc);
}
 
void DrawStar(HWND hWnd, HBRUSH coloredBrush)
{
    static int shapeMultiplier = 6;
    HRGN region;
    POINT mouseCoords;
    POINT* pointArray;
 
    GetCursorPos(&mouseCoords);
    ScreenToClient(hWnd, &mouseCoords);
 
    pointArray = (POINT*)malloc(sizeof(POINT)*11);
                
    pointArray[0].x = mouseCoords.x;
    pointArray[0].y = mouseCoords.y - shapeMultiplier*2;
    
    pointArray[1].x = mouseCoords.x + shapeMultiplier;
    pointArray[1].y = mouseCoords.y;
                
    pointArray[2].x = mouseCoords.x + shapeMultiplier*3;
    pointArray[2].y = mouseCoords.y;
 
    pointArray[3].x = mouseCoords.x + shapeMultiplier;
    pointArray[3].y = mouseCoords.y + shapeMultiplier;
 
    pointArray[4].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[4].y = mouseCoords.y + shapeMultiplier*4;
 
    pointArray[5].x = mouseCoords.x;
    pointArray[5].y = mouseCoords.y + shapeMultiplier*2;
 
    pointArray[6].x = mouseCoords.x - shapeMultiplier*2;
    pointArray[6].y = mouseCoords.y + shapeMultiplier*4;
                
    pointArray[7].x = mouseCoords.x - shapeMultiplier;
    pointArray[7].y = mouseCoords.y + shapeMultiplier;
                
    pointArray[8].x = mouseCoords.x - shapeMultiplier*3;
    pointArray[8].y = mouseCoords.y;
 
    pointArray[9].x = mouseCoords.x - shapeMultiplier;
    pointArray[9].y = mouseCoords.y;
 
    pointArray[10].x = mouseCoords.x;
    pointArray[10].y = mouseCoords.y - shapeMultiplier*2;
 
    region = CreatePolygonRgn(pointArray, (int)11, WINDING);
    figures.push_back(region);
    brushies.push_back(coloredBrush);
 
    HDC hdc = GetDC(hWnd);
    FillRgn(hdc, region, coloredBrush);
    ReleaseDC(hWnd, hdc);
}


Добавлено через 14 часов 50 минут
неужели никто не может помочь с отрисовкой при разворачивании. нужно, чтоб содержимое окна не пропадало
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
02.12.2012, 16:46
Ответы с готовыми решениями:

Не могу реализовать мигание текста, окно не перерисовывается
Помогите реализовать перерисовку окна через каждые 0,5 секунд. #define WIN32_LEAN_AND_MEAN #include&lt;windows.h&gt; ...

MFC. Окно не перерисовывается
Здравствуйте! Пишу мега-программу &quot;Отслеживание пробега мыши&quot;;) afx_msg void FrameWnd::OnMouseMove(UINT nFlags, CPoint point) { ...

Баг при разворачивании окна
Мне необходимо создать окно определённого размера без возможности развернуть его на весь экран и без стандратной системной рамки. Я делаю...

8
Супер-модератор
Эксперт Pascal/DelphiАвтор FAQ
 Аватар для volvo
33371 / 21497 / 8234
Регистрация: 22.10.2011
Сообщений: 36,893
Записей в блоге: 12
02.12.2012, 17:02
Цитата Сообщение от rpo6oBLLLuK Посмотреть сообщение
не могу понять, почему не отрисовывается.
Только я не вижу WM_PAINT в функции окна второй формы, или его там на самом деле нет? Вот поэтому и не отрисовывается.
0
0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 7
02.12.2012, 18:17  [ТС]
есть WM_SIZE, срабатывающее при разворачивании
0
Супер-модератор
Эксперт Pascal/DelphiАвтор FAQ
 Аватар для volvo
33371 / 21497 / 8234
Регистрация: 22.10.2011
Сообщений: 36,893
Записей в блоге: 12
02.12.2012, 18:24
А WM_SIZE никого не интересует. Рисуется окно не по WM_SIZE, а по WM_PAINT.
0
0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 7
02.12.2012, 18:30  [ТС]
Цитата Сообщение от UI Посмотреть сообщение
А WM_SIZE никого не интересует. Рисуется окно не по WM_SIZE, а по WM_PAINT.
если разворачиваю, то срабатывает wm_size и выполняет свой блок кода. какая разница, сработает блок в wm_paint или wm_size. тут что-то в блоке кода не то.
0
6 / 6 / 0
Регистрация: 14.10.2012
Сообщений: 36
02.12.2012, 23:14
А после при перерисовке твоему окну посылается WM_PAINT, обработки которого нет... Я бы на твоем месте прислушался к дельному совету.
0
0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 7
02.12.2012, 23:31  [ТС]
Цитата Сообщение от Ryzhikov_A Посмотреть сообщение
А после при перерисовке твоему окну посылается WM_PAINT, обработки которого нет... Я бы на твоем месте прислушался к дельному совету.
так каким образом сделать рисование. ведь при получении получении информации из певого окна генерируется WM_COPYDATA во 2м окне. как с WM_PAINT связать?
тогда поставлю вопрос немного по другому. как вообще сделать рисование во 2м окне?
0
0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 7
04.12.2012, 00:34  [ТС]
изменил второе окно. толку 0.
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
#include <windows.h>
#include <stdlib.h>
#include <string.h>
#include <tchar.h>
#include <vector>
using namespace std;
 
// Global variables
 
// The main window class name.
static TCHAR szWindowClass[] = _T("2ndpart");
 
// The string that appears in the application's title bar.
static TCHAR szTitle[] = _T("Drawing window");
 
HINSTANCE hInst;
HRGN region;
vector<HRGN> figures;
vector<HBRUSH> brushies;
 
// Forward declarations of functions included in this code module:
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
 
//drawing functions
HRGN Star(HWND, HBRUSH);
HRGN Diamond(HWND, HBRUSH);
HRGN Square(HWND, HBRUSH);
HRGN Circle(HWND, HBRUSH);
 
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    WNDCLASSEX wcex;
 
    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
 
    if (!RegisterClassEx(&wcex))
    {
        MessageBox(NULL,
            _T("Call to RegisterClassEx failed!"),
            _T("Win32 Guided Tour"),
            NULL);
 
        return 1;
    }
 
    hInst = hInstance; // Store instance handle in our global variable
 
    // The parameters to CreateWindow explained:
    // szWindowClass: the name of the application
    // szTitle: the text that appears in the title bar
    // WS_OVERLAPPEDWINDOW: the type of window to create
    // CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
    // 500, 100: initial size (width, length)
    // NULL: the parent of this window
    // NULL: this application does not have a menu bar
    // hInstance: the first parameter from WinMain
    // NULL: not used in this application
    HWND hWnd = CreateWindow(
        szWindowClass,
        szTitle,
        WS_OVERLAPPEDWINDOW & ~(WS_THICKFRAME),
        180, 0,
        320, 240,
        NULL,
        NULL,
        hInstance,
        NULL
    );
 
    if (!hWnd)
    {
        MessageBox(NULL,
            _T("Call to CreateWindow failed!"),
            _T("Win32 Guided Tour"),
            NULL);
 
        return 1;
    }
 
    // The parameters to ShowWindow explained:
    // hWnd: the value returned from CreateWindow
    // nCmdShow: the fourth parameter from WinMain
    ShowWindow(hWnd,
        nCmdShow);
    UpdateWindow(hWnd);
 
    // Main message loop:
    MSG msg;
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
 
    return (int) msg.wParam;
}
 
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    RECT rect;
    int wmId, wmEvent;
    PAINTSTRUCT ps;
    HDC hdc;
    BYTE *res;
 
    //cap for messaging
    bool cap;
    COPYDATASTRUCT cds;
    cds.cbData = sizeof(bool);
    cds.lpData = &cap;
 
    COPYDATASTRUCT* resCDS;
    HBRUSH coloredBrush;
    POINT* pointArray;
    HWND findWindow;
 
    switch (message)
    {
    case WM_RBUTTONDOWN:
        figures.clear();
        brushies.clear();
        InvalidateRect(hWnd, NULL, true);
        break;
    case WM_LBUTTONDOWN:
        findWindow = FindWindow(NULL, _T("1st part"));
        if (findWindow != NULL)
            SendMessage(findWindow, WM_COPYDATA, (WPARAM)hWnd, (LPARAM)&cds);
        break;
    case WM_COPYDATA:
        resCDS = (COPYDATASTRUCT*)lParam;
        res = (BYTE*)resCDS->lpData;
        if (res[0] == 1)
        {
            switch (res[1])
            {
            case 1:
                coloredBrush = CreateSolidBrush(RGB(255,0,0));
                break;
            case 2:
                coloredBrush = CreateSolidBrush(RGB(0,0,255));
                break;
            case 3:
                coloredBrush = CreateSolidBrush(RGB(0,255,0));
                break;
            }
 
            brushies.push_back(coloredBrush);
            
            switch (res[2])
            {
            case 1:
                figures.push_back(Diamond(hWnd,coloredBrush));
                break;
            case 2:
                figures.push_back(Square(hWnd, coloredBrush));
                break;
            case 3:
                figures.push_back(Circle(hWnd, coloredBrush)); 
                break;
            case 4:
                figures.push_back(Star(hWnd, coloredBrush));
                break;
            }
 
            DeleteObject(coloredBrush);
            InvalidateRect(hWnd, NULL, TRUE);
        }
        break;
    case WM_PAINT:
        if(figures.size() != 0 && brushies.size() != 0)
        {   
            hdc = GetDC(hWnd);
            for(int i = 0; i < figures.size(); i++)
                FillRgn(hdc, figures[i], brushies[i]);
            ReleaseDC(hWnd, hdc);
        }
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
        break;
    }
 
    return 0;
}
 
HRGN Diamond(HWND hWnd, HBRUSH coloredBrush)
{
    static int shapeMultiplier = 6;
    POINT mouseCoords;
    POINT* pointArray;
 
    GetCursorPos(&mouseCoords);
    ScreenToClient(hWnd, &mouseCoords);
 
    pointArray = (POINT*)malloc(sizeof(POINT)*5);
                
    pointArray[0].x = mouseCoords.x;
    pointArray[0].y = mouseCoords.y + shapeMultiplier*3;
                
    pointArray[1].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[1].y = mouseCoords.y;
                
    pointArray[2].x = mouseCoords.x;
    pointArray[2].y = mouseCoords.y - shapeMultiplier*3;
 
    pointArray[3].x = mouseCoords.x - shapeMultiplier*2;
    pointArray[3].y = mouseCoords.y;
 
    pointArray[4].x = mouseCoords.x;
    pointArray[4].y = mouseCoords.y + shapeMultiplier*3;
 
    region = CreatePolygonRgn(pointArray, (int)5, WINDING);
 
    return region;
}
 
HRGN Square(HWND hWnd, HBRUSH coloredBrush)
{
    static int shapeMultiplier = 6;
    HRGN region;
    POINT mouseCoords;
    POINT* pointArray;
 
    GetCursorPos(&mouseCoords);
    ScreenToClient(hWnd, &mouseCoords);
 
    pointArray = (POINT*)malloc(sizeof(POINT)*5);
                
    pointArray[0].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[0].y = mouseCoords.y + shapeMultiplier*2;
                
    pointArray[1].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[1].y = mouseCoords.y - shapeMultiplier*2;
        
    pointArray[2].x = mouseCoords.x - shapeMultiplier*2;
    pointArray[2].y = mouseCoords.y - shapeMultiplier*2;
 
    pointArray[3].x = mouseCoords.x - shapeMultiplier*2;
    pointArray[3].y = mouseCoords.y + shapeMultiplier*2;
    
    pointArray[4].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[4].y = mouseCoords.y + shapeMultiplier*2;
 
    region = CreatePolygonRgn(pointArray, (int)5, WINDING);
    
    return region;
}
 
HRGN Circle(HWND hWnd, HBRUSH coloredBrush)
{
    static int shapeMultiplier = 6;
    HRGN region;
    POINT mouseCoords;
    POINT* pointArray;
 
    GetCursorPos(&mouseCoords);
    ScreenToClient(hWnd, &mouseCoords);
 
    region = CreateEllipticRgn(mouseCoords.x - shapeMultiplier*2, 
    mouseCoords.y - shapeMultiplier*2, mouseCoords.x + shapeMultiplier*2, 
    mouseCoords.y + shapeMultiplier*2);
    
    return region;
}
 
HRGN Star(HWND hWnd, HBRUSH coloredBrush)
{
    static int shapeMultiplier = 6;
    HRGN region;
    POINT mouseCoords;
    POINT* pointArray;
 
    GetCursorPos(&mouseCoords);
    ScreenToClient(hWnd, &mouseCoords);
 
    pointArray = (POINT*)malloc(sizeof(POINT)*11);
                
    pointArray[0].x = mouseCoords.x;
    pointArray[0].y = mouseCoords.y - shapeMultiplier*2;
    
    pointArray[1].x = mouseCoords.x + shapeMultiplier;
    pointArray[1].y = mouseCoords.y;
                
    pointArray[2].x = mouseCoords.x + shapeMultiplier*3;
    pointArray[2].y = mouseCoords.y;
 
    pointArray[3].x = mouseCoords.x + shapeMultiplier;
    pointArray[3].y = mouseCoords.y + shapeMultiplier;
 
    pointArray[4].x = mouseCoords.x + shapeMultiplier*2;
    pointArray[4].y = mouseCoords.y + shapeMultiplier*4;
 
    pointArray[5].x = mouseCoords.x;
    pointArray[5].y = mouseCoords.y + shapeMultiplier*2;
 
    pointArray[6].x = mouseCoords.x - shapeMultiplier*2;
    pointArray[6].y = mouseCoords.y + shapeMultiplier*4;
                
    pointArray[7].x = mouseCoords.x - shapeMultiplier;
    pointArray[7].y = mouseCoords.y + shapeMultiplier;
                
    pointArray[8].x = mouseCoords.x - shapeMultiplier*3;
    pointArray[8].y = mouseCoords.y;
 
    pointArray[9].x = mouseCoords.x - shapeMultiplier;
    pointArray[9].y = mouseCoords.y;
 
    pointArray[10].x = mouseCoords.x;
    pointArray[10].y = mouseCoords.y - shapeMultiplier*2;
 
    region = CreatePolygonRgn(pointArray, (int)11, WINDING);
    
    return region;
}
0
0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 7
07.12.2012, 00:04  [ТС]
проблему я решил. спасибо всем за "помощь"
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
07.12.2012, 00:04
Помогаю со студенческими работами здесь

Канва самоочищается при сворачивании-разворачивании
На канве Form1.Canvas нарисовано какое то кол-во shape и линий, если свернуть развернуть окно приложения - то все линии исчезают, shape...

Ошибка при сворачивании-разворачивании игры
Если сворачиваю окно игры, а потом разворачиваю снова, то в этой строке: device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer,...

Масштабирование рисунка при разворачивании формы
Я столкнулся с проблемой в C#.Я например, нарисовал пингвина, он находиться в левом углу. Как сделать так, чтобы когда разворачиваешь окно...

Анимация при сворачивании/разворачивании формы
Собственно из темы всё ясно. Может кто поделится? Нужен триггер типа такого: &lt;EventTrigger...

Что происходит при разворачивании формы?
Здравствуйте! Какие методы выполняются при сворачивании/разворачивании формы? Проблема состоит в том, что в самой форме, у меня...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
9
Ответ Создать тему
Новые блоги и статьи
Изучаю kubernetes
lagorue 13.01.2026
А пригодятся-ли мне знания kubernetes в России?
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru