'' Start
'#DEFINE WIN_INCLUDEALL
#Include Once "windows.bi"
#Include Once "crt.bi"
#Include Once "win/commctrl.bi"
#Include Once "win/commdlg.bi"
#Include Once "Resources.h"
Dim Shared As InitCommonControlsEx iBaresx = (Len(InitCommonControlsEx),ICC_BAR_CLASSES):InitCommonControlsEx(@iBaresx)

'' names of window classes.
Const szAppName = "VectoreR"

'' function prototypes.
Declare Function message_loop As Integer
Declare Sub register_classes
Declare Function WndMain	(ByVal MainForm As HWND, ByVal uMsg As UINT, ByVal wParam As WPARAM, ByVal lParam As LPARAM) As LRESULT
Declare Function WndPalette(ByVal PaletteForm As HWND, ByVal uMsg As UINT, ByVal wParam As WPARAM, ByVal lParam As LPARAM)	As LRESULT
Declare Function WndHolst	(ByVal HolstForm As HWND, ByVal uMsg As UINT, ByVal wParam As WPARAM, ByVal lParam As LPARAM)	As LRESULT
Declare Function WndList	(ByVal ListForm As HWND, ByVal uMsg As UINT, ByVal wParam As WPARAM, ByVal lParam As LPARAM)	As LRESULT
Declare Sub RepaintBack
Declare Sub Selecting(ByVal X As Integer,ByVal Y As Integer)
Declare Sub RepaintDyn(ByVal xDown As Integer,ByVal yDown As Integer,ByVal xMove As Integer,ByVal yMove As Integer)

'' global data.
Dim Shared hModule As HINSTANCE
Dim Shared MainForm As HWND
Dim Shared ListBox2 As HWND ' хэндл ListBox
Dim Shared StatusBar3 As HWND ' хэндл StatusBar

Dim Shared As HWND				hwndMain,hwndToolBar,hwndStatusBar,hwndPalette,hwndList,hwndHolst	'' дескрипторы окон
Dim Shared As HMENU				hMenu

Dim Shared As String *256		szBuf
Dim Shared As String *10		szCount

Dim Shared As Integer			status,iCount,i,j											'' статус выборки, число примитивов,i,j
Dim Shared As Integer			tekI,tekJ											'' текущая ячейка
Dim Shared As Integer			NUndo

Dim Shared As COLORREF			crPalCol(13,1)											'' таблица цветов палитры
Dim Shared As COLORREF			crCurUp
Dim Shared As COLORREF			crCurDown													'' два цвета - верхний и нижний
Dim Shared As WNDPROC			OldWndList													'' адрес перехваченной процедуры


Dim Shared As HDC					hdcMemPalette,hdcMemHolstBack,hdcMemHolstDyn				'' контексты памяти
Dim Shared As HDC					hdcPalette,hdcHolst										'' контексты дисплея
Dim Shared As HPEN				hSelectPen,hPen,hPenD,hPenL								'' перья
Dim Shared As HBRUSH				hSelectBrush,hBrush										'' кисти

Dim Shared As BOOL				LightOn,IsUpColor,IsName

''нектороые координаты элементов окна ''/
Dim Shared As Integer 			PaletteTop,ListTop,HolstTop,HolstLeft,Otstup

'///////////////////////////////// РАЗРИСОВКА ПАЛИТРЫ ///////////////////////////////////////////////
Function RisPal As Integer
	DeleteObject(hBrush)									'' уничтожить кисть
	hBrush = CreateSolidBrush(crCurDown)					'' создать кисть на основе нижнего цвета
	SelectObject(hdcMemPalette,hBrush)						'' выбрать кисть
	SelectObject(hdcMemPalette,GetStockObject(NULL_PEN))	'' выбрать пустое перо
	Rectangle(hdcMemPalette,13,14,25,26)					'' нарисовать нижний квадрат

	SelectObject(hdcMemPalette,hPenD)						'' выбрать перо
	MoveToEx(hdcMemPalette,18,6,NULL)						'' поместить перо
	LineTo(hdcMemPalette,18,19)							'' правая линия
	LineTo(hdcMemPalette,4,19)								'' нижняя линия
	SelectObject(hdcMemPalette,GetStockObject(WHITE_PEN))	'' выбрать белое перо
	LineTo(hdcMemPalette,4,5)								'' левая линия
	LineTo(hdcMemPalette,19,5)								'' верхняя линия

	DeleteObject(hBrush)									'' уничтожить кисть
	hBrush	= CreateSolidBrush(crCurUp)					'' создать кисть на основе верхнего цвета
	SelectObject(hdcMemPalette,hPenL)						'' выбрать светлое перо
	SelectObject(hdcMemPalette,hBrush)						'' выбрать кисть
	Rectangle(hdcMemPalette,5,6,18,19)						'' нарисовать верхний квадрат

	For i=0 To 13
		For j=0 To 1
			DeleteObject(hBrush)									'' удалить кисть
			hBrush		= CreateSolidBrush(crPalCol(i,j))			'' создать новую кисть
			SelectObject(hdcMemPalette,GetStockObject(NULL_PEN))	'' выбрать прозращное перо
			SelectObject(hdcMemPalette,hBrush)						'' выбрать верхнюю кисть
			Rectangle(hdcMemPalette,i * 16 +33,j * 16 +2,i * 16 + 46,j * 16+15) '' нарисовать клетку
		Next j
	Next i

	InvalidateRect(hwndPalette,NULL,FALSE)						'' перерисовка без стирания

End Function
'///////////////////////////////////////////////////////////////////////////////////////////////////

Function MinCoordOf2(ByVal c1 As Integer, ByVal c2 As Integer) As Integer
	If (c1<c2) Then
		Return c1
	Else
		Return c2
	EndIf
End Function


Function MaxCoordOf2(ByVal c1 As Integer, ByVal c2 As Integer) As Integer
	If (c1>c2) Then
		Return c1
	Else
		Return c2
	EndIf
End Function


Function HexToInt(ByVal X As String) As Integer
	Select Case X
		Case "0":	Return 0
		Case "1":	Return 1
		Case "2":	Return 2
		Case "3":	Return 3
		Case "4":	Return 4
		Case "5":	Return 5
		Case "6":	Return 6
		Case "7":	Return 7
		Case "8":	Return 8
		Case "9":	Return 9
		Case "A":	Return 10
		Case "B":	Return 11
		Case "C":	Return 12
		Case "D":	Return 13
		Case "E":	Return 14
		Case "F":	Return 15
	End Select
	Return 1
End Function

Function HexSzToInt(ByVal szCountX As String) As Integer				'/ + быстрое возведение в степень
	Dim As Integer rez, tek, n
	For n = 0 To 5
		tek = HexToInt(Chr(szCountX[n]))
		Select Case n
			Case 5:rez=rez+tek
			Case 4:rez=rez+tek*16
			Case 3:rez=rez+tek*256
			Case 2:rez=rez+tek*4096
			Case 1:rez=rez+tek*65536
			Case 0:rez=rez+tek*1048576
		End Select
	Next n
	Return rez
End Function

Function RecountCoord As Integer
	Dim As RECT	rrr

	PaletteTop = 2
	HolstTop = 2
	ListTop = 2
	HolstLeft = 0
	Otstup = 2

	If (IsWindowVisible(hwndToolBar)) Then
		PaletteTop = 33
		HolstTop = 33
		ListTop = 33
	EndIf

	If (IsWindowVisible(hwndPalette)) Then ListTop = ListTop + 39

	If ((IsWindowVisible(hwndPalette)) Or (IsWindowVisible(hwndList))) Then
		HolstLeft = 264
	Else
		HolstLeft = 3
	EndIf

	If (IsWindowVisible(hwndStatusBar)) Then
		Otstup = 20
	Else
		Otstup = 2
	EndIf


	GetClientRect(hwndMain,@rrr)
	SendMessage(hwndMain,WM_SIZE,0,MAKELPARAM(rrr.right,rrr.bottom))
	InvalidateRect(hwndMain,0,TRUE)

	Return 0
End Function



'' main code.
hModule=GetModuleHandle(NULL)
register_classes
MainForm = CreateWindowEx (NULL, szAppName, "VectoreR", WS_VISIBLE Or WS_OVERLAPPEDWINDOW, 0, 0, 1100, 800, NULL, NULL, hModule, NULL)
ShowWindow(MainForm, SW_SHOW)
UpdateWindow(MainForm)
End message_loop

''message loop.
Function message_loop As Integer
	Dim wMsg As MSG
	Do 'цикл сообщений
		If PeekMessage( @wMsg, NULL, 0, 0, PM_REMOVE) <> 0 Then
			If wMsg.message = WM_QUIT Then Exit Do
			TranslateMessage( @wMsg )
			DispatchMessage( @wMsg )
		Else
			SleepEx(1,0)
		EndIf
	Loop
	Return wMsg.wParam
End Function

''' window procedure #1 ["Form"].
Function WndMain (ByVal MainForm As HWND, ByVal uMsg As UINT, ByVal wParam As WPARAM, ByVal lParam As LPARAM) As LRESULT
	Function = 0

	'// переменные тулбара
	Static As DWORD			dwStyle		'//стиль тулбара
	Static As TBADDBITMAP 	tb				'//расположение битмапа
	Static As TBBUTTON		tbButton(11)	'//массив кнопок

	'// переменные статусбара
	Static As RECT			rect
	Static ptWidth(3) As Integer ={0,0,0}			'таблица ширин статусбара

	'// переменные листбокса
	Static As HFONT		hFont								' шрифт для ListBox'а

	'// переменные файлового диалога
	Static ofn As OPENFILENAME
	Static As ZString*128 szFilter
	szFilter	=	"VCT Files (*.vct)"+Chr(0)+"*.vct"+Chr(0)+"All Files (*.*)"+Chr(0)+"*.*"+Chr(0)
	Static szFullFileName As ZString *256
	szFullFileName = Chr(0)
	Static szFileName As ZString *256
	szFileName = Chr(0)
	Static fp As FILE Ptr

	'// переменные цветового диалога
	Static crCustColor(16) As COLORREF 											'// таблица цветов для пал. диалога
	Static clr As ChooseColor															'// структура для пал. диалога

	'// другие переменные
	Static As HBITMAP			hBitmap,hBitmapHolstBack,hBitmapHolstDyn					'// картинки
	Static As NMHDR Ptr			pnmh
	Static As String Ptr			pReply
	Static As TOOLTIPTEXT Ptr  lpttt

	Select Case uMsg
		Case WM_CREATE

			'///////////////////// СОЗДАЕМ ТУЛБАР ////////////////////////
			dwStyle =	WS_CHILD Or WS_VISIBLE Or WS_DLGFRAME Or CCS_TOP Or CCS_NORESIZE Or TBSTYLE_TOOLTIPS Or TBSTYLE_FLAT
			tb.hInst	=hModule			'//текущее приложение
			tb.nID		=IDB_TOOLBAR				'//номер битмапа в ресурсах

			tbButton(0).iBitmap			= ID_NEW
			tbButton(0).idCommand		= IDM_NEW
			tbButton(0).fsState			= TBSTATE_ENABLED
			tbButton(0).fsStyle			= TBSTYLE_BUTTON
			tbButton(0).dwData			= 0
			tbButton(0).iString			= 0
			tbButton(1).iBitmap			= ID_OPEN
			tbButton(1).idCommand		= IDM_OPEN
			tbButton(1).fsState			= TBSTATE_ENABLED
			tbButton(1).fsStyle			= TBSTYLE_BUTTON
			tbButton(1).dwData			= 0
			tbButton(1).iString			= 0
			tbButton(2).iBitmap			= ID_SAVE
			tbButton(2).idCommand		= IDM_SAVE
			tbButton(2).fsState			= TBSTATE_ENABLED
			tbButton(2).fsStyle			= TBSTYLE_BUTTON
			tbButton(2).dwData			= 0
			tbButton(2).iString			= 0
			tbButton(3).iBitmap			= ID_INFO
			tbButton(3).idCommand		= IDM_HELP
			tbButton(3).fsState			= TBSTATE_ENABLED
			tbButton(3).fsStyle			= TBSTYLE_BUTTON
			tbButton(3).dwData			= 0
			tbButton(3).iString			= 0
			tbButton(4).iBitmap			= 0
			tbButton(4).idCommand		= 1
			tbButton(4).fsState			= TBSTATE_ENABLED
			tbButton(4).fsStyle			= TBSTYLE_SEP
			tbButton(4).dwData			= 0
			tbButton(4).iString			= 0
			tbButton(5).iBitmap			= ID_RGB
			tbButton(5).idCommand		= TB_ID_RGB
			tbButton(5).fsState			= TBSTATE_ENABLED
			tbButton(5).fsStyle			= TBSTYLE_BUTTON
			tbButton(5).dwData			= 0
			tbButton(5).iString			= 0
			tbButton(6).iBitmap			= 0
			tbButton(6).idCommand		= 1
			tbButton(6).fsState			= TBSTATE_ENABLED
			tbButton(6).fsStyle			= TBSTYLE_SEP
			tbButton(6).dwData			= 0
			tbButton(6).iString			= 0
			tbButton(7).iBitmap			= ID_ARROW
			tbButton(7).idCommand		= TB_ID_ARROW
			tbButton(7).fsState			= TBSTATE_ENABLED
			tbButton(7).fsStyle			= TBSTYLE_BUTTON
			tbButton(7).dwData			= 0
			tbButton(7).iString			= 0
			tbButton(8).iBitmap			= ID_LINE
			tbButton(8).idCommand		= TB_ID_LINE
			tbButton(8).fsState			= TBSTATE_ENABLED
			tbButton(8).fsStyle			= TBSTYLE_BUTTON
			tbButton(8).dwData			= 0
			tbButton(8).iString			= 0
			tbButton(9).iBitmap			= ID_RECTANGLE
			tbButton(9).idCommand		= TB_ID_RECTANGLE
			tbButton(9).fsState			= TBSTATE_ENABLED
			tbButton(9).fsStyle			= TBSTYLE_BUTTON
			tbButton(9).dwData			= 0
			tbButton(9).iString			= 0
			tbButton(10).iBitmap			= ID_CIRCLE
			tbButton(10).idCommand		= TB_ID_CIRCLE
			tbButton(10).fsState			= TBSTATE_ENABLED
			tbButton(10).fsStyle			= TBSTYLE_BUTTON
			tbButton(10).dwData			= 0
			tbButton(10).iString			= 0
			hwndToolBar = CreateWindowEx	(0,TOOLBARCLASSNAME,NULL,dwStyle,0,0,0,0,MainForm,CPtr(HMENU,2),hModule,NULL)
			If (hwndToolBar = NULL) Then Return FALSE
			SendMessage(hwndToolBar,TB_BUTTONSTRUCTSIZE,Cast(WPARAM, SizeOf(TBBUTTON)),0)
			SendMessage(hwndToolBar, TB_ADDBITMAP, 11, Cast(LPARAM,@tb))
			SendMessage(hwndToolBar, TB_ADDBUTTONS, 11, Cast(LPARAM,@tbButton(0)))
			SendMessage(hwndToolBar, TB_SETBITMAPSIZE, 0, MAKELONG(20, 20))
			SendMessage(hwndToolBar, TB_SETBUTTONSIZE, 0, MAKELONG(20, 20))
			SendMessage(hwndToolBar,TB_CHECKBUTTON,Cast(WPARAM,TB_ID_ARROW),TRUE)
			SendMessage(hwndToolBar,TB_ENABLEBUTTON,Cast(WPARAM,IDM_SAVE),FALSE)


			'///////////////////// СОЗДАЕМ СТАТУСБАР /////////////////////  or WS_CLIPSIBLINGS
			dwStyle		= WS_CHILD Or WS_VISIBLE Or SBARS_SIZEGRIP Or CCS_NORESIZE
			hwndStatusBar = CreateWindowEx(0,"msCtls_StatusBar32",NULL,dwStyle,0,0,0,0,MainForm,CPtr(HMENU,4),hModule,NULL)
			If (hwndStatusBar = NULL) Then Return FALSE
			SendMessage(hwndStatusBar , WM_SETFONT, Cast(WPARAM, GetStockObject(ANSI_VAR_FONT)), 0)
			SendMessage(hwndStatusBar,SB_SETTEXT,0, Cast(LPARAM, "Готово"))
			GetClientRect(MainForm,@rect)
			ptWidth(0) = rect.right/3
			ptWidth(1) = 2*rect.right/3
			ptWidth(2) = -1
			SendMessage(hwndStatusBar, SB_SETPARTS, 3, Cast(LPARAM, @ptWidth(0)))


			'///////////////////// СОЗДАЕМ ЛИСТБОКС //////////////////////
			hwndList = CreateWindowEx(WS_EX_CLIENTEDGE,"ListBox","Объекты",WS_CHILD Or WS_VISIBLE Or WS_VSCROLL Or LBS_DISABLENOSCROLL Or LBS_NOTIFY Or LBS_NOINTEGRALHEIGHT, 0,0,0,0,MainForm,NULL,hModule,NULL)
			hFont = CreateFont(16,0,-900,-900,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH Or FF_DONTCARE,"Terminal")
			SendMessage(hwndList,WM_SETFONT, hFont,0) ''

			OldWndList = SetWindowLong (hwndList, GWL_WNDPROC, CPtr(Long, @WndList))


			'///////////////////// СОЗДАЕМ ОКНО ПАЛИТРЫ ///////////////////
			hwndPalette		= CreateWindowEx(WS_EX_WINDOWEDGE,"PaletteClass", "Палитра", WS_CHILD Or WS_VISIBLE Or WS_DLGFRAME, 0,0,0,0,MainForm,NULL,hModule,NULL)
			hBitmap = LoadBitmap(hModule,"IDB_PALETTE")				'// первоначальная картинка палитры
			hdcMemPalette = CreateCompatibleDC(GetDC(hwndPalette))	'// контекс памяти палитры
			SelectObject(hdcMemPalette, hBitmap)					'// выбрать в контекст памяти картинку


			'////////////////////// СОЗДАЕМ ХОЛСТЫ //////////////////////////
			hwndHolst	= CreateWindowEx(WS_EX_CLIENTEDGE,"HolstClass", "Холст", WS_CHILD Or WS_VISIBLE, 0,0,0,0 ,MainForm,NULL,hModule,NULL)
			hdcMemHolstBack = CreateCompatibleDC(GetDC(hwndHolst))					'// контекст памяти "Фоновый"
			hdcMemHolstDyn = CreateCompatibleDC(GetDC(hwndHolst))					'// контекст памяти "Результирующий"
			hBitmapHolstBack = CreateCompatibleBitmap(GetDC(hwndHolst),800,600)	'// создать пустую картинку
			hBitmapHolstDyn = CreateCompatibleBitmap(GetDC(hwndHolst),800,600)		'// создать пустую картинку
			SelectObject(hdcMemHolstBack,hBitmapHolstBack)							'// выбрать в фоновый контекст
			SelectObject(hdcMemHolstDyn,hBitmapHolstDyn)							'// выбрать в результирующий контекст

			SelectObject(hdcMemHolstBack,GetStockObject(WHITE_BRUSH))
			SelectObject(hdcMemHolstBack,GetStockObject(BLACK_PEN))
			Rectangle(hdcMemHolstBack,0,0,800,600)


			''/////////////////////// ИНИЦИАЛИЗАЦИЯ ДАННЫХ ФАЙЛ-ДИАЛОГА ///////
			With ofn
				.lStructSize       = SizeOf(OPENFILENAME)	'// размер структуры
				.hwndOwner         = MainForm					'// родитель
				.hInstance         = NULL					'// приложение
				.lpstrFilter       = StrPtr(szFilter)				'// главные фильтры
				.lpstrCustomFilter = NULL					'// отстутствуют текущие фильтры
				.nMaxCustFilter    = 0						'// размер текущих фильтров
				.nFilterIndex      = 1						'// выбран первый фильтр
				.lpstrFile         = StrPtr(szFullFileName)         '// буфер полного имени
				.nMaxFile          = 256					'// размер этого буфера
				.lpstrFileTitle    = StrPtr(szFileName)				'// буфер имени
				.nMaxFileTitle     = 256					'// размер буфера
				.lpstrInitialDir   = NULL					'// стартовая папка - текущая
				.lpstrTitle        = NULL					'// надпись на окне - обычная
				.Flags             = OFN_HIDEREADONLY		'// скрыть кнопку "только для чтения"
				.nFileOffset       = 0
				.nFileExtension    = 0
				.lpstrDefExt       = StrPtr("vct")					'// текущее расширение
				.lCustData         = 0L
				.lpfnHook          = NULL
				.lpTemplateName    = NULL
			End With
			IsName				  = FALSE

			''/////////////////////// ИНИЦИАЛИЗАЦИЯ ДАННЫХ ДИАЛОГА ПАЛИТРЫ ////
			'RtlZeroMemory(@cc,Sizeof(cc))
			With clr
				.lStructSize		= SizeOf(clr)
				.hwndOwner			= MainForm
				.hInstance			= Cast(HWND,hModule)
				.rgbResult			= BGR(&h80, &h80, &h80)
				.lpCustColors		= @crCustColor(0)
				.Flags				= CC_ANYCOLOR Or CC_RGBINIT'CC_RGBINIT or CC_FULLOPEN
				.lCustData			= NULL
				.lpfnHook			= NULL
				.lpTemplateName	= NULL
			End With

			'////////////////////// ИНИЦИАЛИЗАЦИЯ ДАННЫХ ПАЛИТРЫ /////////////
			crPalCol(0, 0)=BGR(0,0,0)
			crPalCol(1, 0)=BGR(128,128,128)
			crPalCol(2, 0)=BGR(128,0,0)
			crPalCol(3, 0)=BGR(128,128,0)
			crPalCol(4, 0)=BGR(0,128,0)
			crPalCol(5, 0)=BGR(0,128,128)
			crPalCol(6, 0)=BGR(0,0,128)
			crPalCol(7, 0)=BGR(128,0,128)
			crPalCol(8, 0)=BGR(128,128,64)
			crPalCol(9, 0)=BGR(0,0,64)
			crPalCol(10, 0)=BGR(0,128,255)
			crPalCol(11, 0)=BGR(0,64,128)
			crPalCol(12, 0)=BGR(128,0,255)
			crPalCol(13, 0)=BGR(128,64,0)
			crPalCol(0, 1)=BGR(255,255,255)
			crPalCol(1, 1)=BGR(192,192,192)
			crPalCol(2, 1)=BGR(255,0,0)
			crPalCol(3, 1)=BGR(255,255,0)
			crPalCol(4, 1)=BGR(0,255,0)
			crPalCol(5, 1)=BGR(0,255,255)
			crPalCol(6, 1)=BGR(0,0,255)
			crPalCol(7, 1)=BGR(255,0,255)
			crPalCol(8, 1)=BGR(255,255,128)
			crPalCol(9, 1)=BGR(0,255,128)
			crPalCol(10, 1)=BGR(128,255,255)
			crPalCol(11, 1)=BGR(128,128,255)
			crPalCol(12, 1)=BGR(255,0,128)
			crPalCol(13, 1)=BGR(255,128,64)
			crCurUp = crPalCol(0, 0)
			crCurDown = crPalCol(0, 1)
			sprintf(szBuf, !"%s %d %s %d %s %d", "R= ", crCurUp Shl 24 Shr 24, " G= ", crCurUp Shl 16 Shr 24, " B=",crCurUp Shl 8 Shr 24)
			SendMessage(hwndStatusBar, SB_SETTEXT, 2, @szBuf)
			IsUpColor = TRUE '// активен левый цвет

			'/////////////////////// СОЗДАНИЕ ОБЪЕКТОВ GDI //////////////////////
			hPen			= CreatePen(PS_SOLID,0,0)
			hPenL			= CreatePen(PS_SOLID,0,BGR(236,233,216))	'// создать светлое техническое перо
			hPenD			= CreatePen(PS_SOLID,0,BGR(172,168,153))	'// создать темное техническое перо
			hSelectPen		= CreatePen(PS_SOLID,0,crCurUp)			'// создать перо
			hBrush			= CreateSolidBrush(0)
			hSelectBrush	= CreateSolidBrush(crCurDown)				'// создать кисть

			'/////////////////////// ТАЙМЕР /////////////////////////////////////
			SetTimer(hwndHolst,1,500,NULL)
			LightOn = TRUE

			'/////////////////////// НАДПИСЬ В СТАТУСБАРЕ ///////////////////////
			sprintf(szBuf, !"%s %06X %s %06X", "Верхний RGB = ", crCurUp, "  Нижний RGB = ", crCurDown)
			SendMessage(hwndStatusBar, SB_SETTEXT, 1, @szBuf)

			'/////////////////////// НАДПИСЬ В ГЛАВНОМ ОКНЕ /////////////////////
			SetWindowText(MainForm, "Новый документ")

			'/////////////////////// УСТАНОВКА МЕНЯЮЩИХСЯ КООРДИНАТ ОКНА ////////
			PaletteTop = 33
			ListTop = 72
			HolstTop = 33
			HolstLeft = 264
			Otstup = 20


			'// нету "return 0" чтобы пропустить процессор дальше в WM_ZIZE для автоматического позиционирования окон
			GetClientRect(MainForm,@rect)
			MoveWindow(MainForm,rect.left,rect.top,rect.right,rect.bottom ,FALSE)

		Case WM_SIZE
			'SendMessage(hwndStatusBar, WM_SIZE, 0, 0)
			GetClientRect(MainForm,@rect)
			MoveWindow(hwndPalette,2,PaletteTop,260,37,FALSE)
			MoveWindow(hwndList,2,ListTop,260,rect.bottom-ListTop-Otstup,FALSE)
			MoveWindow(hwndHolst,HolstLeft,HolstTop,rect.right-2-HolstLeft,rect.bottom-HolstTop-Otstup,FALSE)
			MoveWindow(hwndToolBar,-2,-3,rect.right+4,34,FALSE)
			MoveWindow(hwndStatusBar, 0, rect.bottom-20, rect.right, 20, FALSE)
			ptWidth(0) = rect.right/3
			ptWidth(1) = 2*rect.right/3
			ptWidth(2) = -1
			SendMessage(hwndStatusBar, SB_SETPARTS, 3, @ptWidth(0))

		Case WM_COMMAND:
			hMenu = GetMenu(MainForm)
			Select Case (LoWord(wParam))
				Case IDM_NEW:
					For i = 0 To iCount-1
						SendMessage(hwndList,LB_DELETESTRING,iCount-1-i,0)
					Next i

					iCount = 0
					RepaintBack()
					SetWindowText(MainForm, "Новый документ")
					InvalidateRect(hwndHolst,NULL,FALSE)
					EnableMenuItem(hMenu,IDM_SAVE,MF_GRAYED)
					SendMessage(hwndToolBar,TB_ENABLEBUTTON,IDM_SAVE,FALSE)


				Case IDM_HELP:
					MessageBox(MainForm,!"Простейший векторный редатор.\n\n"+_
					!"Используйте 4 инструмента:\n"+_
					!"<Указатель> - выбирать объекты\n"+_
					!"<Линия> - рисовать отрезки\n"+_
					!"<Прямоугольник> - рисовать прямоугольники\n"+_
					!"<Окружность> - рисовать окружности\n\n"+_
					!"Прямоугольник и окружность закрашиваются\n"+_
					!"нижним цветом. Контур всех фигур рисуется\n"+_
					!"верхним цветом. Выбираются цвета левой и\n"+_
					!"правой кнопкой мыши. Нарисованные объекты\n"+_
					!"удаляются кнопкой Delete или из меню.",szAppName,MB_ICONINFORMATION Or MB_OK)

				Case IDM_ABOUT: MessageBox(MainForm,!"Ox1D Inc.\nFree Code Systems...",szAppName,MB_ICONINFORMATION Or MB_OK)

				Case IDM_OPEN:
					If (GetOpenFileName (@ofn)) Then
						fp = fopen(szFullFileName,"r")
						If fp Then
							For i = 0 To iCount-1
								SendMessage(hwndList,LB_DELETESTRING,iCount-1-i,0)
							Next i
							Do While (feof(fp)=0) '// перебор строк
								If(fgets(szBuf,42,fp)) Then

									szBuf[42]=0
									SendMessage(hwndList,LB_ADDSTRING,0, @szBuf)
								EndIf
							Loop
							fclose(fp)
							RepaintBack

							InvalidateRect(hwndHolst,NULL,FALSE)

							SetWindowText(MainForm, szFullFileName)
							IsName = TRUE
							EnableMenuItem(hMenu,IDM_SAVE,MF_ENABLED)
							SendMessage(hwndToolBar,TB_ENABLEBUTTON, IDM_SAVE,TRUE)
						EndIf
					EndIf

				Case IDM_SAVE:
					fp = fopen(szFullFileName,"w")
					For i = 0 To iCount-1  ' // перебор строк
						SendMessage(hwndList, LB_GETTEXT, i,@szBuf)
						fputs(szBuf,fp)
					Next i
					fclose(fp)


				Case IDM_SAVE_AS:
					If (GetSaveFileName (@ofn)) Then
						fp = fopen(szFullFileName,"w")
						For i = 0 To iCount-1  ' // перебор строк
							SendMessage(hwndList, LB_GETTEXT, i,@szBuf)
							fputs(szBuf,fp)
						Next i
						fclose(fp)
					EndIf
					SetWindowText(MainForm, szFullFileName)
					IsName = TRUE
					EnableMenuItem(hMenu,IDM_SAVE,MF_ENABLED)
					SendMessage(hwndToolBar,TB_ENABLEBUTTON, IDM_SAVE,TRUE)

				Case IDM_EXIT:PostQuitMessage(0)


				Case IDM_DEL:
					i = SendMessage(hwndList, LB_GETCURSEL, 0, 0)
					SendMessage(hwndList,LB_DELETESTRING,i,0)
					RepaintBack
					InvalidateRect(hwndHolst,NULL,FALSE)


				Case IDM_UP_1:
					i = SendMessage(hwndList, LB_GETCURSEL, 0, 0)			'// получаем текщий выбранный элемент
					If Not (SendMessage(hwndList, LB_GETSEL, i,0)=-1) Then '// если он вне списка то выходим
						If (i > 0) Then
							SendMessage(hwndList, LB_GETTEXT, i,@szBuf)	'// получить текущую строку в szBuf
							SendMessage(hwndList,LB_DELETESTRING,i,0)
							SendMessage(hwndList,LB_INSERTSTRING,i-1,@szBuf )
							SendMessage(hwndList,LB_SETCURSEL,i-1,0)
							RepaintBack()
							InvalidateRect(hwndHolst,NULL,FALSE)
						EndIf
					EndIf
					'

				Case IDM_UP_10:
					i = SendMessage(hwndList, LB_GETCURSEL, 0, 0)			'// получаем текщий выбранный элемент
					If Not (SendMessage(hwndList, LB_GETSEL, i,0)=-1) Then '// если он вне списка то выходим
						If (i > 0) Then
							SendMessage(hwndList, LB_GETTEXT, i,@szBuf)	'// получить текущую строку в szBuf
							SendMessage(hwndList,LB_DELETESTRING,i,0)
							If (i < 10) Then i=10
							SendMessage(hwndList,LB_INSERTSTRING,i-10,@szBuf )
							SendMessage(hwndList,LB_SETCURSEL,i-10,0)
							RepaintBack()
							InvalidateRect(hwndHolst,NULL,FALSE)
						EndIf
					EndIf
					'

				Case IDM_DOWN_1:
					i = SendMessage(hwndList, LB_GETCURSEL, 0, 0)			'// получаем текщий выбранный элемент
					If Not (SendMessage(hwndList, LB_GETSEL, i,0)=-1) Then 			'// если он вне списка то выходим
						iCount = SendMessage(hwndList,LB_GETCOUNT,0,0)
						If Not (i = iCount - 1) Then
							SendMessage(hwndList, LB_GETTEXT, i,@szBuf)	'// получить текущую строку в szBuf
							SendMessage(hwndList,LB_DELETESTRING,i,0)
							SendMessage(hwndList,LB_INSERTSTRING,i+1,@szBuf )
							SendMessage(hwndList,LB_SETCURSEL,i+1,0)
							RepaintBack()
							InvalidateRect(hwndHolst,NULL,FALSE)
						EndIf
					EndIf


				Case IDM_DOWN_10:
					i = SendMessage(hwndList, LB_GETCURSEL, 0, 0)			'// получаем текщий выбранный элемент
					If Not (SendMessage(hwndList, LB_GETSEL, i,0)=-1) Then 			'// если он вне списка то выходим
						If Not (i = iCount - 1) Then
							SendMessage(hwndList, LB_GETTEXT, i,@szBuf)	'// получить текущую строку в szBuf
							SendMessage(hwndList,LB_DELETESTRING,i,0)
							If (i > iCount - 11) Then i=iCount - 11
							SendMessage(hwndList,LB_INSERTSTRING,i+10,@szBuf )
							SendMessage(hwndList,LB_SETCURSEL,i+10,0)
							RepaintBack()
							InvalidateRect(hwndHolst,NULL,FALSE)
						EndIf
					EndIf


				Case IDM_TOOLBAR:
					If (IsWindowVisible(hwndToolBar)) Then
						ShowWindow(hwndToolBar,SW_HIDE)
						CheckMenuItem(hMenu,IDM_TOOLBAR,MF_UNCHECKED)
					Else
						ShowWindow(hwndToolBar,SW_SHOW)
						CheckMenuItem(hMenu,IDM_TOOLBAR,MF_CHECKED)
					EndIf
					RecountCoord()


				Case IDM_PALETTE:
					If (IsWindowVisible(hwndPalette)) Then
						ShowWindow(hwndPalette,SW_HIDE)
						CheckMenuItem(hMenu,IDM_PALETTE,MF_UNCHECKED)
					Else
						ShowWindow(hwndPalette,SW_SHOW)
						CheckMenuItem(hMenu,IDM_PALETTE,MF_CHECKED)
					EndIf
					RecountCoord()


				Case IDM_STATUSBAR:
					If (IsWindowVisible(hwndStatusBar)) Then
						ShowWindow(hwndStatusBar,SW_HIDE)
						CheckMenuItem(hMenu,IDM_STATUSBAR,MF_UNCHECKED)
					Else
						ShowWindow(hwndStatusBar,SW_SHOW)
						CheckMenuItem(hMenu,IDM_STATUSBAR,MF_CHECKED)
					EndIf
					RecountCoord()


				Case IDM_LIST:
					If (IsWindowVisible(hwndList)) Then
						ShowWindow(hwndList,SW_HIDE)
						CheckMenuItem(hMenu,IDM_LIST,MF_UNCHECKED)
					Else
						ShowWindow(hwndList,SW_SHOW)
						CheckMenuItem(hMenu,IDM_LIST,MF_CHECKED)
					EndIf
					RecountCoord()
					'

				Case TB_ID_RGB:

					'MessageBox(MainForm,Str(@tmpColor),Str(tmpColor),MB_ICONINFORMATION Or MB_OK)
					If (ChooseColor(@clr)) Then

						If (IsUpColor) Then
							crCurUp=clr.rgbResult				'// изменить верхний цвет
						Else
							crCurDown=clr.rgbResult						'// изменить нижний цвет
						EndIf
						crPalCol(tekI,tekJ) = clr.rgbResult				'// изменить цвет в текущей клетке палитры
						RisPal()
						sprintf(szBuf, !"%s %06X %s %06X", "Верхний RGB = ", crCurUp, " Нижний RGB = ", crCurDown)
						SendMessage(hwndStatusBar, SB_SETTEXT, 1, @szBuf)
					EndIf


				Case TB_ID_ARROW:
					SetTimer(hwndHolst,1,500,NULL)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_ARROW,TRUE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_LINE,FALSE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_RECTANGLE,FALSE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_CIRCLE,FALSE)
					LightOn = TRUE
					SetFocus(hwndHolst)
					status = 0


				Case TB_ID_LINE:
					KillTimer(hwndHolst,1)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_LINE,TRUE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_ARROW,FALSE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_RECTANGLE,FALSE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_CIRCLE,FALSE)
					InvalidateRect(hwndHolst,NULL,FALSE)
					status = 1


				Case TB_ID_RECTANGLE:
					KillTimer(hwndHolst,1)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_RECTANGLE,TRUE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_ARROW,FALSE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_LINE,FALSE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_CIRCLE,FALSE)
					InvalidateRect(hwndHolst,NULL,FALSE)
					status = 2


				Case TB_ID_CIRCLE:
					KillTimer(hwndHolst,1)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_CIRCLE,TRUE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_ARROW,FALSE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_LINE,FALSE)
					SendMessage(hwndToolBar,TB_CHECKBUTTON,TB_ID_RECTANGLE,FALSE)
					InvalidateRect(hwndHolst,NULL,FALSE)
					status = 3


				Case WM_MENUSELECT:
					Select Case (HiWord(wParam))
						Case MF_MOUSESELECT Or MF_HILITE Or MF_POPUP :	'// выбран пункт заглавного меню
							LoadString(hModule, 20+LoWord(wParam), szBuf, SizeOf(szBuf))
							SendMessage(hwndStatusBar, SB_SETTEXT, 0, @szBuf)


						Case MF_MOUSESELECT Or MF_HILITE :				'// подменю
							LoadString(hModule, LoWord(wParam), szBuf, SizeOf(szBuf))
							SendMessage(hwndStatusBar, SB_SETTEXT, 0, @szBuf)


						Case MF_MOUSESELECT Or MF_HILITE Or MF_CHECKED :	'// подменю
							LoadString(hModule, LoWord(wParam), szBuf, SizeOf(szBuf))
							SendMessage(hwndStatusBar, SB_SETTEXT, 0, @szBuf)


						Case Else:
							SendMessage (hwndStatusBar, SB_SETTEXT, 0, @"Готово")
					End Select


				Case WM_NOTIFY:
					pnmh = Cast(LPNMHDR, lParam)
					If(pnmh->code = TTN_NEEDTEXT) Then
						lpttt = Cast(LPTOOLTIPTEXT, lParam)
						Select Case (lpttt->hdr.idFrom)
							Case IDM_NEW:			pReply = @"Создать новый рисунок"
							Case IDM_OPEN:			pReply = @"Открыть файл..."
							Case IDM_SAVE:			pReply = @"Сохранить файл"
							Case IDM_HELP:			pReply = @"Помощь..."
							Case TB_ID_RGB:		pReply = @"Изменить палитру"
							Case TB_ID_ARROW:		pReply = @"Указатель"
							Case TB_ID_LINE:		pReply = @"Линия"
							Case TB_ID_RECTANGLE:pReply = @"Прямоугольник"
							Case TB_ID_CIRCLE:	pReply = @"Окружность"
						End Select
						lstrcpy(lpttt->szText, pReply)
					EndIf
			End Select

		Case WM_DESTROY
			DeleteObject(hPen)
			DeleteObject(hPenL)		'// убрать светлую технич перо
			DeleteObject(hPenD)		'// убрать темную технич перо
			DeleteObject(hSelectPen)		'// убрать перо
			DeleteObject(hBrush)
			DeleteObject(hSelectBrush)		'// убрать кисть
			DeleteDC(hdcMemPalette)
			DeleteDC(hdcMemHolstBack)
			DeleteDC(hdcMemHolstDyn)
			PostQuitMessage(0)
			KillTimer(hwndHolst,1)
			Exit Function
	End Select
	Function = DefWindowProc(MainForm,uMsg,wParam,lParam) ' Дефултная функция обработки окна
End Function


Function WndPalette(ByVal PaletteForm As HWND, ByVal uMsg As UINT, ByVal wParam As WPARAM, ByVal lParam As LPARAM) As LRESULT
	Function = 0
	Dim As Integer x,y
	Dim As PAINTSTRUCT		ps
	Select Case (uMsg)
		Case WM_LBUTTONDOWN:
			x = LoWord(lParam)
			y = HiWord(lParam)
			If (x > 30) Then
				IsUpColor = TRUE
				tekI = (x - 31)\16
				tekJ = y\16
				crCurUp = crPalCol(tekI,tekJ)
				sprintf(szBuf, !"%s %06X %s %06X", "Верхний RGB = ", crCurUp, "  Нижний RGB = ", crCurDown)
				SendMessage(hwndStatusBar, SB_SETTEXT, 1, @szBuf)
				RisPal()
			EndIf
			Return 0

		Case WM_RBUTTONDOWN:
			x = LoWord(lParam)
			y = HiWord(lParam)
			If (x > 30) Then
				IsUpColor = FALSE
				tekI = (x - 31)\16
				tekJ = y\16
				crCurDown = crPalCol(tekI,tekJ)
				sprintf(szBuf, "%s %06X %s %06X", "Верхний RGB = ", crCurUp, "  Нижний RGB = ", crCurDown)
				SendMessage(hwndStatusBar, SB_SETTEXT, 1, @szBuf)
				RisPal()
			EndIf
			Return 0

		Case WM_PAINT:
			hdcPalette= BeginPaint(PaletteForm,@ps)
			BitBlt(hdcPalette, 0, 0, 254, 31, hdcMemPalette, 0, 0, SRCCOPY)
			EndPaint(PaletteForm,@ps)
			Return 0
	End Select
	Function = DefWindowProc(PaletteForm, uMsg, wParam, lParam)
End Function

Function WndHolst(ByVal HolstForm As HWND, ByVal uMsg As UINT, ByVal wParam As WPARAM, ByVal lParam As LPARAM)	As LRESULT
	Function = 0
	Static As Integer xDown,yDown,xMove,yMove
	Static As BOOL	Down = FALSE
	Dim As Integer x1,y1,x2,y2
	Dim As PAINTSTRUCT	psHolst
	Select Case (uMsg)
		Case WM_PAINT:
			hdcHolst = BeginPaint(HolstForm,@psHolst)
			BitBlt(hdcMemHolstDyn, 0, 0, 800, 600,	hdcMemHolstBack, 0, 0, SRCCOPY)'// копируем общую поверхность в результирующую
			If (Down = TRUE) Then RepaintDyn(xDown,yDown,xMove,yMove)					'// рисуем тякущий объект в результирующей
			BitBlt(hdcHolst, 10, 10, 800, 600,hdcMemHolstDyn, 0, 0, SRCCOPY)		'// копируем результирующую на экран
			EndPaint(HolstForm,@psHolst)


		Case WM_LBUTTONDOWN:
			xDown = LoWord(lParam)-10
			xMove = xDown
			yDown = HiWord(lParam)-10
			yMove = yDown
			If (status= 0) Then	Selecting(xDown,yDown)

			DeleteObject(hSelectPen)						'// Уничтожить перо
			hSelectPen = CreatePen(PS_SOLID,0,crCurUp)		'// Создать перо на основе верхнего цвета
			DeleteObject(hSelectBrush)						'// Уничтожить кисть
			hSelectBrush = CreateSolidBrush(crCurDown)		'// Создать кисть на основе нижнего цвета
			Down	= TRUE									'// Мышь нажата


		Case WM_RBUTTONDOWN:
			Down = FALSE
			InvalidateRect(HolstForm,NULL,FALSE)


		Case WM_MOUSEMOVE:
			xMove = LoWord(lParam)-10
			yMove = HiWord(lParam)-10
			sprintf(szBuf, !"%s %04d %s %04d", "X = ",xMove," Y = ",yMove)
			SendMessage(hwndStatusBar, SB_SETTEXT, 2, @szBuf)
			If (Down = TRUE) Then InvalidateRect(HolstForm,NULL,FALSE)


		Case WM_LBUTTONUP:
			If (Down=TRUE) Then
				If Not((xDown=xMove) And (yDown=yMove)) Then
					Down = FALSE
					Select Case (status)
						Case 0:
							Down = FALSE			'// Мышь отпущена

						Case 1:
							sprintf(szBuf,!"%s %04d %04d %04d %04d %06X %06X", " Line =",xDown, yDown, xMove, yMove, crCurUp, crCurDown)
							SendMessage(hwndList,LB_ADDSTRING,0,@szBuf)

						Case 2:
							sprintf(szBuf,!"%s %04d %04d %04d %04d %06X %06X", " Rect =",xDown, yDown, xMove, yMove, crCurUp, crCurDown)
							SendMessage(hwndList,LB_ADDSTRING,0,@szBuf)

						Case 3:
							sprintf(szBuf,!"%s %04d %04d %04d %04d %06X %06X", " Circ =",xDown, yDown, xMove, yMove, crCurUp, crCurDown)
							SendMessage(hwndList,LB_ADDSTRING,0,@szBuf)

					End Select
					iCount = SendMessage(hwndList,LB_GETCOUNT,0,0)
					SendMessage(hwndList, LB_SETCURSEL, iCount-1, 0)	'// Позиционирование курсора на последней строке
					Down = FALSE										'// Мышь отпущена
					RepaintBack()
				EndIf
			EndIf
			'// Перерисовываем фоновую поверхность


		Case WM_TIMER:
			i = SendMessage(hwndList, LB_GETCURSEL, 0, 0)			'// получаем текщий выбранный элемент
			If Not(SendMessage(hwndList, LB_GETSEL, i,0)=-1) Then'// если он вне списка то выходим
				If LightOn Then
					LightOn=FALSE
					SendMessage(hwndList, LB_GETTEXT, i,@szBuf)
					sprintf(szCount,"%c%c%c%c",szBuf[9],szBuf[10],szBuf[11],szBuf[12])
					x1=atoi(szCount)+10
					sprintf(szCount,"%c%c%c%c",szBuf[13],szBuf[14],szBuf[15],szBuf[16])
					y1=atoi(szCount)+10
					sprintf(szCount,"%c%c%c%c",szBuf[18],szBuf[19],szBuf[20],szBuf[21])
					x2=atoi(szCount)+10
					sprintf(szCount,"%c%c%c%c",szBuf[23],szBuf[24],szBuf[25],szBuf[26])
					y2=atoi(szCount)+10
					hdcHolst = GetDC(HolstForm)
					DeleteObject(hPen)
					hPen = CreatePen(PS_SOLID,2,&h0000FF)
					SelectObject(hdcHolst,hPen)
					SelectObject(hdcHolst,GetStockObject(NULL_BRUSH))
					Select Case (Chr(szBuf[1]))
						Case "L":
							MoveToEx(hdcHolst,x1,y1,NULL)	'// Поместить перо в точку нажатия
							LineTo(hdcHolst,x2,y2)			'// Линия от точки нажатия до предыдущей точки

						Case "R":
							Rectangle(hdcHolst,x1,y1,x2+1,y2+1)	'// Прямоугольник от точки нажатия до текущей точки

						Case "C":
							Ellipse(hdcHolst,x1,y1,x2,y2)	'// Прямоугольник от точки нажатия до текущей точки

					End Select
					ReleaseDC(HolstForm,hdcHolst)
				Else
					LightOn = TRUE
					InvalidateRect(HolstForm,NULL,FALSE)
				EndIf
			EndIf
	End Select
	Function = DefWindowProc(HolstForm, uMsg, wParam, lParam)
End Function

'// перехват оконной процедуры
Function WndList(ByVal ListForm As HWND, ByVal uMsg As UINT, ByVal wParam As WPARAM, ByVal lParam As LPARAM)	As LRESULT
	Function = 0
	If (uMsg = WM_KEYUP) Then
		If (wParam = VK_DELETE) Then
			SendMessage(hwndList,LB_DELETESTRING,SendMessage(hwndList, LB_GETCURSEL, 0, 0),0)
			RepaintBack
			InvalidateRect(hwndHolst,NULL,FALSE)
		EndIf
	EndIf

	'// вернуться к обычной процедуре
	Function = CallWindowProc(CPtr(WNDPROC, OldWndList),ListForm,uMsg, wParam, lParam)
End Function

''' register all the window classes.
Sub register_classes
	Dim wc As WNDCLASSEX
	With wc ' заполняем структуру wc
		.cbSize = SizeOf( WNDCLASSEX ) ' размер структуры WNDCLASSEX
		.style = CS_HREDRAW + CS_VREDRAW ' Стиль окна
		.cbClsExtra = NULL ' резервирование дополнительных байт за концом структуры
		.cbWndExtra = NULL
		.hInstance = hModule ' хэндл модуля
		.hbrBackground = Cast(HBRUSH, COLOR_3DFACE + 1) ' Цвет фона
		.lpszMenuName = StrPtr("IDR_MENU1") ' Хэндл меню
		.hIcon = LoadIcon(hModule,"IDI_ICON") ' Хэндл иконки
		.hIconSm = .hIcon 'Хэндл маленькой иконки
		.hCursor = LoadCursor( NULL,IDC_ARROW) ' Хэндл курсора
		.lpfnWndProc   = @WndMain
		.lpszClassName = StrPtr(szAppName)
	End With
	RegisterClassEx(@wc)

	With wc
		.cbSize = SizeOf( WNDCLASSEX )
		.style = CS_HREDRAW + CS_VREDRAW
		.cbClsExtra = NULL
		.cbWndExtra = NULL
		.hInstance = hModule
		.hbrBackground = Cast(HBRUSH, COLOR_3DFACE + 1)
		.lpszMenuName = NULL
		.hIcon = LoadIcon(hModule,IDI_APPLICATION)
		.hIconSm = .hIcon
		.hCursor = LoadCursor( NULL,IDC_ARROW)
		.lpfnWndProc   = @WndPalette
		.lpszClassName = StrPtr("PaletteClass")
	End With
	RegisterClassEx(@wc)

	With wc
		.cbSize = SizeOf( WNDCLASSEX )
		.style = CS_HREDRAW + CS_VREDRAW
		.cbClsExtra = NULL
		.cbWndExtra = NULL
		.hInstance = hModule
		.hbrBackground = Cast(HBRUSH, COLOR_BTNFACE)
		.lpszMenuName = NULL
		.hIcon = LoadIcon(hModule,IDI_APPLICATION)
		.hIconSm = .hIcon
		.hCursor = LoadCursor( NULL,IDC_ARROW)
		.lpfnWndProc   = @WndHolst
		.lpszClassName = StrPtr("HolstClass")
	End With
	RegisterClassEx(@wc)

End Sub

Sub RepaintBack
	Dim As Integer x1,y1,x2,y2
	Dim As COLORREF crPlay

	SendMessage(hwndList, LB_GETTEXT, 0, @szBuf)
	SelectObject(hdcMemHolstBack,GetStockObject(WHITE_BRUSH))
	SelectObject(hdcMemHolstBack,GetStockObject(BLACK_PEN))
	Rectangle(hdcMemHolstBack,0,0,800,600)
	iCount = SendMessage(hwndList,LB_GETCOUNT,0,0)

	For i = 0 To iCount-1 '// перебор строк
		SendMessage(hwndList, LB_GETTEXT, i, @szBuf)	'// получить текущую строку в szBuf

		sprintf(szCount,"%c%c%c%c",szBuf[9],szBuf[10],szBuf[11],szBuf[12]) '// собрать szCount из элементов szBuf
		x1=atoi(szCount)
		sprintf(szCount,"%c%c%c%c",szBuf[13],szBuf[14],szBuf[15],szBuf[16])
		y1=atoi(szCount)
		sprintf(szCount,"%c%c%c%c",szBuf[18],szBuf[19],szBuf[20],szBuf[21])
		x2=atoi(szCount)
		sprintf(szCount,"%c%c%c%c",szBuf[23],szBuf[24],szBuf[25],szBuf[26])
		y2=atoi(szCount)

		sprintf(szCount,"%c%c%c%c%c%c",szBuf[28],szBuf[29],szBuf[30],szBuf[31],szBuf[32],szBuf[33])
		crPlay = HexSzToInt(szCount)

		DeleteObject(hPen)						'// Уничтожить перо
		hPen = CreatePen(PS_SOLID,0,crPlay)	'// Создать перо на основе верхнего цвета

		sprintf(szCount,"%c%c%c%c%c%c",szBuf[35],szBuf[36],szBuf[37],szBuf[38],szBuf[39],szBuf[40])
		crPlay = HexSzToInt(szCount)
		DeleteObject(hBrush)						'// Уничтожить кисть
		hBrush = CreateSolidBrush(crPlay)	'// Создать кисть на основе верхнего цвета

		SelectObject(hdcMemHolstBack,hPen)
		SelectObject(hdcMemHolstBack,hBrush)

		Select Case Chr(szBuf[1])
			Case "L"
				MoveToEx(hdcMemHolstBack,x1,y1,NULL)	'// Поместить перо в точку нажатия
				LineTo(hdcMemHolstBack,x2,y2)			'// Линия от точки нажатия до предыдущей точки;

			Case "R"
				Rectangle(hdcMemHolstBack,x1,y1,x2,y2)	'// Прямоугольник от точки нажатия до текущей точки;

			Case "C"
				Ellipse(hdcMemHolstBack,x1,y1,x2,y2)	'// Прямоугольник от точки нажатия до текущей точки;

		End Select
	Next i
End Sub


Sub RepaintDyn(ByVal xDown As Integer,ByVal yDown As Integer,ByVal xMove As Integer,ByVal yMove As Integer)
	SelectObject(hdcMemHolstDyn,hSelectPen)			'// Выбрать текущее перо
	SelectObject(hdcMemHolstDyn,hSelectBrush)			'// Выбрать текущую кисть
	Select Case (status)										'// Какой объект выбран
		Case 1:												'// Линия
			MoveToEx(hdcMemHolstDyn,xDown,yDown,NULL)			'// Поместить перо в точку нажатия
			LineTo(hdcMemHolstDyn,xMove,yMove)					'// Линия от точки нажатия до текущей точки

		Case 2:												'// Прямоугольник
			Rectangle(hdcMemHolstDyn,xDown,yDown,xMove,yMove)	'// от точки нажатия до текущей точки

		Case 3:												'// Эллипс
			Ellipse(hdcMemHolstDyn,xDown,yDown,xMove,yMove)	'// от точки нажатия до текущей точки
	End Select
	sprintf(szBuf, !"%s %d %s %d %s %d", "R= ", crCurDown Shl 24 Shr 24, " G= ", crCurDown Shl 16 Shr 24, " B=",crCurDown Shl 8 Shr 24)
	SendMessage(hwndStatusBar, SB_SETTEXT, 2, @szBuf)
End Sub


Sub Selecting(ByVal X As Integer,ByVal Y As Integer)'// суровая математика
	Dim As Integer x1,y1,x2,y2,yy,xx
	Dim As Integer GorX,GorY,VerX,VerY
	Dim As Double a,b,k,z
	Dim Iis As BOOL	 = FALSE
	iCount = SendMessage(hwndList,LB_GETCOUNT,0,0)
	For i = iCount-1 To 0 Step -1'// перебор строк
		SendMessage(hwndList, LB_GETTEXT, i,@szBuf)
		sprintf(szCount,"%c%c%c%c",szBuf[9],szBuf[10],szBuf[11],szBuf[12])
		x1=atoi(szCount)
		sprintf(szCount,"%c%c%c%c",szBuf[13],szBuf[14],szBuf[15],szBuf[16])
		y1=atoi(szCount)
		sprintf(szCount,"%c%c%c%c",szBuf[18],szBuf[19],szBuf[20],szBuf[21])
		x2=atoi(szCount)
		sprintf(szCount,"%c%c%c%c",szBuf[23],szBuf[24],szBuf[25],szBuf[26])
		y2=atoi(szCount)
		Select Case (szBuf) '// проверка попадания внутрь фигуры
			Case "L": '// попал ли курсор на линию
				If (x1=x2) Then	'// вертикальная линия
					If ((MinCoordOf2(y1,y2)<=Y) And (Y<=MaxCoordOf2(y1,y2))) Then
						If (((x1-2)<X) And (X<(x1+2))) Then Iis = TRUE
					EndIf

				ElseIf (y1=y2) Then '// горизонтальная линия
					If ((MinCoordOf2(x1,x2)<=X) And (X<=MaxCoordOf2(x1,x2))) Then
						If (((y1-2)<Y) And (Y<(y1+2))) Then Iis = TRUE
					EndIf

				ElseIf ((MinCoordOf2(x1,x2)<=X) And (X<=MaxCoordOf2(x1,x2)) And  (MinCoordOf2(y1,y2)<=Y) And (Y<=MaxCoordOf2(y1,y2))) Then
					k = ((y1-y2)\(x1-x2))
					z = y1 - k*x1
					'// находим точку пересечения с горизонталью
					GorX = ((Y - z)\k)
					GorY = Y
					'// находим точку пересечения с вертикалью
					VerY = (k*X+z)
					VerX = X
					If ((Abs(X-GorX)<3) Or (Abs(Y-VerY)<3)) Then	Iis = TRUE

				EndIf

			Case "R" '// попал ли курсор в прямоугольник
				If ((MinCoordOf2(x1,x2)<=X) And (X<=MaxCoordOf2(x1,x2)) And  (MinCoordOf2(y1,y2)<=Y) And (Y<=MaxCoordOf2(y1,y2))) Then Iis = TRUE

			Case "C" '// попал ли курсор в эллипс
				If ((MinCoordOf2(x1,x2)<=X) And (X<=MaxCoordOf2(x1,x2)) And  (MinCoordOf2(y1,y2)<=Y) And (Y<=MaxCoordOf2(y1,y2))) Then
					a = (MaxCoordOf2(x1,x2) - MinCoordOf2(x1,x2))/2
					b = (MaxCoordOf2(y1,y2) - MinCoordOf2(y1,y2))/2
					xx = X - (x1+x2)/2
					yy = Y - (y1+y2)/2
					If (((xx*xx)\(a*a))+((yy*yy)\(b*b))<=1) Then	Iis = TRUE
				EndIf
		End Select
	Next i

	If (Iis=TRUE) Then
		SendMessage(hwndList, LB_SETCURSEL, i, 0)	'// Позиционирование курсора на выделенном объекте
		SetFocus(hwndList)
	EndIf
End Sub