//////////////////////////////////////////////////////////////////////
//
// Разработчик: Алексей Фёдоров aka АЛьФ, mailto: alf@dorex.ru
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "sizecbar.h"
#include "afxpriv.h"
#define DELETE_EXCEPTION(e) do { e->Delete(); } while (0)

#include "painthook.h"
#include "FormExFormView.h"

//#undef VK_1CPP_SourceTable
//#define VK_1CPP_SourceTable
#include "TableEx.h"

// artbear
#ifndef FORMEX_DLL
#include ".\\TurboBL\\gcboost.h"
#endif

#include "MethodsWrapper.h"
#include "BLModuleWrapper.h"

extern CMapStringToPtr cModuleMap; // для анализа закрытия формы

// завершение

extern CBkEndUI * pBkEndUI;
extern HINSTANCE hDllInstance;
extern class CMDIFrameWnd * pMainWindow;
BOOL bSetDrawWrap = FALSE;
//extern CSizingControlBar* pWndToDock;
extern CWnd* pWndToDock;
extern class CWinApp* pApp; //CApp7
extern BOOL m_bShowKL;

//#ifndef VK_1CPP_SourceTable
CMapStringToPtr DocNamesArray;
struct SDocNames{
	DWORD id;
	CString strFolder;
};
//#endif

typedef int(CBLModule::*PF_FF)(char const * )const;
CDllMethodWrapper<PF_FF> wrapperFindFunc;

typedef int(CBLModule::*PF_FP)(char const * ,int )const;
CDllMethodWrapper<PF_FP> wrapperFindProc;

typedef int(CBLModule::*PF_CAP)(int,int,class CValue * *);
CDllMethodWrapper<PF_CAP> wrapperCallAsProc;

typedef int(CBLModule::*PF_CAF)(int,class CValue &,int,class CValue * *);
CDllMethodWrapper<PF_CAF> wrapperCallAsFunc;

#ifdef FORMEX_DLL

typedef void(CBLModule::*PF_AsCont)(class CBLContext *);
static BYTE*   adrWrapAssignContext;
static PF_AsCont jmpWrapAssignContext;
static BYTE    origWrapAssignContext[6];
static BYTE    wrapWrapAssignContext[6];

#endif

typedef int(SECStatusBar::*PF_SI)(unsigned int const *,int);
CDllMethodWrapper<PF_SI> wrapperSetIndicators;

typedef int(CBrowse::*PF_GHTB)(int);
CDllMethodWrapper<PF_GHTB> wrapperGetHiTrackBound;

typedef int(CBrowse::*PF_GLTB)(int);
CDllMethodWrapper<PF_GLTB> wrapperGetLoTrackBound;

typedef class CWnd * (CGetDoc7::*PF_GDCC)(class CGetField *,unsigned int,class CRect const &,class CWnd *,unsigned long,unsigned long);
CDllMethodWrapper<PF_GDCC> wrapperCreateControl;

typedef void (CGetDoc7::*PF_PSO)(class CValue*);
CDllMethodWrapper<PF_PSO> wrapperProcessSecondOpen;

typedef void (CBrowseView7::*PF_ONINITUP)(void);
CDllMethodWrapper<PF_ONINITUP> wrapperOnInitialUpdate;

typedef int (CGetDlg::*PF_ONINITDLG)(void);
CDllMethodWrapper<PF_ONINITDLG> wrapperOnInitDialog;

typedef int(CGetDoc7::*PF_LayF)(class CFormView *);
CDllMethodWrapper<PF_LayF> wrapperLayoutForm;

typedef int(CBLModule::*PF_GPI)(int,class CBLProcInfo &)const;
CDllMethodWrapper<PF_GPI> wrapperGetProcInfo;

typedef int(CBLProcInfo::*PF_GNP)(void)const;
CDllMethodWrapper<PF_GNP> wrapperGetNParams;

typedef HBRUSH  (CDrawTrasparentCtrl::*PF_CC_TC)(class CDC *,unsigned int);
static BYTE*   adrCtlColorTrans;

typedef HBRUSH  (CDrawStatic::*PF_CC)(class CDC *,unsigned int);
static BYTE*   adrCtlColor;

typedef void (*PF_DX_T)(class CGetExchange *,int,class CValue &);
CDllMethodWrapper<PF_DX_T> wrapperDX_Text;

/*
typedef class CSbCntDoc * (*PF_ActSL)(long,class CObjID,unsigned int,unsigned int,class CObjID,class CString,class CDate,int,class CObjID,int,long,int,class CValue *,class CString,int,int,int,class CValue *);
static BYTE*   adrActivateSubkList;
static PF_ActSL jmpActivateSubkList;
static BYTE    origActivateSubkList[6];
static BYTE    wrapActivateSubkList[6];
*/

/*// artbear - этот метод переопределяется в ТурбоБЛ TurboBL
typedef int(CBLContext::*CBLContext_PF_FM)(char const * )const;
static BYTE* adrFindMethod;
static CBLContext_PF_FM jmpFindMethod;
static BYTE  origFindMethod[6];
static BYTE  wrapFindMethod[6];
// end
*/

typedef void (CGetDoc7::*PF_ONCD)(void);
CDllMethodWrapper<PF_ONCD> wrapperOnCloseDocument;

typedef int(CGetDoc::*PF_ONUPDATA)(int, UINT);
CDllMethodWrapper<PF_ONUPDATA> wrapperUpdateData;

typedef int(CGetDoc7::*PF_LOADFORM)(long,char const *);
CDllMethodWrapper<PF_LOADFORM> wrapperLoadForm;

typedef int(CEditDoc::*PF_DOLOADEX)(LPCSTR);
CDllMethodWrapper<PF_DOLOADEX> wrapperDoLoadExternal;

typedef void(CImageCol::*PF_GETDATAIMAGECOL)(CString&);
CDllMethodWrapper<PF_GETDATAIMAGECOL> wrapperGetDataImageCol;

typedef int(CGetDoc7::*PF_LOADDIALOG)(long,char const *);
CDllMethodWrapper<PF_LOADDIALOG> wrapperLoadDialog;

//typedef static void (CGetDlg::*PF_OPENDOCUMENTFILEEX)(unsigned int,char const *,long,class CValue *,unsigned int,unsigned int,unsigned int,unsigned int);
CDllMethodWrapper<void*> wrapperOpenDocumentFileEx;

typedef void (CCheckListBox::*PF_CLBDI)(LPDRAWITEMSTRUCT);
typedef BOOL (CCheckListBox::*PF_CLBOCN)(UINT , WPARAM , LPARAM , LRESULT* );

CBLModule7* pGlobalModuleFormEx;

AFX_PMSG origOnEnable;
typedef void (CDrawTrasparentCtrl::*PF_OnEn)(int);

struct CWrapModule::paramdefs CWrapModule::glFnNames[] = {
	{"ПриНачалеРаботыСистемы","OnStartSystem",false,0},
	{"ПриЗавершенииРаботыСистемы","OnFinishSystem",false,0},
	{"ПриУдаленииЭлемента","OnDeleteItem",false,2},
	{"ПриОткрытииИстории","OnOpenHistory",false,3},
	{"ПриЗаписиИстории","OnWriteHistory",false,4},
	{"ПриУдаленииИстории","OnDeleteHistory",false,4},
	{"ПриЗаписиКонстанты","OnWriteConst",false,2},
	{"ПриУдаленииДокумента","OnDeleteDoc",false,2},
	{"ПриИзмененииВремениДокумента","OnChangeTimeDoc",false,1},
	{"ПриОтменеПроведенияДокумента","OnUnPosting",false,1},
	{"ПриУстановкеОтбора","OnSetSelectInJournal",false,2},
	{"ПриУдаленииСчета","OnDeleteAccount",false,2},
	{"ПриВыклВклПроводокОперации","OnOperEntryOffOn",false,1},
	{"ПриСменеРасчетногоПериода","OnPeriodChange",false,2},
	{"ОбработкаЯчейкиТаблицы","SheetCellProcessing",true,4},
	{NULL,NULL,false,0}
};

int CWrapModule::FindFunction(char const * lpFnName)const
{
	int i;

	for (i = 0;glFnNames[i].rusName != NULL;i++){
		if (!stricmp(lpFnName,glFnNames[i].rusName))
			return i;
		if (!stricmp(lpFnName,glFnNames[i].engName))
			return i;
	}
	return -1;
};

static bool bCallSysProc = false;
static bool bCallSysProcEx = false;

int  CWrapModule::WrapGetProcInfo(int nProc, class CBLProcInfo & cProcInfo)const
{
	int ret = 0;
	wrapperGetProcInfo.RestoreOrigAddress();

	if(bCallSysProc && (pGlobalModuleFormEx == (CBLModule*)this))
	{
		cProcInfo.m_Module = (CBLModule*)this;
		cProcInfo.m_ProcID = (ULONG) -nProc;
		ret = 1;
	}
	else
		ret = ((CBLModule*)this)->GetProcInfo(nProc, cProcInfo);

	wrapperGetProcInfo.RestoreWrapAddress();

	return ret;
}

int  CWrapModule::WrapGetNParams()const
{
	int ret = 0;
	wrapperGetNParams.RestoreOrigAddress();

	CBLProcInfo* This = (CBLProcInfo*)this;
	if(bCallSysProc && (pGlobalModuleFormEx == This->m_Module))
	{
		int ret_o = -1;
		CBLModule* pMod = This->GetModule();
		if(pMod)
		{
			int n = pMod->FindFunc(glFnNames[-((int)This->m_ProcID)].rusName);
			if(n < 0)
				n = pMod->FindFunc(glFnNames[-((int)This->m_ProcID)].engName);
			if(n < 0)
				n = pMod->FindProc(glFnNames[-((int)This->m_ProcID)].rusName, 0);
			if(n < 0)
				n = pMod->FindProc(glFnNames[-((int)This->m_ProcID)].engName, 0);
			if(n >= 0)
			{
				int nn = (int)This->m_ProcID;
				This->m_ProcID = n;
				ret_o = This->GetNParams();
				This->m_ProcID = nn;
			}
		}

		ret = glFnNames[-((int)This->m_ProcID)].ParamsNum;
		if(ret < ret_o) ret = ret_o;
	}
	else
		ret = ((CBLProcInfo*)this)->GetNParams();

	wrapperGetNParams.RestoreWrapAddress();

	return ret;
}

int  CWrapModule::WrapFindFunc(char const * fName)const
{
	int ret = -1;
	wrapperFindFunc.RestoreOrigAddress();
//Msg("%s %s", "CWrapModule::WrapFindFunc fName", fName);
	int nProcNum = FindFunction(fName);
	if((pGlobalModuleFormEx == (CBLModule*)this) && !bCallSysProc && !bCallSysProcEx && (nProcNum >= 0))
	{
		wrapperCallAsFunc.RestoreWrapAddress();

		bCallSysProc = true;
		ret = nProcNum;
	}
	else
		//ret = ((CBLModule*)this)->FindFunc(fName);
		ret = (((CBLModule*)this)->*wrapperFindFunc.GetOrigMethod())(fName);
	
	wrapperFindFunc.RestoreWrapAddress();

	return ret;
}


int  CWrapModule::WrapFindProc(char const * pName,int flag)const
{
	int ret = -1;
//Msg("%s %s", "CWrapModule::WrapFindProc pName", pName);
	wrapperFindProc.RestoreOrigAddress();

	int nProcNum = FindFunction(pName);
	if((pGlobalModuleFormEx == (CBLModule*)this) && !bCallSysProc && !bCallSysProcEx && (nProcNum >= 0))
	{
		wrapperCallAsProc.RestoreWrapAddress();

		bCallSysProc = true;
		ret = nProcNum;
	}
	else
		ret = ((CBLModule*)this)->FindProc(pName,flag);

	wrapperFindProc.RestoreWrapAddress();

	return ret;
}

int CWrapModule::WrapCallAsFunc(int num,class CValue & retValue,int argNum,class CValue * * ppValue)
{
	int ret = 0;
	wrapperCallAsFunc.RestoreOrigAddress();
	
	if(bCallSysProc)
	{
//Msg("%s %s", "CWrapModule::WrapCallAsFunc glFnNames[num].rusName", glFnNames[num].rusName);
		bCallSysProc = false;
		bCallSysProcEx = true;
		//argNum = glFnNames[num].ParamsNum;
		if(glFnNames[num].HasFSO && (argNum >= 2))
			*(ppValue[1]) = 0L;

		BOOL res = _CallFromGlobalModules(NULL,
								NULL,
								glFnNames[num].rusName,
								glFnNames[num].engName,
								argNum,
								ppValue,
								true);

		if(glFnNames[num].HasFSO)
		{
			if(res)
			{
				if(ppValue[1]->GetNumeric() != 0)
					ret = 0;
				else
					ret = 1;
			}
			else
				ret = 0;
		}
		else
			ret = 1;

		bCallSysProcEx = false;
	}
	else
		ret = ((CBLModule*)this)->CallAsFunc(num,retValue,argNum,ppValue);

	wrapperCallAsFunc.RestoreWrapAddress();

	return ret;
}

int CWrapModule::WrapCallAsProc(int num,int argNum,class CValue * * ppValue)
{
	int ret = 0;
	wrapperCallAsProc.RestoreOrigAddress();

//
//	CBLModule* This = (CBLModule*)this;
//	CBLProcInfo ProcInfo;
//	This->GetProcInfo(num, ProcInfo);
//	pBkEndUI->DoMessageLine(CString("CallAsProc PROCEDURE: ")+ProcInfo.GetName());
//
	if(bCallSysProc)
	{
//Msg("%s %s", "CWrapModule::WrapCallAsProc glFnNames[num].rusName", glFnNames[num].rusName);
		bCallSysProc = false;
		bCallSysProcEx = true;
		//argNum = glFnNames[num].ParamsNum;
		if(glFnNames[num].HasFSO && (argNum >= 2))
			*(ppValue[1]) = 0L;
		BOOL res = _CallFromGlobalModules(NULL,
								NULL,
								glFnNames[num].rusName,
								glFnNames[num].engName,
								argNum,
								ppValue,
								true);

		if(glFnNames[num].HasFSO)
		{
			if(res)
			{
				if(ppValue[1]->GetNumeric() != 0)
					ret = 0;
				else
					ret = 1;
			}
			else
				ret = 0;
		}
		else
			ret = 1;
		bCallSysProcEx = false;
	}
	else
		ret = ((CBLModule*)this)->CallAsProc(num,argNum,ppValue);

	wrapperCallAsProc.RestoreWrapAddress();

	return ret;
}

#ifdef FORMEX_DLL

void  CWrapModule::WrapAssignContext(class CBLContext * pCont)
{
	if(pCont)
//		if(!pCont->GetLoadedID())
			if(CString("CGroupContext") == pCont->GetRuntimeClass()->m_lpszClassName)
				pCont->m_FlagAutoDestroy = (int)this;

	BYTE* adr1 = adrWrapAssignContext;
	for(int i = 0; i<6;i++) *adr1++ = origWrapAssignContext[i];
	((CBLModule*)this)->AssignContext(pCont);
	adr1 = adrWrapAssignContext;
	for(i = 0; i<6;i++) *adr1++ = wrapWrapAssignContext[i];
}

#endif

union PtrC{
	void* pV;
/*	PF_GHTB pGHTB;
	PF_GLTB pGLTB;*/
	PF_CC_TC pCC_TC;
	PF_CC pCC;
	PF_OnEn pOnEn;
/*	PF_ONINITUP pOnInitUp;
	PF_ONINITDLG pOnInitDlg;
	PF_ONCD pOnCloseDocument;*/
	AFX_PMSG pV_M;
/*	PF_LayF pLayF;
	PF_ONUPDATA pOnUpData;
	PF_LOADFORM pLoadForm;
	PF_LOADDIALOG pLoadDialog;
	PF_DOLOADEX pDoLoadExternal;
	PF_GETDATAIMAGECOL pGetDataImageCol;*/
//	CBLContext_PF_FM pContextFindMethod;
} conv;

int  CWrapModule::WrapSetIndicators(unsigned int const * num1,int num2)
{
	wrapperSetIndicators.RestoreOrigAddress();

	((SECStatusBar*)this)->SetIndicators(num1, num2);

	if(m_bShowKL)
	{
		SECStatusBar* pStatus = (SECStatusBar*)this;
		if(pStatus)
		{
//			int count = num2;
			UINT* nIDs;
//			UINT* nStyles;
//			int* cxWidths;
			nIDs = (UINT*)malloc((num2+2)*sizeof(UINT));
//			nStyles = (UINT*)malloc(count*sizeof(UINT));
//			cxWidths = (int*)malloc(count*sizeof(int));
			for(int i = 0; i<num2; i++)
				nIDs[i] = num1[i];
//				pStatus->GetPaneInfo(i,nIDs[i],nStyles[i],cxWidths[i]);
			nIDs[num2] = 0;
			nIDs[num2+1] = 0;
			pStatus->AllocElements(num2+2,100);
			((SECStatusBar*)this)->SetIndicators(nIDs, num2+2);
//			pStatus->SetIndicators(nIDs, num2+2);
			pStatus->SetPaneInfo(num2+1,NULL,SBPS_NORMAL, 43);
			pStatus->SetPaneInfo(num2,NULL,SBPS_NORMAL, 20);
			char KLName[KL_NAMELENGTH]; 
			if(GetLocaleInfo((LCID)((WORD)GetKeyboardLayout(AfxGetApp()->m_nThreadID)),LOCALE_SABBREVLANGNAME,KLName,KL_NAMELENGTH))
				pStatus->SetPaneText(num2,KLName,KL_NAMELENGTH);
//			for(i = 0; i<count; i++)
//				pStatus->SetPaneInfo(i,nIDs[i],nStyles[i],cxWidths[i]);

			free(nIDs);
//			free(nStyles);
//			free(cxWidths);
		}
	}
//	else

	wrapperSetIndicators.RestoreWrapAddress();

	return 1;
}

//CGetDoc7::OnCloseDocument
void CWrapModule::WrapOnCloseDocument(void)
{
	wrapperOnCloseDocument.RestoreOrigAddress();

	CGetDoc7* This = (CGetDoc7*)this;
	BOOL bAutoDelete = This->m_bAutoDelete;
	This->m_bAutoDelete = FALSE;

	// отсоединение присоединенной к форме формы
	POSITION aPOS = ((CDocument*)This)->GetFirstViewPosition();
	CFormView* pFView0 = (CFormView*)((CDocument*)This)->GetNextView(aPOS);
	if(pFView0)
	{
		CWnd* pWnd = pFView0->GetParent();
		if(CString("CFormExFormView") == pWnd->GetRuntimeClass()->m_lpszClassName)
		{
			if(CSplitterWnd* pSWnd = (CSplitterWnd*)pWnd->GetParent())
			{
				int szCol = pSWnd->GetColumnCount();
				int szRow = pSWnd->GetRowCount();
				CFormExFormView* pExFormView = NULL;
				for(int iCol = 0; (iCol < szCol) && (pExFormView == NULL); iCol++)
					for(int iRow = 0; (iRow < szRow) && (pExFormView == NULL); iRow++)
					{
						if(CFormExFormView* pPane = (CFormExFormView*)pSWnd->GetPane(iRow,iCol))
							if(pPane->m_bAttached == true)
								pExFormView = pPane;
					}
				if(pExFormView)
				{
					CFrameWnd* pWndFrame = pExFormView->m_frame;
					pExFormView->m_frame = NULL;
					CMDIFrameWnd* pMain = GetMainFrame();
					pWndFrame->SetParent(CWnd::FromHandle(pMain->m_hWndMDIClient));
					CWnd* pWnd = pExFormView->GetWindow(GW_CHILD);
					while(pWnd)
					{
						pWnd->SetParent(pWndFrame);
						pWnd = pExFormView->GetWindow(GW_CHILD);
					}
					pWndFrame->ShowWindow(SW_SHOW);
					((CTabFrame*)pWndFrame)->RecalcLayout(1);
				}
			}
		}

		// отсоединение присоединенной к реквизиту формы
		CWnd* pWndCld1 = pFView0->GetWindow(GW_CHILD);
		while(pWndCld1)
		{
			CWnd* pWndCld2 = pWndCld1;//->GetWindow(GW_CHILD);
			if(pWndCld2)
			{
				if(CString("CSplitterWnd") == pWndCld2->GetRuntimeClass()->m_lpszClassName)
				{
					CSplitterWnd* pSWnd = (CSplitterWnd*)pWndCld2;

					CFormExFormView* pPane = (CFormExFormView*)pSWnd->GetPane(0,0);
					if(pPane)
					{
						CFrameWnd* pWndFrame = pPane->m_frame;
						if(pWndFrame)
						{
							pPane->m_frame = NULL;
//							CMDIFrameWnd* pMain = GetMainFrame();
//							pWndFrame->SetParent(CWnd::FromHandle(pMain->m_hWndMDIClient));
							CWnd* pWnd = pPane->GetWindow(GW_CHILD);
							while(pWnd)
							{
								pWnd->SetParent(pWndFrame);
								pWnd = pPane->GetWindow(GW_CHILD);
							}
							pWndFrame->ShowWindow(SW_SHOW);
							((CTabFrame*)pWndFrame)->RecalcLayout(1);
						}
					}
				}
			}
			pWndCld1 = pWndCld1->GetNextWindow();
		}
	}

/*	conv.pV = adrOnCloseDocument;
	(This->*(conv.pOnCloseDocument))();

	adr1 = adrOnCloseDocument;
	for(i = 0; i<6;i++) *adr1++ = wrapOnCloseDocument[i];*/
	(This->*wrapperOnCloseDocument.GetOrigMethod())();

	wrapperOnCloseDocument.RestoreWrapAddress();

	_CallModuleProc(This,"ПослеЗакрытия","OnClosed",0,NULL);

	// artbear исправление бага 2503
	// http://cvs.alterplast.ru/bugs/show_bug.cgi?id=2503
	// чтобы точно определить факт открытия формы, кеш текущей закрываемой формы нужно удалить
	CString ID = "";
	ID.Format("%d", This->m_pBLModule);

	CModuleInfoFormEx* pModuleInfo;
	if(cModuleMap.Lookup(ID, (void *&)pModuleInfo))
	{
		CMapStringToPtr* pMap = &pModuleInfo->cProcMap;
		CString sKey;
		CProcInfoFormEx* pProcInfo;

		POSITION pos = pMap->GetStartPosition();
		while (pos)
		{
			pMap->GetNextAssoc(pos, sKey, (void *&)pProcInfo);
			if (pProcInfo)
				delete pProcInfo;
		}

		cModuleMap.RemoveKey(ID);
		delete pModuleInfo;
	}

	// end

	This->m_bAutoDelete = bAutoDelete;
	if(bAutoDelete)
	{
		CDocument* ThisDoc = (CDocument*)this;
		delete ThisDoc;
	}
}

class CGetDlgMy: public CGetDlg
{
public:
	CGetDlgMy(UINT uTempl,CWnd * pParent):CGetDlg(uTempl,pParent)
	{
	};

	static void SetLParam(long lNewParam)
	{
		m_lParam = lNewParam;
	};
	static long GetLParam(void)
	{
		return m_lParam;
	};

	virtual int DoModal()
	{
		// can be constructed with a resource template or InitModalIndirect
		ASSERT(m_lpszTemplateName != NULL || m_hDialogTemplate != NULL ||
			m_lpDialogTemplate != NULL);

		// load resource as necessary
		LPCDLGTEMPLATE lpDialogTemplate = m_lpDialogTemplate;
		HGLOBAL hDialogTemplate = m_hDialogTemplate;
		HINSTANCE hInst = AfxGetResourceHandle();
		if (m_lpszTemplateName != NULL)
		{
			hInst = AfxFindResourceHandle(m_lpszTemplateName, RT_DIALOG);
			HRSRC hResource = ::FindResource(hInst, m_lpszTemplateName, RT_DIALOG);
			hDialogTemplate = LoadResource(hInst, hResource);
		}
		if (hDialogTemplate != NULL)
			lpDialogTemplate = (LPCDLGTEMPLATE)LockResource(hDialogTemplate);

		// return -1 in case of failure to load the dialog template resource
		if (lpDialogTemplate == NULL)
			return -1;

		// disable parent (before creating dialog)
		HWND hWndParent = PreModal();
		AfxUnhookWindowCreate();
		BOOL bEnableParent = FALSE;
		if (hWndParent != NULL && ::IsWindowEnabled(hWndParent))
		{
			::EnableWindow(hWndParent, FALSE);
			bEnableParent = TRUE;
		}

		TRY
		{
			// create modeless dialog
			AfxHookWindowCreate(this);
			if (CreateDlgIndirect(lpDialogTemplate,
							CWnd::FromHandle(hWndParent), hInst))
			{
				if (m_nFlags & WF_CONTINUEMODAL)
				{
					// enter modal loop
					DWORD dwFlags = MLF_SHOWONIDLE;
					if (GetStyle() & DS_NOIDLEMSG)
						dwFlags |= MLF_NOIDLEMSG;
//					VERIFY(RunModalLoop(dwFlags) == m_nModalResult);
				}

				// hide the window before enabling the parent, etc.
//				if (m_hWnd != NULL)
//					SetWindowPos(NULL, 0, 0, 0, 0, SWP_HIDEWINDOW|
//						SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE|SWP_NOZORDER);
			}
		}
		CATCH_ALL(e)
		{
			DELETE_EXCEPTION(e);
			m_nModalResult = -1;
		}
		END_CATCH_ALL

		if (bEnableParent)
			::EnableWindow(hWndParent, TRUE);
		if (hWndParent != NULL && ::GetActiveWindow() == m_hWnd)
			::SetActiveWindow(hWndParent);

		// destroy modal window
//		DestroyWindow();
//		PostModal();

		// unlock/free resources as necessary
		if (m_lpszTemplateName != NULL || m_hDialogTemplate != NULL)
			UnlockResource(hDialogTemplate);
		if (m_lpszTemplateName != NULL)
			FreeResource(hDialogTemplate);

		return m_nModalResult;
	};

	DECLARE_MESSAGE_MAP()

	void OnDestroy(void);
};

BEGIN_MESSAGE_MAP(CGetDlgMy, CGetDlg)
	ON_WM_DESTROY()
END_MESSAGE_MAP()

void CGetDlgMy::OnDestroy(void)
{
};

//CGetDlg::OpenDocumentFileEx LPCSTR
void  WrapOpenDocumentFileEx(UINT a_uParam1,LPCSTR a_chStr,long a_lParam,CValue * a_pVal,UINT a_uParam2,UINT a_uParam3,UINT a_uParam4,UINT a_uParam5)
{
//	memcpy(adrOpenDocumentFileEx, origOpenDocumentFileEx, 6);
	wrapperOpenDocumentFileEx.RestoreOrigAddress();

	if(pWndToDock)
	{
		//CSizingControlBar* l_pWndToDock = pWndToDock;
		CWnd* l_pWndToDock = pWndToDock;
		pWndToDock = NULL;

//		memcpy(adrOpenDocumentFileEx, wrapOpenDocumentFileEx, 6);
		wrapperOpenDocumentFileEx.RestoreWrapAddress();

		CGetDlgMy::SetLParam(a_lParam);
		CGetDlgMy* pGetDlg;
		if(l_pWndToDock->IsKindOf(RUNTIME_CLASS(CSizingControlBar)))
		{
			pGetDlg = new CGetDlgMy(a_uParam3,pWndToDock);
		}
		else
		{
			pGetDlg = new CGetDlgMy(a_uParam3,NULL);
		}

		if(a_pVal)
		{
			CType cType(0);
			cType.m_flags = 0;
			cType.m_length = 0;
			cType.m_mdid = 0;
			cType.m_prec = 0;
			cType.type = 0;
			a_pVal->SetType(cType);
		}
		pGetDlg->m_pValue = a_pVal;
		pGetDlg->bufGetDlg[0x00] = a_uParam2;
		pGetDlg->bufGetDlg[0x01] = a_uParam4;
		pGetDlg->bufGetDlg[0x02] = a_uParam5;

		pGetDlg->m_TemplID = a_uParam1;
		pGetDlg->m_cStr = a_chStr;

		//SetModalMode(1);
		SetModalMode(0);

		int n = 0;

		while(((CApp7*)pApp)->IsWaiting())
		{
			((CApp7*)pApp)->StopWait(0xE001);
			n++;
		}

		pGetDlg->DoModal();

		if(l_pWndToDock->IsKindOf(RUNTIME_CLASS(CSizingControlBar)))
		{
			pGetDlg->ModifyStyle(WS_POPUPWINDOW|DS_MODALFRAME|WS_CAPTION,WS_CHILD);
			pGetDlg->ModifyStyleEx(WS_EX_DLGMODALFRAME|WS_EX_CLIENTEDGE, 0);
			pGetDlg->SetParent(l_pWndToDock);
			((CSizingControlBar*)l_pWndToDock)->m_pChildDlg = pGetDlg;
		}

		while(n > 0)
		{
			n--;
			((CApp7*)pApp)->StartWait();
		}

		//SetModalMode(0);

		CGetDlgMy::SetLParam(0);
	}
	else
	{
		CGetDlg::OpenDocumentFileEx(a_uParam1,a_chStr,a_lParam,a_pVal,a_uParam2,a_uParam3,a_uParam4,a_uParam5);
//		memcpy(adrOpenDocumentFileEx, wrapOpenDocumentFileEx, 6);
		wrapperOpenDocumentFileEx.RestoreWrapAddress();
	}
}

//CGetDlg::OnInitDialog
int CWrapModule::WrapOnInitDialog(void)
{
/*	BYTE* adr1 = adrOnInitDialog;
	for(int i = 0; i<6;i++) *adr1++ = origOnInitDialog[i];

	conv.pV = adrOnInitDialog;
	int ret = (((CGetDlg*)this)->*(conv.pOnInitDlg))();

	adr1 = adrOnInitDialog;
	for(i = 0; i<6;i++) *adr1++ = wrapOnInitDialog[i];*/
	wrapperOnInitDialog.RestoreOrigAddress();
	int ret = (((CGetDlg*)this)->*wrapperOnInitDialog.GetOrigMethod())();

	wrapperOnInitDialog.RestoreWrapAddress();

	CGetDoc7* pDoc = CGetDlg::GetTopmostDocunent();
	int iStatusCode = 1;
	if(pDoc)
	{
		CBLModule7* pMod = pDoc->m_pBLModule;
		if(pMod)
			iStatusCode = pMod->GetStatusCode();
	}
	if(iStatusCode)
	{
// /*// artbear Зачем этот код по отрисовке ?
		((CGetDlg*)this)->CenterWindow();
		((CGetDlg*)this)->ShowWindow(SW_SHOW);
		((CGetDlg*)this)->UpdateWindow();
		((CGetDlg*)this)->UpdateData();
		((CGetDlg*)this)->RedrawWindow();
//*/
		_CallModuleProc(pDoc,"ПослеОткрытия","OnActivate",0,NULL);
// /*
		((CGetDlg*)this)->Invalidate();
//end */	
	}

	return ret;
}

//CBrowseView7::OnInitialUpdate
void CWrapModule::WrapOnInitialUpdate(void)
{
/*	BYTE* adr1 = adrOnInitialUpdate;
	for(int i = 0; i<6;i++) *adr1++ = origOnInitialUpdate[i];

	conv.pV = adrOnInitialUpdate;
	(((CBrowseView7*)this)->*(conv.pOnInitUp))();

	adr1 = adrOnInitialUpdate;
	for(i = 0; i<6;i++) *adr1++ = wrapOnInitialUpdate[i];*/
	wrapperOnInitialUpdate.RestoreOrigAddress();
	(((CBrowseView7*)this)->*wrapperOnInitialUpdate.GetOrigMethod())();

	wrapperOnInitialUpdate.RestoreWrapAddress();

	CGetDoc7* pDoc = ((CBrowseView7*)this)->GetDocument();

	int iStatusCode = 0;
	if(pDoc)
	{
		CBLModule7* pMod = pDoc->m_pBLModule;
		if(pMod)
			iStatusCode = pMod->GetStatusCode();
	}
	if(iStatusCode)
	{
		CWnd* pWnd = ((CBrowseView7*)this)->GetParent();
		if(pWnd->IsKindOf(RUNTIME_CLASS(CSplitterWnd)))
		{
			CSplitterWnd* pSplitterWnd = (CSplitterWnd*)pWnd;
			int countCol = pSplitterWnd->GetColumnCount();
			int countRow = pSplitterWnd->GetRowCount();
			for(int iCol = 0; iCol < countCol; iCol++)
				for(int iRow = 0; iRow < countRow; iRow++)
				{
					CWnd* pPane = pSplitterWnd->GetPane(iRow, iCol);
					if(pPane->IsKindOf(RUNTIME_CLASS(CSheetView)))
					{
						CSheetViewMy* pSheetView = (CSheetViewMy*)pPane;
						pSheetView->OnInitialUpdate();
					}
				}
		}

// АЛьФ ------------------>
// перерисовка вызывает торможение при открытии форм (формы открываются в два раза медленней)
// однако без перерисовки возможны глюки при включении своей отрисовки контролов.
// пока убираю, но на будущее необходимо это дело запомнить.
// <------------------- АЛьФ

		ActivateOpenDocFrame(pDoc);
//		pMainWindow->RedrawWindow();
		_CallModuleProc(pDoc,"ПослеОткрытия","OnActivate",0,NULL);
		pDoc->UpdateAllViews(NULL);
//		((CBrowseView7*)this)->RedrawWindow();
//		pMainWindow->RedrawWindow();

// artbear Выполню ускорение контекста, в т.ч. и для внешних отчетов, и 
// 1)	тогда будет возможность обращаться к переменным и методам любой формы напрямую (TurboBL)
// 2)	самое главное, для внешних отчетов больше нет необходимости создавать объект "УскорительГК"
//
#ifndef FORMEX_DLL
		{
			// при включенной отладке не удается загрузить классы, храняющиеся во внешних файлах отчетов/обработок
			if(!pMainAddIn->m_EnableDebugging)
			{
				//Msg("WrapOnInitialUpdate ПослеОткрытия");
				CBLModule7* pMod = pDoc->m_pBLModule;
				CGroupContext * pCont = (CGroupContext*)CBLModuleWrapper::GetContextFromModule(pMod);
				if(pCont)
				{
					if(!CGCBoost::Boost(pMod, false))
						CBLModule::RaiseExtRuntimeError("Ошибка ускорения контекста",0);
				}
			}
		}
#endif
//end
	}
}

//CGetDoc::UpdateData
int  CWrapModule::WrapUpdateData(int i1,unsigned int ui1)
{
	int ret = 0;
/*	BYTE* adr1 = adrUpdateData;
	for(int i = 0; i<6;i++) *adr1++ = origUpdateData[i];

	conv.pV = adrUpdateData;
	ret = (((CGetDoc*)this)->*(conv.pOnUpData))(i1, ui1);

	adr1 = adrUpdateData;
	for(i = 0; i<6;i++) *adr1++ = wrapUpdateData[i];*/
	wrapperUpdateData.RestoreOrigAddress();
	ret = (((CGetDoc*)this)->*wrapperUpdateData.GetOrigMethod())(i1, ui1);

	wrapperUpdateData.RestoreWrapAddress();

//	if(((CObject*)this)->IsKindOf(RUNTIME_CLASS(CGetDoc7)))
//		_CallModuleProc(reinterpret_cast<CGetDoc7*>(this),"ПослеОбновленияФормы","OnRefresh",0,NULL);

	return ret;
}

//CGetDoc7::WrapLoadDialog
int  CWrapModule::WrapLoadDialog(long lID,char const * pFolder)
{
	int ret = 0;
//	memcpy(adrLoadDialog, origLoadDialog, 6);
	wrapperLoadDialog.RestoreOrigAddress();

	long _lID = lID;
	char const * _pFolder = pFolder;
	CEditDoc* pEditDoc = NULL;

	CGetDoc7* This = (CGetDoc7*)this;

	if(pGlobalModuleFormEx)
	{
		int r = pGlobalModuleFormEx->FindProc("ПриЗагрузкеФормы",0);
		if(r >= 0)
		{
			CValue cVal;
			CValue* pVal;
			pVal = &cVal;
			CTypedCont* pCont=NULL;
			CString name;
			CConfigCont::IDToPath(lID, pFolder, name, &pCont, FALSE);
			if(pCont)
			{
				CWorkBookDoc* pWBDoc = pCont->GetWorkBook();
				if(pWBDoc)
				{
					pEditDoc = (CEditDoc*)pWBDoc->GetDEditDocument();
				}
			}

			CMetaDataCont * pMDCont = NULL;

			if (lID > 0)
				name = GetModuleFullName(lID, pFolder, 0, pMDCont);
			else
				name = "НеизвестныйОбъект";

			cVal = name;

			pGlobalModuleFormEx->CallAsProc(r,1,&pVal);

			CString nameNew;
			nameNew = cVal.GetString();
			nameNew.MakeUpper();
			if(name.CollateNoCase(nameNew) != 0)
			{
				SDocNames *pDocNames = NULL;
				if(DocNamesArray.Lookup(nameNew, (void*&)pDocNames))
				{
					_lID = pDocNames->id;
					_pFolder = LPCSTR(pDocNames->strFolder);
				}
			}
		}
	}

/*	conv.pV = adrLoadDialog;
	ret = (This->*(conv.pLoadDialog))(_lID, _pFolder);

	memcpy(adrLoadDialog, wrapLoadDialog, 6);*/
	ret = (This->*wrapperLoadDialog.GetOrigMethod())(_lID, _pFolder);

	wrapperLoadDialog.RestoreWrapAddress();

	CEditDoc* pEditDocNew = This->m_pEditDoc;
	if((pEditDoc != NULL) && (pEditDocNew != NULL) && (pEditDocNew != pEditDoc))
	{
		int szN = pEditDocNew->m_extListSA.GetSize();
		if(szN == 0)
		{
			int sz = pEditDoc->m_extListSA.GetSize();
			int szU = pEditDoc->m_extListUA.GetSize();
			for(int i = 0; i < sz; i++)
			{
				CString str = pEditDoc->m_extListSA.GetAt(i);
				UINT n = 1;
				pEditDocNew->m_extListSA.Add(str);
				pEditDocNew->m_extListUA.Add(n);
				CCtrlHolder* pCtrl = (CCtrlHolder*)pEditDoc->m_extCtrlArray.GetAt(i);

				if(pCtrl)
				{
					POSITION pos = pEditDocNew->m_objList.GetHeadPosition();
					while(pos)
					{
						CCtrlHolder* pCtrlNew = (CCtrlHolder*)pEditDocNew->m_objList.GetNext(pos);
						if(pCtrlNew)
						{
							if(str.CompareNoCase(pCtrlNew->m_pName) == 0)
							{
								pCtrlNew->m_ID = pCtrl->m_ID;
								pos = NULL;
							}
						}
					}
					pos = This->m_cControlList.GetHeadPosition();
					while(pos)
					{
						CControlID* pControlIDNew = (CControlID*)This->m_cControlList.GetNext(pos);
						if(pControlIDNew)
						{
							if(str.CompareNoCase(pControlIDNew->m_CodeName) == 0)
							{
								pControlIDNew->m_LongID = pCtrl->m_ID;
								pos = NULL;
							}
						}
					}
				}
			}
		}
	}

	return ret;
}

//CGetDoc7::WrapLoadForm
int  CWrapModule::WrapLoadForm(long lID,char const * pFolder)
{
	int ret = 0;

	long _lID = lID;
	char const * _pFolder = pFolder;
	CEditDoc* pEditDoc = NULL;

	CGetDoc7* This = (CGetDoc7*)this;

	if(pGlobalModuleFormEx)
	{
		int r = pGlobalModuleFormEx->FindProc("ПриЗагрузкеМодуляФормы",0);
		if(r >= 0)
		{
			CValue cVal;
			CValue* pVal;
			pVal = &cVal;
			CTypedCont* pCont=NULL;
			CString name;
			CConfigCont::IDToPath(lID, pFolder, name, &pCont, FALSE);
			if(pCont)
			{
				CWorkBookDoc* pWBDoc = pCont->GetWorkBook();
				if(pWBDoc)
				{
					pEditDoc = (CEditDoc*)pWBDoc->GetDEditDocument();
				}
			}

			CMetaDataCont * pMDCont = NULL;

			if (lID > 0)
				name = GetModuleFullName(lID, pFolder, 0, pMDCont);
			else
				name = "НеизвестныйОбъект";

			cVal = name;

			pGlobalModuleFormEx->CallAsProc(r,1,&pVal);

			CString nameNew;
			nameNew = cVal.GetString();
			nameNew.MakeUpper();
			if(name.CollateNoCase(nameNew) != 0)
			{
				SDocNames *pDocNames = NULL;
				if(DocNamesArray.Lookup(nameNew, (void*&)pDocNames))
				{
					_lID = pDocNames->id;
					_pFolder = LPCSTR(pDocNames->strFolder);
				}
			}
		}
	}

/*	conv.pV = adrLoadForm;
	ret = (This->*(conv.pLoadForm))(_lID, _pFolder);

	memcpy(adrLoadForm, wrapLoadForm, 6);*/
	wrapperLoadForm.RestoreOrigAddress();
	ret = (This->*wrapperLoadForm.GetOrigMethod())(_lID, _pFolder);

	wrapperLoadForm.RestoreWrapAddress();

	return ret;
}

//CEditDoc::DoLoadExternal
int CWrapModule::WrapDoLoadExternal(LPCSTR a_strFileName)
{
	int ret = 0;
//	memcpy(adrDoLoadExternal, origDoLoadExternal, 6);
	wrapperDoLoadExternal.RestoreOrigAddress();

	CEditDoc* This = (CEditDoc*)this;

	CString s_strFileName = CString(a_strFileName);
	if(s_strFileName.Right(14).CompareNoCase("\\Dialog Stream") == 0)
	{
		s_strFileName = s_strFileName.Left(s_strFileName.GetLength() - 14);
	}
	CValue vFileName = s_strFileName;
	CValue *lArray[1] = {&vFileName};
	//_CallModuleProc(NULL,"ПриЗагрузкеВнешнегоОтчета","OnLoadAsExternalForm",1,lArray);

	int iStatusCode = pGlobalModuleFormEx->GetStatusCode();
	pGlobalModuleFormEx->SetStatusCode(1);

	_CallFromGlobalModules(NULL,NULL,"ПриЗагрузкеВнешнегоОтчета","OnLoadAsExternalForm",1,lArray);
	if(pGlobalModuleFormEx->GetStatusCode() == 0)
	{
		ret = 0;
	}
	else
	{
/*		conv.pV = adrDoLoadExternal;
		ret = (This->*(conv.pDoLoadExternal))(a_strFileName);*/
		ret = (This->*wrapperDoLoadExternal.GetOrigMethod())(a_strFileName);
	}

	pGlobalModuleFormEx->SetStatusCode(iStatusCode);

//	memcpy(adrDoLoadExternal, wrapDoLoadExternal, 6);
	wrapperDoLoadExternal.RestoreWrapAddress();

	return ret;
}

void CWrapModule::WrapGetDataImageCol(CString& a_Str)
{
//	memcpy(adrGetDataImageCol, origGetDataImageCol, 6);
	wrapperGetDataImageCol.RestoreOrigAddress();

	CImageCol* This = (CImageCol*)this;
/*	conv.pV = adrGetDataImageCol;
	(This->*(conv.pGetDataImageCol))(a_Str);
	memcpy(adrGetDataImageCol, wrapGetDataImageCol, 6);*/
	(This->*wrapperGetDataImageCol.GetOrigMethod())(a_Str);

	wrapperGetDataImageCol.RestoreWrapAddress();

	CBrowse* pBr = This->m_Browse;
	if(pBr)
	{
		CWnd* pParent = pBr->GetParent();
		if(pParent)
		{
			CGetDoc7* pDoc = NULL;
			if(pParent->IsKindOf(RUNTIME_CLASS(CGetDlg)))
			{
				pDoc = ((CGetDlg*)pParent)->m_pDoc;
			}
			else if(pParent->IsKindOf(RUNTIME_CLASS(CBrowseView7)))
			{
				pDoc = ((CBrowseView7*)pParent)->GetDocument();
			}
			CValue vPicNum = a_Str;
			CValue *lArray[1] = {&vPicNum};
			_CallModuleProc(pDoc,"ПиктограммаМногострочнойЧасти","MultiLinePic",1,lArray);
			a_Str = vPicNum.Format();
		}
	}
}


int  CWrapModule::WrapLayoutForm(class CFormView * pFormView)
{
	int ret = 0;
/*	BYTE* adr1 = adrLayoutForm;
	for(int i = 0; i<6;i++) *adr1++ = origLayoutForm[i];

	conv.pV = adrLayoutForm;
	ret = (((CGetDoc7*)this)->*(conv.pLayF))(pFormView);

	adr1 = adrLayoutForm;
	for(i = 0; i<6;i++) *adr1++ = wrapLayoutForm[i];*/
	wrapperLayoutForm.RestoreOrigAddress();
	ret = (((CGetDoc7*)this)->*wrapperLayoutForm.GetOrigMethod())(pFormView);

	wrapperLayoutForm.RestoreWrapAddress();

	_CallModuleProc(reinterpret_cast<CGetDoc7*>(this),"ПослеСозданияФормы","OnCreateForm",0,NULL);

	return ret;
}

/*// artbear - этот метод переопределяется в ТурбоБЛ TurboBL
int  CWrapModule::WrapFindMethod(char const * fName)const
{
	int ret = 0;
	BYTE* adr1 = adrFindMethod;
	for(int i = 0; i<6;i++) *adr1++ = origFindMethod[i];

Msg("%s %s", "CWrapModule::WrapFindMethod fName", fName);
Msg("%s %s ", "(CBLContext* )this->GetRuntimeClass()->m_lpszClassName", ((CBLContext* )this)->GetRuntimeClass()->m_lpszClassName);

	conv.pV = adrFindMethod;
	//ret = (((CBLContext*)this)->*(conv.pContextFindMethod))(fName);

//	CBLContext* pCont = CBLContext::GetLoadedContext(1);
	CBLContext* pCont = (CBLContext*)this;
Msg("1%s %s ", "pCont->GetRuntimeClass()->m_lpszClassName", pCont->GetRuntimeClass()->m_lpszClassName);
	
	ret = ((pCont)->*(conv.pContextFindMethod))(fName);
	//ret = (((CGeneralContextDef*)this)->*(conv.pContextFindMethod))(fName);
	
///*	CGCBoost::SGCInfo* obGetInfo = (CGCBoost::SGCInfo*)pCont->m_FlagAutoDestroy;
Msg("2%s %s ", "pCont->GetRuntimeClass()->m_lpszClassName", pCont->GetRuntimeClass()->m_lpszClassName);
	if (!obGetInfo)
Msg("ошибка obGetInfo == 0 %s %s ", "pCont->GetRuntimeClass()->m_lpszClassName", pCont->GetRuntimeClass()->m_lpszClassName);
	CGCBoost::SGCData* obGetData = obGetInfo->m_pData;
	if (!obGetData)
Msg("ошибка obGetData == 0 %s %s ", "pCont->GetRuntimeClass()->m_lpszClassName", pCont->GetRuntimeClass()->m_lpszClassName);
Msg("3%s %s ", "pCont->GetRuntimeClass()->m_lpszClassName", pCont->GetRuntimeClass()->m_lpszClassName);
	ret = obGetData->FindMethod(fName);
///

Msg("%s %s ", "ret", ret);

	adr1 = adrFindMethod;
	for(i = 0; i<6;i++) *adr1++ = wrapFindMethod[i];
Msg("%s %d", "CWrapModule::WrapFindMethod index", ret);

	return ret;
}
//end
*/

int  CWrapModule::WrapGetHiTrackBound(int iNum)
{
	int ret = 0;
	wrapperGetHiTrackBound.RestoreOrigAddress();

	/*
	UINT uFlag = ((DWORD*)this)[0x27];
	if(uFlag == 0)
	{
		CRect cRect;
		((CBrowse*)this)->GetCellRect(cRect,0,iNum);
		ret = cRect.right+1;
	}
	else
	{
		conv.pV = adrGetHiTrackBound;
		ret = (((CBrowse*)this)->*(conv.pGHTB))(iNum);
	}
	*/
/*		conv.pV = adrGetHiTrackBound;
		ret = (((CBrowse*)this)->*(conv.pGHTB))(iNum);

	adr1 = adrGetHiTrackBound;
	for(i = 0; i<6;i++) *adr1++ = wrapGetHiTrackBound[i];*/
	ret = (((CBrowse*)this)->*wrapperGetHiTrackBound.GetOrigMethod())(iNum);

	wrapperGetHiTrackBound.RestoreWrapAddress();

	return ret;
}

int  CWrapModule::WrapGetLoTrackBound(int iNum)
{
	int ret = 0;
/*	BYTE* adr1 = adrGetLoTrackBound;
	for(int i = 0; i<6;i++) *adr1++ = origGetLoTrackBound[i];*/
	wrapperGetLoTrackBound.RestoreOrigAddress();

	/*
	UINT uFlag = ((DWORD*)this)[0x27];
	if(uFlag == 0)
	{
		CRect cRect;
		((CBrowse*)this)->GetCellRect(cRect,0,iNum);
		ret = cRect.right+1;
	}
	else
	{
		conv.pV = adrGetLoTrackBound;
		ret = (((CBrowse*)this)->*(conv.pGLTB))(iNum);
	}
	*/
/*		conv.pV = adrGetLoTrackBound;
		ret = (((CBrowse*)this)->*(conv.pGLTB))(iNum);

	adr1 = adrGetLoTrackBound;
	for(i = 0; i<6;i++) *adr1++ = wrapGetLoTrackBound[i];*/
	ret = (((CBrowse*)this)->*wrapperGetLoTrackBound.GetOrigMethod())(iNum);

	wrapperGetLoTrackBound.RestoreWrapAddress();

	return ret;
}

class CWnd * CWrapModule::WrapCreateControl(class CGetField * pGetField,unsigned int id,class CRect const & rect,class CWnd * pParent,unsigned long style,unsigned long styleex)
{
	CControlID* set = pGetField->m_Set;
	CWnd * ret = NULL;
	wrapperCreateControl.RestoreOrigAddress();

	DWORD dwStyle = 0;
	if(set)
	{
		dwStyle = set->m_DependParam;
		if(bSetDrawWrap)
		{
			if((set->m_CtrlType == 0x0B) && ((dwStyle & 0x02000000) == 0))
			{
				style |= LBS_HASSTRINGS|LBS_OWNERDRAWFIXED;
			}
			else if(set->m_CtrlType == 0x0E)
			{
				style |= CBS_HASSTRINGS|CBS_OWNERDRAWFIXED;
			}
		}
	}

	ret = ((CGetDoc7*)this)->CreateControl(pGetField,id,rect,pParent,style,styleex);

	if(bSetDrawWrap)
	{
		if((ret != NULL) && (set != NULL) && (set->m_CtrlType == 0x0B) && ((dwStyle & 0x02000000) == 0))
		{
			CFormExListBox* pLB;
			pLB = new CFormExListBox;
			if(pLB)
			{
				pLB->SubclassWindow(ret->GetSafeHwnd());
				pLB->SetFont(ret->GetFont());
			}
		}
		else if((ret != NULL) && (set != NULL) && (set->m_CtrlType == 0x0E))// && ((dwStyle & 0x02000000) == 0))
		{
			CFormExComboBox* pCB;
			pCB = new CFormExComboBox;
			if(pCB)
			{
				pCB->SubclassWindow(ret->GetSafeHwnd());
				pCB->SetFont(ret->GetFont());
			}
		}

		if((ret != NULL) && (set != NULL))
		{
			if(set->m_CtrlType == 0x05)
			{
				CFont cFont;
				cFont.CreateFontIndirect(&(set->m_Font));
				HFONT hFont = (HFONT)cFont.Detach();
				ret->SetFont(CFont::FromHandle(hFont));
				ret->RedrawWindow();
			}
		}
	}

	wrapperCreateControl.RestoreWrapAddress();

	return ret;
}

void CWrapModule::WrapProcessSecondOpen(CValue* val)
{
	wrapperProcessSecondOpen.RestoreOrigAddress();

	CGetDoc7* This = (CGetDoc7*)this;
	This->ProcessSecondOpen(val);

	CGroupContext *pCont = This->GetGroupContext();
	if(pCont)
	{
		CBLContext *pCont0;
		for(int i = 0; i<pCont->GetSize(); i++)
		{
			pCont0 = pCont->GetContext(i);
			if(!strcmp(pCont0->GetRuntimeClass()->m_lpszClassName,"CDocContext"))
				((CDocContext*)pCont0)->SetEnableNewLine(1);
		}
	}
	wrapperProcessSecondOpen.RestoreWrapAddress();

}

/*
class CSbCntDoc * WrapActivateSubkList(	long lID,
										class CObjID cObjID_1,
										UINT ui_1,
										UINT ui_2,
										class CObjID cObjID_2,
										class CString str_1,
										class CDate date_1,
										int i_1,
										class CObjID cObjID_3,
										int i_2,
										long lID_2,
										int i_3,
										class CValue * pValue_1,
										class CString str_2,
										int i_4,
										int i_5,
										int i_6,
										class CValue * pValue_2)
{
	CSbCntDoc * ret = NULL;
	BYTE* adr1 = adrActivateSubkList;
	for(int i = 0; i<6;i++) *adr1++ = origActivateSubkList[i];

	ret = ActivateSubkList(	lID, cObjID_1, ui_1, ui_2, cObjID_2, str_1, date_1, i_1,
							cObjID_3, i_2, lID_2, i_3, pValue_1, str_2, i_4, i_5, i_6,
							pValue_2);

	adr1 = adrActivateSubkList;
	for(i = 0; i<6;i++) *adr1++ = wrapActivateSubkList[i];

	return ret;
}
*/

void DX_TextWrap(class CGetExchange * pGet,int iID,class CValue & cVal)
{
	wrapperDX_Text.RestoreOrigAddress();

	DX_Text(pGet,iID,cVal);

	if(bSetDrawWrap)
	{
		if(pGet)
		{
			CGetCtrl* pCtrl = pGet->PrepareControl(iID);
			if(pCtrl)
			{
				CWnd* pWnd = pCtrl->GetDlgItem();
				if(pWnd)
				{
					CGetDoc7* pDoc = (CGetDoc7*)pCtrl->m_pGetDoc;
					CGetFieldsArray* pGetFieldsArray = NULL;
					CGetField* pGetField = NULL;
					CControlID* pControlID = NULL;
					int num = pDoc->GetCtrlN(pCtrl);
					if(num >= 0)
					{
						pGetFieldsArray = (CGetFieldsArray*)(&(((CGetDoc77*)pDoc)->m_Array));
						if((pGetFieldsArray != NULL) && (pGetFieldsArray->GetSize() > num))
						{
							pGetField = pGetFieldsArray->GetAt(num);
							if(pGetField)
							{
								pControlID = pGetField->GetCtrlInfo();
								if(pControlID)
								{
									UINT CtrlType = pControlID->GetCtrlType();
									switch(CtrlType)
									{
									case 1://STATIC (Текст)
										{
											pWnd->Invalidate();
											break;
										}
									case 2://1CEDIT (Поле ввода)
										{
											break;
										}
									case 3://BUTTON (Кнопка)
										{
											break;
										}
									case 4://1CGROUPBOX (Рамка группы)
										{
											break;
										}
									case 5://1CEDIT (Колонка многострочной части редактируемая)
										{
											break;
										}
									case 8://SysTreeView32 (Дерево групп)
										{
											break;
										}
									case 9://STATIC (Колонка многострочной части с пикторгаммой или просто текстовая)
										{
											break;
										}
									case 10://PICTURE (Картинка)
										{
											break;
										}
									case 11://LISTBOX (Список)
										{
											break;
										}
									case 12://CHECKBOX (Флажок)
										{
											//pWnd->InvalidateRect(NULL);
											break;
										}
									case 13://RADIO (Переключатель)
										{
											break;
										}
									case 14://COMBOBOX (Поле со списком)
										{
											break;
										}
									case 15://TABLE (Таблица)
										{
											break;
										}
									default: 
										{
										}
									};
								}
							}
						}
					}
				}
			}
		}
	}

	wrapperDX_Text.RestoreWrapAddress();
}

void CWrapModule::CheckListBoxDrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	((CFormExCheckListBox*)this)->MyDrawItem(lpDrawItemStruct);
}

BOOL CWrapModule::CheckListBoxOnChildNotify(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
	return ((CFormExCheckListBox*)this)->MyOnChildNotify(message, wParam, lParam, pResult);
}

void CFormExCheckListBox::MyDrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	ASSERT((GetStyle() & (LBS_OWNERDRAWFIXED | LBS_HASSTRINGS)) ==
		(LBS_OWNERDRAWFIXED | LBS_HASSTRINGS));

	CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC);

	if (((LONG)(lpDrawItemStruct->itemID) >= 0) &&
		(lpDrawItemStruct->itemAction & (ODA_DRAWENTIRE | ODA_SELECT)))
	{
		int cyItem = GetItemHeight(lpDrawItemStruct->itemID);

		if (m_cyText == 0)
			VERIFY(cyItem >= CalcMinimumItemHeight());

		CString strText;
		GetText(lpDrawItemStruct->itemID, strText);

		COLORREF newTextColor = GetSysColor(COLOR_WINDOWTEXT);
		COLORREF newBkColor = GetSysColor(COLOR_WINDOW);

		COLORREF oldTextColor = pDC->SetTextColor(newTextColor);
		COLORREF oldBkColor = pDC->SetBkColor(newBkColor);

		COLORREF crBkColor = ::GetSysColor(COLOR_WINDOW);
		COLORREF crBkColorSel = ::GetSysColor(COLOR_ACTIVECAPTION);
		COLORREF crTextColor = ::GetSysColor(COLOR_WINDOWTEXT);
		COLORREF crTextColorSel = RGB(0xFF,0xFF,0xFF);
		DWORD fontSetS = 0;
		DWORD fontSet = 0;

		CString st_buf = strText;
		st_buf.MakeUpper();
		char ** endptr = NULL;
		const char * ptr = NULL;
					
		int iBuf = st_buf.Find("FONTSET_S[",0);
		if(iBuf >= 0)
		{
			iBuf += 10;
			if(st_buf.Mid(iBuf, 4) != "NONE")
				fontSetS = (DWORD)atol(st_buf.Mid(iBuf));
		}
		iBuf = st_buf.Find("FONTSET[",0);
		if(iBuf >= 0)
		{
			iBuf += 8;
			if(st_buf.Mid(iBuf, 4) != "NONE")
				fontSet = (DWORD)atol(st_buf.Mid(iBuf));
		}
		iBuf = st_buf.Find("FONT_S[",0);
		if(iBuf >= 0)
		{
			iBuf  += 7;
			if(st_buf.Mid(iBuf , 4) != "NONE")
			{
				ptr = st_buf.Mid(iBuf);
				endptr = (char**)&ptr;
				crTextColorSel = strtol(ptr,endptr,0);
			}
		}
		iBuf = st_buf.Find("FONT[",0);
		if(iBuf >= 0)
		{
			iBuf += 5;
			if(st_buf.Mid(iBuf, 4) != "NONE")
			{
				ptr = st_buf.Mid(iBuf);
				endptr = (char**)&ptr;
				crTextColor = strtol(ptr,endptr,0);
			}
		}
		iBuf = st_buf.Find("BRUSH_S[",0);
		if(iBuf >= 0)
		{
			iBuf += 8;
			if(st_buf.Mid(iBuf, 4) != "NONE")
			{
				ptr = st_buf.Mid(iBuf);
				endptr = (char**)&ptr;
				crBkColorSel = strtol(ptr,endptr,0);
			}
		}
		iBuf = st_buf.Find("BRUSH[",0);
		if(iBuf >= 0)
		{
			iBuf += 6;
			if(st_buf.Mid(iBuf, 4) != "NONE")
			{
				ptr = st_buf.Mid(iBuf);
				endptr = (char**)&ptr;
				crBkColor = strtol(ptr,endptr,0);
			}
		}

		CImageList cImageList;
		cImageList.Create(13, 16, ILC_MASK, 2, 0);

		iBuf = st_buf.Find("IMAGE[",0);
		if(iBuf >= 0)
		{
			iBuf += 6;
			int iBufEnd = st_buf.Find("]",iBuf);
			if(iBufEnd > iBuf)
			{
				CString strAlias = st_buf.Mid(iBuf, iBufEnd - iBuf);
				CGalleryHolder * pGalleryHolder = CGalleryHolder::GetGallery();
				if(pGalleryHolder)
				{
					ULONG picID = pGalleryHolder->FindByAlias(strAlias);
					if(picID)
					{
						CPictureHolder7 * pic;
						pic = new CPictureHolder7(pGalleryHolder->GetPicture(picID));

						CBitmap bitmap;
						BOOL bResult = FALSE;
						CDC dcMem;

						if (dcMem.CreateCompatibleDC(pDC))
						{
							CSize hmSize = pic->GetSize();

							CBitmap bmMem;

							if (bmMem.CreateCompatibleBitmap(pDC, hmSize.cx, 16))
							{
								CBitmap* pOldBM = dcMem.SelectObject(&bmMem);

								dcMem.FillSolidRect(0, 0, hmSize.cx, 16, RGB(0x00,0x80,0x80));
								RECT rect1;
								RECT rect2;
								rect1.top = rect1.left = 0;
								rect1.right = hmSize.cx;
								if(hmSize.cy<16) rect1.bottom = hmSize.cy;
								else rect1.bottom = 16;
								
								pic->Render(dcMem, rect1, 0, &rect2);

								bResult = bitmap.Attach(bmMem.Detach());

								dcMem.SelectObject(pOldBM);
							}
						}

						if(bResult)
						{
							cImageList.Add(&bitmap, RGB(0x00,0x80,0x80));
						}
					}
				}
			}
		}

		if(cImageList.GetImageCount() == 0)
		{
			HBITMAP hBitmap;
			hBitmap = ::LoadBitmap(hDllInstance,MAKEINTRESOURCE(IDB_CHECKS));
			cImageList.Add(CBitmap::FromHandle(hBitmap), RGB(0x00,0x80,0x80));
			::DeleteObject(hBitmap);
		}

		CFont* pOldFont = pDC->SelectObject(GetFont());

		CRect itemRect = lpDrawItemStruct->rcItem;

		if((lpDrawItemStruct->itemState & ODS_SELECTED))
		{
			pDC->FillSolidRect(itemRect, crBkColorSel);
			pDC->SetTextColor(crTextColorSel);
			if(fontSetS)
				pDC->SelectObject(CFont::FromHandle((HFONT)fontSetS));
			else if(fontSet)
				pDC->SelectObject(CFont::FromHandle((HFONT)fontSet));
		}
		else
		{
			pDC->FillSolidRect(itemRect, crBkColor);
			pDC->SetTextColor(crTextColor);
			if(fontSet)
				pDC->SelectObject(CFont::FromHandle((HFONT)fontSet));
		}

		int nCheck = GetCheck(lpDrawItemStruct->itemID);

		CRect rectCheck = lpDrawItemStruct->rcItem;
		rectCheck.left += 0;
		rectCheck.top += 1 + max(0, (cyItem - 16) / 2);

		cImageList.Draw(pDC, nCheck, rectCheck.TopLeft(), ILD_NORMAL);

		int n = strText.Find("\r");
		if(n>=0) strText = strText.Left(n);

		CRect textRect = itemRect;
		//textRect.DeflateRect(2,0);
		int h = textRect.Height();
		textRect.top = lpDrawItemStruct->rcItem.top + max(0, (cyItem - m_cyText) / 2);
		textRect.bottom = textRect.top + h;
		textRect.left += 13;

		pDC->DrawText(strText, textRect, DT_VCENTER | DT_SINGLELINE | DT_EXPANDTABS);

		pDC->SetTextColor(oldTextColor);
		pDC->SetBkColor(oldBkColor);
		pDC->SelectObject(pOldFont);
	}

	if ((lpDrawItemStruct->itemAction & ODA_FOCUS) != 0)
	{
		CRect focusRect = lpDrawItemStruct->rcItem;
		focusRect.left += 12;
		pDC->DrawFocusRect(&(focusRect));
	}
}

BOOL CFormExCheckListBox::MyOnChildNotify(UINT message, WPARAM wParam, LPARAM lParam,
	LRESULT* pResult)
{
	switch (message)
	{
	case WM_DRAWITEM:
		ASSERT(pResult == NULL);       // no return value expected
		//PreDrawItem((LPDRAWITEMSTRUCT)lParam);
		MyDrawItem((LPDRAWITEMSTRUCT)lParam);
		break;
	case WM_MEASUREITEM:
		ASSERT(pResult == NULL);       // no return value expected
		PreMeasureItem((LPMEASUREITEMSTRUCT)lParam);
		break;
	case WM_COMPAREITEM:
		ASSERT(pResult != NULL);       // return value expected
		*pResult = PreCompareItem((LPCOMPAREITEMSTRUCT)lParam);
		break;
	case WM_DELETEITEM:
		ASSERT(pResult == NULL);       // no return value expected
		PreDeleteItem((LPDELETEITEMSTRUCT)lParam);
		break;
	default:
		return CListBox::OnChildNotify(message, wParam, lParam, pResult);
	}
	return TRUE;
}

static DWORD dwOrigCheckListBoxDrawItem = 0;
static DWORD dwOrigCheckListBoxOnChildNotify = 0;
static DWORD dwOrigDrawStaticGetMessageMap = 0;
static DWORD pMsgOrigDrawTransCtrl = 0;

void CWrapModule::SetWrapCheckListBoxDrawItem(BOOL bOnOff)
{
	HINSTANCE hSev=GetModuleHandle("seven.dll");
	BYTE* adr1;
	DWORD old;

	if(bOnOff)
	{
		adr1=(BYTE*)GetProcAddress(hSev,"??_7CCheckListBox7@@6B@");
		VirtualProtect(adr1,0xC0,PAGE_EXECUTE_READWRITE,&old);

		PF_CLBDI jmp1 = (PF_CLBDI)CheckListBoxDrawItem;
		DWORD dw = (DWORD)&jmp1;

		dwOrigCheckListBoxDrawItem = ((DWORD*)adr1)[0x30];
		((DWORD*)adr1)[0x30] = *((DWORD*)dw);

		PF_CLBOCN jmp2 = (PF_CLBOCN)CheckListBoxOnChildNotify;
		dw = (DWORD)&jmp2;

		dwOrigCheckListBoxOnChildNotify = ((DWORD*)adr1)[0x2C];
		((DWORD*)adr1)[0x2C] = *((DWORD*)dw);

		//?_GetBaseMessageMap@CDrawStatic@@KGPBUAFX_MSGMAP@@XZ
		//?messageMap@CDrawStatic@@1UAFX_MSGMAP@@B
		adr1=(BYTE*)GetProcAddress(hSev,"?messageMap@CDrawStatic@@1UAFX_MSGMAP@@B");
		VirtualProtect(adr1,4,PAGE_EXECUTE_READWRITE,&old);
		dwOrigDrawStaticGetMessageMap = *(DWORD*)adr1;
		*(DWORD*)adr1 = (DWORD)&CDrawStaticWrap::pubGetMessageMap;

		//?_GetBaseMessageMap@CDrawTrasparentCtrl@@KGPBUAFX_MSGMAP@@XZ
		//?messageMap@CDrawTrasparentCtrl@@1UAFX_MSGMAP@@B
		adr1=(BYTE*)GetProcAddress(hSev,"?messageMap@CDrawTrasparentCtrl@@1UAFX_MSGMAP@@B");
		VirtualProtect(adr1,0x40,PAGE_EXECUTE_READWRITE,&old);

		pMsgOrigDrawTransCtrl = *(DWORD*)adr1;
		*(DWORD*)adr1 = (DWORD)&CDrawTrasparentCtrlWrap::pubGetMessageMap;
		AFX_MSGMAP* pMsg = (AFX_MSGMAP*)adr1;
		AFX_MSGMAP_ENTRY* pEntr = (AFX_MSGMAP_ENTRY*)pMsg->lpEntries;
		AFX_MSGMAP* pMsg2 = (AFX_MSGMAP*)CDrawTrasparentCtrlWrap::pubGetMessageMap();
		AFX_MSGMAP_ENTRY* pEntr2 = (AFX_MSGMAP_ENTRY*)pMsg2->lpEntries;
		VirtualProtect(pEntr2,0x40,PAGE_EXECUTE_READWRITE,&old);
		origOnEnable = pEntr[1].pfn;
		pEntr[1].pfn = pEntr2[1].pfn;
		pEntr2[1].pfn = origOnEnable;
		//*(DWORD*)adr1 = (DWORD)&CDrawTrasparentCtrlWrap::pubGetMessageMap;
	}
	else
	{
		adr1=(BYTE*)GetProcAddress(hSev,"??_7CCheckListBox7@@6B@");
		VirtualProtect(adr1,0xC0,PAGE_EXECUTE_READWRITE,&old);

		((DWORD*)adr1)[0x30] = dwOrigCheckListBoxDrawItem;
		((DWORD*)adr1)[0x2C] = dwOrigCheckListBoxOnChildNotify;

		adr1=(BYTE*)GetProcAddress(hSev,"?messageMap@CDrawStatic@@1UAFX_MSGMAP@@B");
		VirtualProtect(adr1,4,PAGE_EXECUTE_READWRITE,&old);

		*(DWORD*)adr1 = dwOrigDrawStaticGetMessageMap;

		adr1=(BYTE*)GetProcAddress(hSev,"?messageMap@CDrawTrasparentCtrl@@1UAFX_MSGMAP@@B");
		VirtualProtect(adr1,0x40,PAGE_EXECUTE_READWRITE,&old);

		AFX_MSGMAP* pMsg = (AFX_MSGMAP*)adr1;
		AFX_MSGMAP_ENTRY* pEntr = (AFX_MSGMAP_ENTRY*)pMsg->lpEntries;
		AFX_MSGMAP* pMsg2 = (AFX_MSGMAP*)CDrawTrasparentCtrlWrap::pubGetMessageMap();
		AFX_MSGMAP_ENTRY* pEntr2 = (AFX_MSGMAP_ENTRY*)pMsg2->lpEntries;
		VirtualProtect(pEntr2,0x40,PAGE_EXECUTE_READWRITE,&old);
		AFX_PMSG wrapOnEnable = pEntr[1].pfn;
		pEntr[1].pfn = pEntr2[1].pfn;
		pEntr2[1].pfn = origOnEnable;

		*(DWORD*)adr1 = pMsgOrigDrawTransCtrl;
	}
};

CWrapModule::CWrapModule()
{

	pGlobalModuleFormEx = (CBLModule7*)GetGlobalModule();

	DWORD old;
	HINSTANCE hBr32=GetModuleHandle("br32.dll");
	HINSTANCE hBl=GetModuleHandle("blang.dll");
	HINSTANCE hBas=GetModuleHandle("basic.dll");
	HINSTANCE hFrame=GetModuleHandle("frame.dll");
	HINSTANCE hSev=GetModuleHandle("seven.dll");
	HINSTANCE hBk=GetModuleHandle("bkend.dll");
	HINSTANCE hEd=GetModuleHandle("editr.dll");
	BYTE* adr1;
//	int i; CBLModule7

#ifdef FORMEX_DLL
	int i;
//?AssignContext@CBLModule@@QAEXPAVCBLContext@@@Z
	adr1=(BYTE*)GetProcAddress(hBl,"?AssignContext@CBLModule@@QAEXPAVCBLContext@@@Z");
	VirtualProtect(adr1,6,PAGE_EXECUTE_READWRITE,&old);

	jmpWrapAssignContext=(PF_AsCont)WrapAssignContext;
	adrWrapAssignContext = adr1;
	for(i = 0; i<6;i++) origWrapAssignContext[i] = *adr1++;
	adr1 = adrWrapAssignContext;
	*adr1++=0xFF;
	*adr1++=0x25;
	*(DWORD*)adr1=(DWORD)&jmpWrapAssignContext;
	adr1 = adrWrapAssignContext;
	for(i = 0; i<6;i++) wrapWrapAssignContext[i] = *adr1++;
#endif

	wrapperSetIndicators.DoWrap(hFrame, "?SetIndicators@SECStatusBar@@QAEHPBIH@Z", (PF_SI)WrapSetIndicators);

	wrapperCallAsFunc.DoWrap(hBl, "?CallAsFunc@CBLModule@@QAEHHAAVCValue@@HPAPAV2@@Z", (PF_CAF)WrapCallAsFunc);

	wrapperCallAsProc.DoWrap(hBl, "?CallAsProc@CBLModule@@QAEHHHPAPAVCValue@@@Z", (PF_CAP)WrapCallAsProc);

	wrapperFindProc.DoWrap(hBl, "?FindProc@CBLModule@@QBEHPBDH@Z", (PF_FP)WrapFindProc);

	wrapperFindFunc.DoWrap(hBl,"?FindFunc@CBLModule@@QBEHPBD@Z", (PF_FF)WrapFindFunc);

	wrapperGetProcInfo.DoWrap(hBl, "?GetProcInfo@CBLModule@@QBEHHAAVCBLProcInfo@@@Z", (PF_GPI)WrapGetProcInfo);

	wrapperGetNParams.DoWrap(hBl, "?GetNParams@CBLProcInfo@@QBEHXZ", (PF_GNP)WrapGetNParams);

	/*
/*
//?GetHiTrackBound@CBrowse@@IAEHH@Z
	adr1=(BYTE*)GetProcAddress(hBr32,"?GetHiTrackBound@CBrowse@@IAEHH@Z");
	VirtualProtect(adr1,6,PAGE_EXECUTE_READWRITE,&old);

	jmpGetHiTrackBound=(PF_GHTB)WrapGetHiTrackBound;
	adrGetHiTrackBound = adr1;
	for(i = 0; i<6;i++) origGetHiTrackBound[i] = *adr1++;
	adr1 = adrGetHiTrackBound;
	*adr1++=0xFF;
	*adr1++=0x25;
	*(DWORD*)adr1=(DWORD)&jmpGetHiTrackBound;
	adr1 = adrGetHiTrackBound;
	for(i = 0; i<6;i++) wrapGetHiTrackBound[i] = *adr1++;* /
	wrapperGetHiTrackBound.DoWrap(hBr32, "?GetHiTrackBound@CBrowse@@IAEHH@Z", (PF_GHTB)WrapGetHiTrackBound);

/*
//?GetLoTrackBound@CBrowse@@IAEHH@Z
	adr1=(BYTE*)GetProcAddress(hBr32,"?GetLoTrackBound@CBrowse@@IAEHH@Z");
	VirtualProtect(adr1,6,PAGE_EXECUTE_READWRITE,&old);

	jmpGetLoTrackBound=(PF_GLTB)WrapGetLoTrackBound;
	adrGetLoTrackBound = adr1;
	for(i = 0; i<6;i++) origGetLoTrackBound[i] = *adr1++;
	adr1 = adrGetLoTrackBound;
	*adr1++=0xFF;
	*adr1++=0x25;
	*(DWORD*)adr1=(DWORD)&jmpGetLoTrackBound;
	adr1 = adrGetLoTrackBound;
	for(i = 0; i<6;i++) wrapGetLoTrackBound[i] = *adr1++;* /
	wrapperGetLoTrackBound.DoWrap(hBr32, "?GetLoTrackBound@CBrowse@@IAEHH@Z", (PF_GLTB)WrapGetLoTrackBound);
	*/

//?CtlColor@CDrawTrasparentCtrl@@IAEPAUHBRUSH__@@PAVCDC@@I@Z
	adr1=(BYTE*)GetProcAddress(hSev,"?CtlColor@CDrawTrasparentCtrl@@IAEPAUHBRUSH__@@PAVCDC@@I@Z");
	VirtualProtect(adr1,6,PAGE_EXECUTE_READWRITE,&old);
	adrCtlColorTrans = adr1;

//?CtlColor@CDrawStatic@@IAEPAUHBRUSH__@@PAVCDC@@I@Z
	adr1=(BYTE*)GetProcAddress(hSev,"?CtlColor@CDrawStatic@@IAEPAUHBRUSH__@@PAVCDC@@I@Z");
	VirtualProtect(adr1,6,PAGE_EXECUTE_READWRITE,&old);
	adrCtlColor = adr1;

	wrapperDX_Text.DoWrap(hBk, "?DX_Text@@YAXPAVCGetExchange@@HAAVCValue@@@Z", (PF_DX_T)DX_TextWrap);

	wrapperCreateControl.DoWrap(hBas, "?CreateControl@CGetDoc7@@QAEPAVCWnd@@PAVCGetField@@IABVCRect@@PAV2@KK@Z", 
		(PF_GDCC)WrapCreateControl);

	wrapperProcessSecondOpen.DoWrap(hBas, "?ProcessSecondOpen@CGetDoc7@@QAEXPAVCValue@@@Z", 
		(PF_PSO)WrapProcessSecondOpen);

//?DrawItem@CCheckListBox@@UAEXPAUtagDRAWITEMSTRUCT@@@Z
//??_7CCheckListBox7@@6B@
	SetWrapCheckListBoxDrawItem(TRUE);
	SetWrapCheckListBoxDrawItem(bSetDrawWrap);

	wrapperOnInitialUpdate.DoWrap(hBas, "?OnInitialUpdate@CBrowseView7@@MAEXXZ", 
		(PF_ONINITUP)WrapOnInitialUpdate);

	wrapperOnInitDialog.DoWrap(hBas, "?OnInitDialog@CGetDlg@@MAEHXZ", 
		(PF_ONINITDLG)WrapOnInitDialog);

	wrapperLayoutForm.DoWrap(hBas, "?LayoutForm@CGetDoc7@@UAEHPAVCFormView@@@Z", 
		(PF_LayF)WrapLayoutForm);

/*// artbear - этот метод переопределяется в ТурбоБЛ TurboBL
//		из-за этого, если раскомментарить след.код, 1С сразу упадет !!
//	?FindMethod@CBLContext@@UBEHPBD@Z
//	adr1=(BYTE*)GetProcAddress(hBk,"?FindFunc@CBLModule@@QBEHPBD@Z");
	adr1=(BYTE*)GetProcAddress(hBk,"?FindMethod@CBLContext@@UBEHPBD@Z");
	VirtualProtect(adr1,6,PAGE_EXECUTE_READWRITE,&old);

	jmpFindMethod=(CBLContext_PF_FM)WrapFindMethod;
	adrFindMethod = adr1;
	for(i = 0; i<6;i++) origFindMethod[i] = *adr1++;
	adr1 = adrFindMethod;
	*adr1++=0xFF;
	*adr1++=0x25;
	*(DWORD*)adr1=(DWORD)&jmpFindMethod;
	adr1 = adrFindMethod;
	for(i = 0; i<6;i++) wrapFindMethod[i] = *adr1++;
*/

	wrapperOnCloseDocument.DoWrap(hBas, "?OnCloseDocument@CGetDoc7@@UAEXXZ", 
		(PF_ONCD)WrapOnCloseDocument);

	wrapperUpdateData.DoWrap(hBr32, "?UpdateData@CGetDoc@@UAEHHI@Z", 
		(PF_ONUPDATA)WrapUpdateData);

//?ActivateSubkList@@YAPAVCSbCntDoc@@JVCObjID@@II0VCString@@VCDate@@H0HJHPAVCValue@@1HHH3@Z
/*
	adr1=(BYTE*)GetProcAddress(hBas,"?ActivateSubkList@@YAPAVCSbCntDoc@@JVCObjID@@II0VCString@@VCDate@@H0HJHPAVCValue@@1HHH3@Z");
	VirtualProtect(adr1,6,PAGE_EXECUTE_READWRITE,&old);

	jmpActivateSubkList=(PF_ActSL)WrapActivateSubkList;
	adrActivateSubkList = adr1;
	for(i = 0; i<6;i++) origActivateSubkList[i] = *adr1++;
	adr1 = adrActivateSubkList;
	*adr1++=0xFF;
	*adr1++=0x25;
	*(DWORD*)adr1=(DWORD)&jmpActivateSubkList;
	adr1 = adrActivateSubkList;
	for(i = 0; i<6;i++) wrapActivateSubkList[i] = *adr1++;
*/

	wrapperLoadForm.DoWrap(hBas, "?LoadForm@CGetDoc7@@IAEHJPBD@Z", 
		(PF_LOADFORM)WrapLoadForm);

	wrapperLoadDialog.DoWrap(hBas, "?LoadDialog@CGetDoc7@@IAEHJPBD@Z", 
		(PF_LOADDIALOG)WrapLoadDialog);

	wrapperOpenDocumentFileEx.DoWrap(hBas, "?OpenDocumentFileEx@CGetDlg@@SAXIPBDJPAVCValue@@IIII@Z",
		(void*)WrapOpenDocumentFileEx);

	wrapperDoLoadExternal.DoWrap(hEd, "?DoLoadExternal@CEditDoc@@IAEHPBD@Z",
		(PF_DOLOADEX)WrapDoLoadExternal);

	wrapperGetDataImageCol.DoWrap(hSev, "?GetData@CImageCol@@UAEXAAVCString@@@Z",
		(PF_GETDATAIMAGECOL)WrapGetDataImageCol);

#ifndef VK_1CPP_SourceTable
	// перехват объекта Таблица
	CBLContext* pTablCont = CBLContext::CreateInstance("Table");
	if(pTablCont)
		CTableWrapEx::SetTableWrap(pTablCont);
#endif
}

BEGIN_MESSAGE_MAP(CDrawStaticWrap, CStatic)
	ON_WM_PAINT()
END_MESSAGE_MAP()

   // Map "Static Styles" to "Text Styles"
#define MAP_STYLE(src, dest) if(dwStyle & (src)) dwText |= (dest)
#define NMAP_STYLE(src, dest) if(!(dwStyle & (src))) dwText |= (dest)

void CDrawStaticWrap::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	
	// Where to draw text
	CRect client_rect;
	GetClientRect(client_rect);
	
	// Get the caption
	CString szText;
	GetWindowText(szText);
	
	// Get the font
	CFont *pFont, *pOldFont;
	pFont = GetFont();
	pOldFont = dc.SelectObject(pFont);
	
	DWORD dwStyle = GetStyle(), dwText = DT_EXPANDTABS; //0;
	
	MAP_STYLE(	SS_RIGHT,			DT_RIGHT					);
	MAP_STYLE(	SS_CENTER,			DT_CENTER					);
	MAP_STYLE(	SS_CENTERIMAGE,		DT_VCENTER | DT_SINGLELINE	);
	MAP_STYLE(	SS_NOPREFIX,		DT_NOPREFIX					);
	MAP_STYLE(	SS_WORDELLIPSIS,	DT_WORD_ELLIPSIS			);
	MAP_STYLE(	SS_ENDELLIPSIS,		DT_END_ELLIPSIS				);
	MAP_STYLE(	SS_PATHELLIPSIS,	DT_PATH_ELLIPSIS			);
	
	NMAP_STYLE(	SS_LEFTNOWORDWRAP |
				SS_CENTERIMAGE |
				SS_WORDELLIPSIS |
				SS_ENDELLIPSIS |
				SS_PATHELLIPSIS,	DT_WORDBREAK);
	
	conv.pV = adrCtlColor;
	HBRUSH hBrush = (((CDrawStatic*)this)->*(conv.pCC))(&dc, GetDlgCtrlID());

	CBrush* pBrush = CBrush::FromHandle(hBrush);
	dc.FillRect(client_rect,pBrush);
	// Set transparent background
	//if(((CDrawStatic*)this)->IsTransparent())
		dc.SetBkMode(TRANSPARENT);
	
	// Draw the text
	if(dwStyle & WS_DISABLED)
	{
		COLORREF crOld = dc.SetTextColor(RGB(0xFF,0xFF,0xFF));
		dc.DrawText(szText, client_rect, dwText);
		dc.SetTextColor(RGB(0x80,0x80,0x80));
		client_rect.left--;
		client_rect.top--;
		client_rect.right--;
		client_rect.bottom--;
		dc.DrawText(szText, client_rect, dwText);
		dc.SetTextColor(crOld);
	}
	else
	{
		dc.DrawText(szText, client_rect, dwText);
	}
	
	dc.SelectObject(pOldFont);
}

BEGIN_MESSAGE_MAP(CDrawTrasparentCtrlWrap, CButton)
	ON_WM_PAINT()
	ON_WM_ENABLE()
	ON_WM_ERASEBKGND()
	ON_WM_SETFOCUS()
	ON_WM_KILLFOCUS()
END_MESSAGE_MAP()

void CDrawTrasparentCtrlWrap::OnPaint()
{
	DWORD dwStyle = GetStyle(), dwText = 0;
	CPaintDC dc(this); // device context for painting
	CRect rect;
	GetClientRect(rect);
	DRAWITEMSTRUCT DIS;
	DIS.hDC = dc.m_hDC;
	DIS.rcItem = rect;
	
	MAP_STYLE(	WS_DISABLED,			ODS_DISABLED);
	if(GetFocus() == this) dwText |= ODS_FOCUS;
	DIS.itemState = dwText;

	CFont *pFont, *pOldFont;
	pFont = GetFont();
	pOldFont = dc.SelectObject(pFont);
	Draw(&DIS);
	dc.SelectObject(pOldFont);
}
//-------------------------------------------------------------------
//
COLORREF m_crText = ::GetSysColor(COLOR_WINDOWTEXT);
COLORREF m_crWindow = ::GetSysColor(COLOR_WINDOW);
COLORREF m_crFace = ::GetSysColor(COLOR_3DFACE);

void CDrawTrasparentCtrlWrap::Draw(LPDRAWITEMSTRUCT lpDIS) 
{
	CDC* pDC = CDC::FromHandle(lpDIS->hDC);
	CRect rectItem(lpDIS->rcItem);

  	UINT nState = lpDIS->itemState;
	UINT nStyle = GetStyle();
	BOOL bDisabled = BOOL(nState & ODS_DISABLED);

	// Determine the rect for the check mark.
	CRect rectCheck;
	int nHeight = 13;
	int nAdjust = (rectItem.Height() - nHeight) >> 1;
	if (nStyle & BS_LEFTTEXT)
		rectCheck.SetRect(rectItem.right - nHeight, rectItem.top + nAdjust, 
								rectItem.right, rectItem.top + nHeight + nAdjust);
	else
		rectCheck.SetRect(rectItem.left, rectItem.top + nAdjust, 
								rectItem.left + nHeight, rectItem.top + nHeight + nAdjust);

	pDC->SetBkMode(TRANSPARENT);

	conv.pV = adrCtlColorTrans;
	HBRUSH hBrush = (((CDrawTrasparentCtrl*)this)->*(conv.pCC_TC))(pDC, GetDlgCtrlID());
	HWND parent = GetParent()->GetSafeHwnd();
    if (hBrush == NULL)
        hBrush = (HBRUSH)::DefWindowProc(parent, WM_CTLCOLORSTATIC,
					(WPARAM)pDC->m_hDC, (LPARAM)GetSafeHwnd() );

	CBrush* pBrush = CBrush::FromHandle(hBrush);
	pDC->FillRect(rectItem,pBrush);

	// Determine the rect for the text.
	if (nStyle & BS_LEFTTEXT)
		rectItem.left = lpDIS->rcItem.left + 2;
	else
		rectItem.left += nHeight + 5; //5;
	//rectItem.top++;

	CString sText;
	GetWindowText(sText);

	CSize size = pDC->GetTextExtent(sText);
  	rectItem.right = rectItem.left + size.cx;// + (nStyle & BS_LEFTTEXT ? 2 : -5);
	rectItem.top = (rectItem.Height() - size.cy) >> 1;
	rectItem.bottom = rectItem.top + size.cy;

	if(rectItem.right > lpDIS->rcItem.right) rectItem.right = lpDIS->rcItem.right;
	// Draw the text.
	if (bDisabled)
	{
		CRect client_rect = rectItem;
		COLORREF crOld = pDC->SetTextColor(RGB(0xFF,0xFF,0xFF));
		client_rect.left++;
		client_rect.right++;
		pDC->DrawText(sText, client_rect, DT_LEFT);
		pDC->SetTextColor(RGB(0x80,0x80,0x80));
		client_rect.left--;
		client_rect.top--;
		client_rect.right--;
		client_rect.bottom--;
		pDC->DrawText(sText, client_rect, DT_LEFT | DT_EXPANDTABS);
		pDC->SetTextColor(crOld);
	}
	else
		pDC->DrawText(sText, rectItem, DT_LEFT | DT_EXPANDTABS);

	// Draw the focus rect.
	if((nStyle & BS_AUTORADIOBUTTON) == BS_AUTORADIOBUTTON)
	{
//		rectItem.InflateRect(2, 1, 0, 1);
//		if(rectItem.top < 0) rectItem.top = 0;
		if (nState & ODS_FOCUS)
			pDC->DrawFocusRect(rectItem); 

		DrawRadioMark(pDC, rectCheck, nStyle, nState);
	}
	else
	{
//		rectItem.InflateRect(2, 1, 0, 2);
		rectItem.InflateRect(1, 0, 0, 0);
		if (nState & ODS_FOCUS)
			pDC->DrawFocusRect(rectItem); 

		DrawCheckMark(pDC, rectCheck, nStyle, nState);
	}

}	// DrawItem

//-------------------------------------------------------------------
//
void CDrawTrasparentCtrlWrap::DrawCheckMark(CDC *pDC, CRect rect, UINT nStyle, UINT nState)
{
	DWORD flags = DFCS_BUTTONCHECK;
	if (nStyle & BS_FLAT)
		flags |= DFCS_FLAT;
	if (GetCheck())
		flags |= DFCS_CHECKED;
	if(nState & ODS_DISABLED)
		flags |= DFCS_INACTIVE;
	pDC->DrawFrameControl(rect, DFC_BUTTON, flags);
}

void CDrawTrasparentCtrlWrap::DrawRadioMark(CDC *pDC, CRect rect, UINT nStyle, UINT nState)
{
	DWORD flags = DFCS_BUTTONRADIO;
	if (nStyle & BS_FLAT)
		flags |= DFCS_FLAT;
	if (GetCheck())
		flags |= DFCS_CHECKED;
	if(nState & ODS_DISABLED)
		flags |= DFCS_INACTIVE;
	pDC->DrawFrameControl(rect, DFC_BUTTON, flags);
}

void CDrawTrasparentCtrlWrap::OnEnable(BOOL bEnable)
{
//	OnEnable(bEnable);
	conv.pV_M = origOnEnable;
	(((CDrawTrasparentCtrl*)this)->*(conv.pOnEn))(bEnable);
	CWnd* pParent = GetParent();
	if(pParent)
	{
		CRect rect;
		GetWindowRect(rect);
		pParent->ScreenToClient(rect);
		pParent->InvalidateRect(rect);
	}
//	Invalidate();
}

BOOL CDrawTrasparentCtrlWrap::OnEraseBkgnd(CDC* pDC)
{
	return CButton::OnEraseBkgnd(pDC);
}

void CDrawTrasparentCtrlWrap::OnSetFocus(CWnd* pPre)
{
	CWnd* pParent = GetParent();
	if(pParent)
	{
		CRect rect;
		GetWindowRect(rect);
		pParent->ScreenToClient(rect);
		pParent->InvalidateRect(rect);
	}
	CWnd::OnSetFocus(pPre);
}

void CDrawTrasparentCtrlWrap::OnKillFocus(CWnd* pNew)
{
	CWnd* pParent = GetParent();
	if(pParent)
	{
		CRect rect;
		GetWindowRect(rect);
		pParent->ScreenToClient(rect);
		pParent->InvalidateRect(rect);
	}
	CWnd::OnKillFocus(pNew);
}

//////////////////////////////////////////////////////////////////////////////////////////
BEGIN_MESSAGE_MAP(CFormExListBox, CListBox)
	//{{AFX_MSG_MAP(CFormExListBox)
	ON_WM_PAINT()
	ON_WM_NCDESTROY()
    ON_MESSAGE(WM_SETFONT, OnSetFont)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

void CFormExListBox::OnPaint()
{
	CListBox::OnPaint();
}

void CFormExListBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	CRect itemRect = lpDrawItemStruct->rcItem;
	CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
	pDC->SetBkMode(TRANSPARENT);

	CString str;
	GetText(lpDrawItemStruct->itemID, str);

	COLORREF crOldText = pDC->GetTextColor();
	COLORREF crBkColor = ::GetSysColor(COLOR_WINDOW);
	COLORREF crBkColorSel = ::GetSysColor(COLOR_ACTIVECAPTION);
	COLORREF crTextColor = ::GetSysColor(COLOR_WINDOWTEXT);
	COLORREF crTextColorSel = RGB(0xFF,0xFF,0xFF);
	DWORD fontSetS = 0;
	DWORD fontSet = 0;

	CString st_buf = str;
	st_buf.MakeUpper();
	char ** endptr = NULL;
	const char * ptr = NULL;
				
	int iBuf = st_buf.Find("FONTSET_S[",0);
	if(iBuf >= 0)
	{
		iBuf += 10;
		if(st_buf.Mid(iBuf, 4) != "NONE")
			fontSetS = (DWORD)atol(st_buf.Mid(iBuf));
	}
	iBuf = st_buf.Find("FONTSET[",0);
	if(iBuf >= 0)
	{
		iBuf += 8;
		if(st_buf.Mid(iBuf, 4) != "NONE")
			fontSet = (DWORD)atol(st_buf.Mid(iBuf));
	}
	iBuf = st_buf.Find("FONT_S[",0);
	if(iBuf >= 0)
	{
		iBuf  += 7;
		if(st_buf.Mid(iBuf , 4) != "NONE")
		{
			ptr = st_buf.Mid(iBuf);
			endptr = (char**)&ptr;
			crTextColorSel = strtol(ptr,endptr,0);
		}
	}
	iBuf = st_buf.Find("FONT[",0);
	if(iBuf >= 0)
	{
		iBuf += 5;
		if(st_buf.Mid(iBuf, 4) != "NONE")
		{
			ptr = st_buf.Mid(iBuf);
			endptr = (char**)&ptr;
			crTextColor = strtol(ptr,endptr,0);
		}
	}
	iBuf = st_buf.Find("BRUSH_S[",0);
	if(iBuf >= 0)
	{
		iBuf += 8;
		if(st_buf.Mid(iBuf, 4) != "NONE")
		{
			ptr = st_buf.Mid(iBuf);
			endptr = (char**)&ptr;
			crBkColorSel = strtol(ptr,endptr,0);
		}
	}
	iBuf = st_buf.Find("BRUSH[",0);
	if(iBuf >= 0)
	{
		iBuf += 6;
		if(st_buf.Mid(iBuf, 4) != "NONE")
		{
			ptr = st_buf.Mid(iBuf);
			endptr = (char**)&ptr;
			crBkColor = strtol(ptr,endptr,0);
		}
	}

	CFont* pOldFont = pDC->SelectObject(GetFont());

	if((lpDrawItemStruct->itemState & ODS_SELECTED))
	{
		pDC->FillSolidRect(itemRect, crBkColorSel);
		pDC->SetTextColor(crTextColorSel);
		if(fontSetS)
			pDC->SelectObject(CFont::FromHandle((HFONT)fontSetS));
		else if(fontSet)
			pDC->SelectObject(CFont::FromHandle((HFONT)fontSet));
	}
	else
	{
		pDC->FillSolidRect(itemRect, crBkColor);
		pDC->SetTextColor(crTextColor);
		if(fontSet)
			pDC->SelectObject(CFont::FromHandle((HFONT)fontSet));
	}

	int n = str.Find("\r");
	if(n>=0) str = str.Left(n);
	CRect textRect = itemRect;
	textRect.DeflateRect(2,0,0,0);
	pDC->DrawText(str, textRect, DT_VCENTER | DT_SINGLELINE | DT_EXPANDTABS);

	if ((lpDrawItemStruct->itemState & ODS_FOCUS) != 0)
		pDC->DrawFocusRect(itemRect);


	pDC->SetTextColor(crOldText);
	pDC->SelectObject(pOldFont);
}

void CFormExListBox::OnNcDestroy(void)
{
	CListBox::OnNcDestroy();
	delete this;
}

LRESULT CFormExListBox::OnSetFont(WPARAM wParam, LPARAM lParam)
{
    LRESULT lresult = CListBox::Default();

	CDC* pDC = GetDC();
	TEXTMETRIC tm;
	CFont* pFont = GetFont();
	CFont* pOldFont = pDC->SelectObject(pFont);	
	pDC->GetTextMetrics(&tm);
	int nItemHeight = tm.tmHeight; // + tm.tmExternalLeading + tm.tmInternalLeading;
	pDC->SelectObject(pOldFont);
	SetItemHeight(-1, nItemHeight);
    return lresult;
}

//////////////////////////////////////////////////////////////////////////////////////////
BEGIN_MESSAGE_MAP(CFormExComboBox, CComboBox)
	//{{AFX_MSG_MAP(CFormExComboBox)
	//ON_WM_PAINT()
	ON_WM_NCDESTROY()
	ON_MESSAGE(WM_SETFONT, OnSetFont)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/*
void CFormExComboBox::OnPaint()
{
	CComboBox::OnPaint();
}
*/

void CFormExComboBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
	CRect itemRect = lpDrawItemStruct->rcItem;
	CDC* pDC = CDC::FromHandle(lpDrawItemStruct->hDC);
	pDC->SetBkMode(TRANSPARENT);

	CString str;
	GetLBText(lpDrawItemStruct->itemID, str);

	COLORREF crOldText = pDC->GetTextColor();
	COLORREF crBkColor = ::GetSysColor(COLOR_WINDOW);
	COLORREF crBkColorSel = ::GetSysColor(COLOR_ACTIVECAPTION);
	COLORREF crTextColor = ::GetSysColor(COLOR_WINDOWTEXT);
	COLORREF crTextColorSel = RGB(0xFF,0xFF,0xFF);
	DWORD fontSetS = 0;
	DWORD fontSet = 0;

	CString st_buf = str;
	st_buf.MakeUpper();
	char ** endptr = NULL;
	const char * ptr = NULL;
				
	int iBuf = st_buf.Find("FONTSET_S[",0);
	if(iBuf >= 0)
	{
		iBuf += 10;
		if(st_buf.Mid(iBuf, 4) != "NONE")
			fontSetS = (DWORD)atol(st_buf.Mid(iBuf));
	}
	iBuf = st_buf.Find("FONTSET[",0);
	if(iBuf >= 0)
	{
		iBuf += 8;
		if(st_buf.Mid(iBuf, 4) != "NONE")
			fontSet = (DWORD)atol(st_buf.Mid(iBuf));
	}
	iBuf = st_buf.Find("FONT_S[",0);
	if(iBuf >= 0)
	{
		iBuf  += 7;
		if(st_buf.Mid(iBuf , 4) != "NONE")
		{
			ptr = st_buf.Mid(iBuf);
			endptr = (char**)&ptr;
			crTextColorSel = strtol(ptr,endptr,0);
		}
	}
	iBuf = st_buf.Find("FONT[",0);
	if(iBuf >= 0)
	{
		iBuf += 5;
		if(st_buf.Mid(iBuf, 4) != "NONE")
		{
			ptr = st_buf.Mid(iBuf);
			endptr = (char**)&ptr;
			crTextColor = strtol(ptr,endptr,0);
		}
	}
	iBuf = st_buf.Find("BRUSH_S[",0);
	if(iBuf >= 0)
	{
		iBuf += 8;
		if(st_buf.Mid(iBuf, 4) != "NONE")
		{
			ptr = st_buf.Mid(iBuf);
			endptr = (char**)&ptr;
			crBkColorSel = strtol(ptr,endptr,0);
		}
	}
	iBuf = st_buf.Find("BRUSH[",0);
	if(iBuf >= 0)
	{
		iBuf += 6;
		if(st_buf.Mid(iBuf, 4) != "NONE")
		{
			ptr = st_buf.Mid(iBuf);
			endptr = (char**)&ptr;
			crBkColor = strtol(ptr,endptr,0);
		}
	}

	CFont* pOldFont = pDC->SelectObject(GetFont());

	if((lpDrawItemStruct->itemState & ODS_SELECTED))
	{
		pDC->FillSolidRect(itemRect, crBkColorSel);
		pDC->SetTextColor(crTextColorSel);
		if(fontSetS)
			pDC->SelectObject(CFont::FromHandle((HFONT)fontSetS));
		else if(fontSet)
			pDC->SelectObject(CFont::FromHandle((HFONT)fontSet));
	}
	else
	{
		pDC->FillSolidRect(itemRect, crBkColor);
		pDC->SetTextColor(crTextColor);
		if(fontSet)
			pDC->SelectObject(CFont::FromHandle((HFONT)fontSet));
	}

	int n = str.Find("\r");
	if(n>=0) str = str.Left(n);
	CRect textRect = itemRect;
	textRect.DeflateRect(1,1,1,1);
	pDC->DrawText(str, textRect, DT_VCENTER | DT_SINGLELINE | DT_EXPANDTABS);

	if ((lpDrawItemStruct->itemState & ODS_FOCUS) != 0)
		pDC->DrawFocusRect(itemRect);

	pDC->SetTextColor(crOldText);
	pDC->SelectObject(pOldFont);
}

void CFormExComboBox::OnNcDestroy(void)
{
	CComboBox::OnNcDestroy();
	delete this;
}

LRESULT CFormExComboBox::OnSetFont(WPARAM wParam, LPARAM lParam)
{
    LRESULT lresult = CComboBox::Default();

	CDC* pDC = GetDC();
	TEXTMETRIC tm;
	CFont* pFont = GetFont();
	CFont* pOldFont = pDC->SelectObject(pFont);	
	pDC->GetTextMetrics(&tm);
	int nItemHeight = tm.tmHeight + tm.tmExternalLeading + tm.tmInternalLeading;
	pDC->SelectObject(pOldFont);
	SetItemHeight(-1, nItemHeight);

    return lresult;
}

#ifndef VK_1CPP_SourceTable

int procGetAllTypedItem(class CString &str,long l1,long l2,enum PageType pt)
{
	if(str.CollateNoCase("ModuleText") == 0)
		return 1;

	CMetaDataCont *pMD = GetMetaData();
	CMetaDataObj* pMDO = pMD->FindObject(l1);
	CString str1 = GetModuleFullName(l1, str, 0, pMD);
	str1.MakeUpper();

	SDocNames *pDocNames = NULL;
	pDocNames = new SDocNames;
	pDocNames->id = l1;
	pDocNames->strFolder = str;
	DocNamesArray.SetAt(str1,pDocNames);

	return 1;
}

int CTableWrapEx::SetTable(class CValue **ppValue)
{
	// возвращает:
	// 0 - таблица установлена
	// 1 - необходим вызов штатной обработки
	// 2 - ошибка пути
	// 3 - ошибка имени таблицы
	// 4 - прочие ошибки
	CString strPath = ppValue[1]->GetString();
	CString strName = ppValue[0]->GetString();
	strPath = AllTrim(strPath);
	if(strPath.IsEmpty())
		return 1;

	strPath.MakeUpper();
	if(strPath.Right(4).CompareNoCase(".MXL") == 0)
	{
		*ppValue[0] = strPath;
		return 1;
	}

	int mdPos = strPath.Find("@MD");
	if (mdPos >= 0)
	{
		CString strPathTemp = strPath.Left(mdPos);
		strPath = CString("MD.Обработка.")+AllTrim(strPathTemp)+".Форма";
		strPath.MakeUpper();
	}

	if (strPath.Left(3).CompareNoCase("MD.") == 0) // внутри md
	{
		CString strDoc = strPath.Mid(3);
		SDocNames *pDocNames = NULL;
		if(DocNamesArray.Lookup(strDoc, (void*&)pDocNames))
			return 2;

		CApp7* pApp7 = (CApp7*) AfxGetApp();
		CProfile7* pProfile7 = pApp7->GetProps();
		CString Prop8 = pProfile7->GetStringProp(0x08); // полный путь к файлу 1Cv7.MD (с именем файла)
		CString strFull = "";
		strFull.Format("%s\\%s\\%s_Number%d\\WorkBook",Prop8,pDocNames->strFolder,pDocNames->strFolder,pDocNames->id);
		CWorkBookDoc* pDoc = (CWorkBookDoc*)CConfigCont::PathToDocument(strFull);
		if (!pDoc)
		{
			CString str;
			CTypedCont *pTypedCont;
			if(CConfigCont::IDToPath(pDocNames->id, pDocNames->strFolder, str, &pTypedCont, 0))
				pDoc = pTypedCont->GetWorkBook();
		}
		if (!pDoc)
			return 4;

		if (strName.IsEmpty())
			GetFirstTableName(pDoc, strName);

		CSheetDoc* pSheetDoc = (CSheetDoc*)pDoc->FindDocument(strName);
		if (!pSheetDoc)
			return 3;

		m_pSheetDocIn = pSheetDoc;
		SetPSheet();
		if(m_pSheetDocOut && (CTemplate7::GetDocumentID(m_pSheetDocOut) != 0))
			m_pSheetDocOut->UpdateAllViews(NULL, 8, NULL);
		return 0;
	}

	// из внешнего отчета
	CTemplate7* pTempl = CTemplate7::FromID(0xBA);
	if (!pTempl)
		return 4;

	POSITION pos = pTempl->GetFirstDocPosition();
	while (pos)
	{
		CWorkBookDoc* pDoc = (CWorkBookDoc*)pTempl->GetNextDoc(pos);
		if (!pDoc)
			continue;

		CString strSrc = pDoc->GetSourcePathName();
		if (strSrc.CompareNoCase(strPath) != 0)
			continue;

		if (strName.IsEmpty()) 
			GetFirstTableName(pDoc, strName);

		CSheetDoc* pSheetDoc = (CSheetDoc*)pDoc->FindDocument(strName);
		if (!pSheetDoc)
			return 3;

		m_pSheetDocIn = pSheetDoc;
		SetPSheet();
		if(m_pSheetDocOut && (CTemplate7::GetDocumentID(m_pSheetDocOut) != 0))
			m_pSheetDocOut->UpdateAllViews(NULL, 8, NULL);
		return 0;
	}

	pTempl = CTemplate7::FromID(0xA1);

	if (!pTempl)
		return 4;

	if (strName.IsEmpty())
		strName = "Moxel WorkPlace";

	COleStorage pOleStorage(NULL);
	CFileException excepFile;
	if (!pOleStorage.Open(strPath, CFile::shareExclusive, &excepFile))
		return 2;

	int res = 4;
	COleStreamFile * pOleStream = pOleStorage.OpenStream(CContainer::GetContentsStreamName(), CFile::shareExclusive, &excepFile);
	if (pOleStream)
	{
		DWORD StreamLen = pOleStream->GetLength();
		char* buf = (char*)malloc(StreamLen);
		pOleStream->Read(buf, StreamLen);
		CItemList list1;
		int n = 0;
		CString strStreamName = "";
		list1.LoadFromString(buf, &n);
		for(int j = list1.FindGenericItem("Moxcel.Worksheet", -1); j >= 0; j = list1.FindGenericItem("Moxcel.Worksheet", ++j))
		{
			CItem* pItem = (CItem*)list1.GetItemAt(j);
			if(pItem->WhatIsIt() != 1)
				continue;

			CItem* pItem1 = (CItem*)((CGenericItem*)pItem)->m_array.GetAt(1);
			CItem* pItem2 = (CItem*)((CGenericItem*)pItem)->m_array.GetAt(2);
			if((strName.CompareNoCase(pItem2->m_str) == 0) ||
				((pItem2->m_str.CompareNoCase("Moxel WorkPlace") == 0) &&
				 (strName.CompareNoCase("Таблица") == 0)))
			{
				strStreamName = pItem1->m_str;
			}
		}
		free(buf);
		pOleStorage.ReleaseStream(pOleStream, TRUE);
		if (!strStreamName.IsEmpty())
		{
			if (pOleStream = pOleStorage.OpenStream(strStreamName, CFile::shareExclusive, &excepFile))
			{
				CArchive ar(pOleStream, CArchive::load);
				if (m_pSheetDocIn)
				{
					// пытаемся очистить ранее созданные нами CSheetDoc
					if (CTemplate7::GetDocumentID(m_pSheetDocIn) == 0)
						delete m_pSheetDocIn;
				}
				m_pSheetDocIn = (CSheetDoc*)CSheetDoc::CreateObject();//new CSheetDoc;
//				CTemplate7::RegisterDocument(m_pSheetDocIn);
//				pTempl->AddDocument(m_pSheetDocIn);

				m_pSheetDocIn->DeleteContents();
				m_pSheetDocIn->Serialize(ar);

				SetPSheet();
				if (m_pSheetDocOut && (CTemplate7::GetDocumentID(m_pSheetDocOut) != 0))
					m_pSheetDocOut->UpdateAllViews(NULL, 8, NULL);

				CTemplate7::UnRegisterDocument(m_pSheetDocIn);
				pOleStorage.ReleaseStream(pOleStream, TRUE);
				res = 0;
			}
			else
				res = 4;
		}
		else
			res = 3;
	}
	pOleStorage.Release(TRUE);

	return res;
}

#endif