Пример #1
1
void CLog::ErrLogMsg( EErrorMsg_Type eType, const TString& strMsg, const TString& ErrInfo )
{

    // 日志文件获得
    const SOpenFile* pOpenFlil = GetLogFile( eErrLog );
    if ( pOpenFlil == NULL )
    {
        // bad, 日志文件获得失败
        return;
    }

    // 输出
    static const int BUF_SIZE = 256;
    TCHAR szCharBuf[BUF_SIZE];

    _stprintf_s( szCharBuf, BUF_SIZE, _T("%s  Type: %d; Msg: %s")
                , ErrInfo.c_str(), eType, strMsg.c_str() );

    if ( WriteFile( pOpenFlil->pFile, szCharBuf ) == false )
    {
        // bad, 日志写入失败
        return;
    }
}
Пример #2
0
VOID ExecuteSubProcess()
{
    HANDLE hEventLog = RegisterEventSource(NULL, ServiceName);
    BOOL bSuccess = ReportEvent(
        hEventLog,                  // Handle to the eventlog
        EVENTLOG_INFORMATION_TYPE,	// Type of event
        0,						    // Category (could also be 0)
        MSG_SERVICE_START,          // Event id
        NULL,                       // User's sid (NULL for none)
        0,                          // Number of insertion strings
        0,                          // Number of additional bytes
        NULL,                       // Array of insertion strings
        NULL                        // Pointer to additional bytes
        );

    DeregisterEventSource(hEventLog);

    if (!StartServiceCtrlDispatcher(g_lpServiceStartTable))
    {
        TCHAR msg[MAX_PATH] = {0, };
        _stprintf_s(msg, _T("StartServiceCtrlDispatcher failed, error code = %d\n"), GetLastError());
        WriteLog(msg);
    }
}
Пример #3
0
void logServiceMessage(LPCTSTR lpcszMsg, int severity=EVENTLOG_INFORMATION_TYPE) {
    TCHAR    chMsg[256];
    HANDLE  evSrc;
    LPCTSTR  lpszStrings[2];
	
    DWORD lastErr = GetLastError();
	
    _stprintf_s(chMsg, sizeof chMsg, _T("Service error code: %d"), lastErr);
    lpszStrings[0] = chMsg;
    lpszStrings[1] = lpcszMsg;
	
    evSrc = RegisterEventSource(NULL, TEXT(SERVICENAME));
	
    if (evSrc != NULL) {
		ReportEvent(evSrc, severity, 0, 0, NULL, 2, 0,
			(const char**)lpszStrings, NULL);              
		
		(VOID) DeregisterEventSource(evSrc);
    }
	if (bStandAlone) {
		_ftprintf(stderr, lpcszMsg);
		_ftprintf(stderr, "\n");
	}
}
Пример #4
0
/*--------------------------------------------------------------------------------*/
BOOL	CStorageSerial::QuerySystemStorage(LPTSTR Volume,PULONG DeviceNumber)
{
	BOOL	Result = FALSE;
	HANDLE	FileHandle = INVALID_HANDLE_VALUE;
	ULONG	NumberOfReturnBytes = 0;
	TCHAR	DeviceName[64] = {0};
	STORAGE_DEVICE_NUMBER	StorageDeviceNumber = {0};

	if(IsUserAnAdmin())
	{
		_stprintf_s(DeviceName,sizeof(DeviceName)/sizeof(TCHAR),_T("\\\\.\\%s"),Volume);
		FileHandle = CreateFile(DeviceName,
			GENERIC_READ | GENERIC_WRITE,
			FILE_SHARE_READ | FILE_SHARE_WRITE,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,NULL);
		if(FileHandle != INVALID_HANDLE_VALUE)
		{
			Result = DeviceIoControl(FileHandle,
				IOCTL_STORAGE_GET_DEVICE_NUMBER,
				NULL,
				0,
				&StorageDeviceNumber,
				sizeof(StorageDeviceNumber),
				&NumberOfReturnBytes,
				NULL);
			if(Result)
			{
				*DeviceNumber = StorageDeviceNumber.DeviceNumber;
			}
			CloseHandle(FileHandle);
		}
	}
	return	(Result);
}
Пример #5
0
EtermConfig* EtermConfigData::GetConfig(CString ServerUrl)
{
	EtermConfig* config=NULL;

	try
	{
		RxADO ado;
		TCHAR szSql[1024] = { 0 };
		_stprintf_s(szSql, _T("SELECT ServerUrl,OfficeNo,ConfigType,ConfigState,AllowAirLine,DenyAirLine,ConfigLevel,ConfigList FROM dbo.EtermConfig WITH(NOLOCK) WHERE ServerUrl='%s'"), ServerUrl);
		_RecordsetPtr rst = ado.GetRecordSet(Global::szConnectString, szSql);
		
		_variant_t ServerUrl = rst->GetCollect("ServerUrl");
		_variant_t OfficeNo = rst->GetCollect("OfficeNo");
		_variant_t Types = rst->GetCollect("ConfigType");
		_variant_t State = rst->GetCollect("ConfigState");
		_variant_t AllowAirLine = rst->GetCollect("AllowAirLine");
		_variant_t DenyAirLine = rst->GetCollect("DenyAirLine");
		_variant_t ConfigLevel = rst->GetCollect("ConfigLevel");
		_variant_t ConfigList = rst->GetCollect("ConfigList");

		config = new EtermConfig;
		config->ServerUrl = ServerUrl.bstrVal;
		config->OfficeNo = OfficeNo.bstrVal;
		config->Types = Types.bstrVal;
		config->State = State.intVal;
		config->AllowAirLine = AllowAirLine.bstrVal;
		config->DenyAirLine = DenyAirLine.bstrVal;
		config->ConfigLevel = ConfigLevel.intVal;
		config->ConfigList = ConfigList.bstrVal;
	}
	catch (_com_error err)
	{
		Global::WriteLog(CLog(err.ErrorMessage()));
	}
	return config;
}
Пример #6
0
HRESULT STDMETHODCALLTYPE MFilterSAX2ErrorHandler::error(struct ISAXLocator * pLocator,
                                                         const wchar_t * pwchErrorMessage,
                                                         HRESULT hrErrorCode )
{
  TCHAR szErrorMessage[MAX_PATH*2] = {0};
  TCHAR szFormatString[MAX_PATH*2] = {0};
  int iLineNumber, iCharacter;

  _tcscpy_s(szErrorMessage, MAX_PATH * 2, pwchErrorMessage);
  pLocator->getLineNumber(&iLineNumber);
  pLocator->getColumnNumber(&iCharacter);

  stringT cs_format;
  LoadAString(cs_format, IDSC_MSXMLSAXGENERROR);

  _stprintf_s(szFormatString, MAX_PATH * 2, cs_format.c_str(),
              hrErrorCode, iLineNumber, iCharacter, szErrorMessage);

  m_strValidationResult += szFormatString;

  bErrorsFound = TRUE;

  return S_OK;
}
Пример #7
0
bool CMusicListGroupUI::AdjustIndexs(int nStartPos)
{
	TCHAR szBuf[MAX_PATH] = {0};
	CMusicListItemUI *pListElement = NULL;
	CLabelUI* id = NULL;
	int nSum = GetTreeNodes().GetSize();
	for (int i = 0; i < nSum; i++ )
	{
		pListElement = static_cast<CMusicListItemUI*>(GetTreeNodes().GetAt(i));
		if (pListElement == NULL)
			return false;
		id = static_cast<CLabelUI*>(GetTreeView()->GetManager()->FindSubControlByName(pListElement, kMusicIndexControlName));
		if (id != NULL)
		{
			int index = 0;

			_stprintf_s(szBuf, MAX_PATH - 1, _T("%2.2d"), i + 1);
			id->SetText(szBuf);
		}
		else
			return false;
	}
	return true;
}
Пример #8
0
/* static */
CString CBugTraqAssociations::LookupProviderName(const CLSID &provider_clsid)
{
	OLECHAR szClsid[40] = { 0 };
	StringFromGUID2(provider_clsid, szClsid, ARRAYSIZE(szClsid));

	TCHAR szSubKey[MAX_PATH] = {0};
	_stprintf_s(szSubKey, _T("CLSID\\%ls"), szClsid);

	CString provider_name = CString(szClsid);

	HKEY hk;
	if (RegOpenKeyEx(HKEY_CLASSES_ROOT, szSubKey, 0, KEY_READ, &hk) == ERROR_SUCCESS)
	{
		TCHAR szClassName[MAX_PATH] = {0};
		DWORD cbClassName = sizeof(szClassName);

		if (RegQueryValueEx(hk, NULL, NULL, NULL, (LPBYTE)szClassName, &cbClassName) == ERROR_SUCCESS)
			provider_name = CString(szClassName);

		RegCloseKey(hk);
	}

	return provider_name;
}
Пример #9
0
void CSettingWindow::colorBox(CControlUI* pUI)
{
	static CHOOSECOLOR cc;
	static COLORREF crCustCoLors[16];
	cc.lStructSize=sizeof(CHOOSECOLOR);
	cc.hwndOwner= this->m_hWnd;
	cc.hInstance=NULL;
	cc.rgbResult = static_cast<CHorizontalLayoutUI*>(pUI->GetParent())->GetItemAt(0)->GetBkColor();
	cc.lpCustColors=crCustCoLors;
	cc.Flags=CC_RGBINIT|CC_FULLOPEN | CC_ANYCOLOR; 
	cc.lCustData=0;
	cc.lpfnHook=NULL;
	cc.lpTemplateName=NULL;
	if(TRUE == ChooseColor(&cc))
	{ 
		TCHAR szBuf[MAX_PATH] = {0};
#if defined(UNDER_CE)
		_stprintf(szBuf, _T("FF%02X%02X%02X"), GetRValue(cc.rgbResult), GetGValue(cc.rgbResult), GetBValue(cc.rgbResult));
#else
		_stprintf_s(szBuf, MAX_PATH - 1, _T("FF%02X%02X%02X"), GetRValue(cc.rgbResult), GetGValue(cc.rgbResult), GetBValue(cc.rgbResult));
#endif
		LPTSTR pstr = NULL;
		DWORD dwFontColor = _tcstoul(szBuf, &pstr, 16);
		static_cast<CHorizontalLayoutUI*>(pUI->GetParent())->GetItemAt(0)->SetBkColor(dwFontColor);
		CLrcPreViewUI* pLrcPreView = static_cast<CLrcPreViewUI*>(GetPaintMgr()->FindControl(_T("lrcPreView")));
		ASSERT(pLrcPreView);
		CConfigMgr::spLrcConfigT pLrcCfg = theConfigMgr->GetLrcConfig();
		pLrcPreView->m_iFontSize = pLrcCfg->GetLrcDeskFontSize();
		pLrcPreView->m_iFontStyle = pLrcCfg->GetLrcDeskFontStyle();
		pLrcPreView->m_sFontName = pLrcCfg->GetLrcDeskFontName();
		pLrcPreView->m_dwFontColor = dwFontColor;
		pLrcPreView->Invalidate();
		setModify(true);
	}

}
Пример #10
0
void CBGMusic::Exec()
{
	if(bLoop == TRUE && pMediaSeeking){
		LONGLONG s, e;
		pMediaSeeking->GetPositions(&s, &e);
		if(s >= e){
			s = 0;
			pMediaSeeking->SetPositions(
				&s, AM_SEEKING_AbsolutePositioning,
				NULL, AM_SEEKING_NoPositioning);
		}
	}

	if(bFading == TRUE){
		float t = (float)timeGetTime() - time_s;
		pBasicAudio->put_Volume((long)(delta * t + vol_s));

		TCHAR str[20];
		_stprintf_s(str, 20, _T("%f"), delta * t + vol_s);
		//DXTRACE_MSG(str);
		
		if(t >= time_e) bFading = FALSE;
	}
}
Пример #11
0
LRESULT CAboutDlg::DlgFunc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM /*lParam*/)
{
    switch (uMsg)
    {
    case WM_INITDIALOG:
        {
            InitDialog(hwndDlg, IDI_TORTOISEIDIFF);
            // initialize the controls
            TCHAR verbuf[1024] = {0};
            TCHAR maskbuf[1024] = {0};
            if (!::LoadString (hResource, IDS_VERSION, maskbuf, _countof(maskbuf)))
            {
                SecureZeroMemory(maskbuf, sizeof(maskbuf));
            }
            _stprintf_s(verbuf, maskbuf, TGIT_VERMAJOR, TGIT_VERMINOR, TGIT_VERMICRO, TGIT_VERBUILD);
            SetDlgItemText(hwndDlg, IDC_ABOUTVERSION, verbuf);
        }
        return TRUE;
    case WM_COMMAND:
        return DoCommand(LOWORD(wParam));
    default:
        return FALSE;
    }
}
Пример #12
0
//Function which takes input of An HTML Resource Id
BOOL CInfoDlg::ShowDialog(UINT idAboutHTMLID, HINSTANCE hInstance)
{
    //Load the IE Specific MSTML Interface DKK
    HINSTANCE hinstMSHTML = LoadLibrary(_T("MSHTML.DLL"));
    BOOL bSuccess = FALSE;
    if(hinstMSHTML)
    {
        SHOWHTMLDIALOGFN *pfnShowHTMLDialog;
        //Locate The Function ShowHTMLDialog in the Loaded MSHTML.DLL
        pfnShowHTMLDialog = (SHOWHTMLDIALOGFN*)GetProcAddress(hinstMSHTML, "ShowHTMLDialog");
        if(pfnShowHTMLDialog)
        {
            LPTSTR lpszModule = new TCHAR[MAX_PATH];
            //Get The Application Path
            if (GetModuleFileName(hInstance, lpszModule, MAX_PATH))
            {
                //Add the IE Res protocol
                TCHAR strResourceURL[MAX_PATH*4];
                _stprintf_s(strResourceURL, _countof(strResourceURL), _T("res://%s/%u"), lpszModule, idAboutHTMLID);
                //Attempt to Create the URL Moniker to the specified in the URL String
                IMoniker *pmk;
                if(SUCCEEDED(CreateURLMoniker(NULL,strResourceURL,&pmk)))
                {
                    //Invoke the ShowHTMLDialog function by pointer
                    //passing the HWND of your Application , the Moniker,
                    //the remaining parameters can be set to NULL
                    pfnShowHTMLDialog(NULL,pmk,NULL,L"resizable:yes",NULL);
                    bSuccess = TRUE;
                }
            }
            delete [] lpszModule;
        }
        FreeLibrary(hinstMSHTML);
    }
    return bSuccess;
}
Пример #13
0
// try to find current Java Home from registry
// HKLM\Software\JavaSoft\Java Runtime Environment\CurrentVersion
// HKLM\Software\JavaSoft\Java Runtime Environment\[CurrentVersion]\JavaHome
// return TRUE if found, and path is set in lpszJavaHome
// return FALSE otherwise
bool getSystemJRE(LPTSTR szHomeBin, unsigned long buflen) {
    HKEY hKey, vKey;
    DWORD dwType, dwCount = BUFFER_SIZE*sizeof(TCHAR);
    TCHAR versionString[BUFFER_SIZE], fullKey[2*BUFFER_SIZE];

    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, JAVA_RUNTIME_SUBKEY, 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
        if (RegQueryValueEx(hKey, _T("CurrentVersion"), NULL, &dwType, (LPBYTE) versionString, &dwCount) == ERROR_SUCCESS) {
            _stprintf_s(fullKey, 2*BUFFER_SIZE, _T("%s\\%s"), JAVA_RUNTIME_SUBKEY, versionString);
            if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, fullKey, 0, KEY_READ, &vKey) == ERROR_SUCCESS) {
                dwCount = buflen * sizeof(TCHAR);
                if (RegQueryValueEx(vKey, _T("JavaHome"), NULL, &dwType, (LPBYTE) szHomeBin, &dwCount) == ERROR_SUCCESS) {
                    if (fileExists(szHomeBin)) {
                        return true;
                    } else {
                        showError(szHomeBin, _T("System JRE does not exist at this location!"));
                        return false;
                    }
                } else {
                    showError(fullKey, _T("System JRE not found (registry)!"));
                    return false;
                }
            } else {
                showError(fullKey, _T("Failed to open registry key!!"));
                return false;
            }
        } else {
            showError(JAVA_RUNTIME_SUBKEY, _T("No value for CurrentVersion."));
            return false;
        }
    } else {
        showError(JAVA_RUNTIME_SUBKEY, _T("Failed to open registry key!"));
        return false;
    }

    return false;
}
Пример #14
0
VOID NdPerfLog(__in LPCWSTR logfile, __in __format_string LPCWSTR  fmt, ...)
{
	va_list argList;
	va_start(argList, fmt);	
	WCHAR szMsg[4096];
	StringCchVPrintfW(szMsg, _countof(szMsg), fmt, argList);
	va_end(argList);

	//MSG(동기화 추가);
	HANDLE hFile = CreateFile(
		logfile,
		GENERIC_WRITE,
		FILE_SHARE_READ | FILE_SHARE_WRITE,
		NULL,
		OPEN_ALWAYS,
		FILE_ATTRIBUTE_NORMAL,
		NULL
		);
	if (hFile == INVALID_HANDLE_VALUE)
	{
		_stprintf_s(szMsg, L"Cannot create a log file. [errcode: %d][%s]\n", GetLastError(), logfile);
		OutputDebugString(szMsg);
	}
	else
	{
		(VOID)SetFilePointer(hFile, 0, 0, FILE_END);
		std::string s;
		s.append(ToAnsiStr(GetCurrentTimeStr().c_str()));
		s.append(" ");
		s.append(ToAnsiStr(szMsg));
		s.append("");
		DWORD dwWritten;
		(VOID)WriteFile(hFile, s.c_str(), (DWORD)s.size(), &dwWritten, 0);
		CloseHandle(hFile);
	}
}
Пример #15
0
/**
 * @brief WM_NOTIFY handler of Machine State dialog.
 * @param hwnd - window handle.
 * @param idCtrl - identifier of the common control sending the message.
 * @param pnmh - pointer to an NMHDR structure that contains the notification code and additional information.
 */
static LRESULT MachineStateDlg_OnNotify(HWND hwnd, int idCtrl, LPNMHDR pnmh)
{
    switch (pnmh->code)
    {
    case LVN_ITEMCHANGED:
    {
        if (idCtrl != IDC_PROCESS_LIST)
            break;
        LPNMLISTVIEW pnmv = (LPNMLISTVIEW)pnmh;
        if ((pnmv->uNewState & LVIS_SELECTED) != (pnmv->uOldState & LVIS_SELECTED))
        {
            if (pnmv->uNewState & LVIS_SELECTED)
            {
                CWaitCursor wait(true);
                HWND hwndModuleList = GetDlgItem(hwnd, IDC_PROCESS_MODULES_LIST);
                SendMessage(hwndModuleList, WM_SETREDRAW, FALSE, 0);
                DisplayWaitBanner(hwndModuleList);

                LVITEM lvi;
                ZeroMemory(&lvi, sizeof(lvi));
                lvi.mask = LVIF_TEXT;
                CEnumProcess::CModuleEntry module;
                if (g_pEnumProc->GetModuleFirst((DWORD)pnmv->lParam, module))
                {
                    int iItemPos = 0;
                    do
                    {
                        lvi.iItem = iItemPos;
                        lvi.pszText = module.m_szModuleName;
                        ListView_InsertItem(hwndModuleList, &lvi);
                        TCHAR szVersionString[64];
                        if (CSymEngine::GetVersionString(module.m_szModuleName, szVersionString, countof(szVersionString)))
                            ListView_SetItemText(hwndModuleList, iItemPos, CID_MODULE_VERSION, szVersionString);
                        TCHAR szTempBuf[32];
#if defined _WIN64
                        _stprintf_s(szTempBuf, countof(szTempBuf), _T("%016X"), (DWORD_PTR)module.m_pLoadBase);
#elif defined _WIN32
                        _stprintf_s(szTempBuf, countof(szTempBuf), _T("%08X"), (DWORD_PTR)module.m_pLoadBase);
#endif
                        ListView_SetItemText(hwndModuleList, iItemPos, CID_MODULE_BASE, szTempBuf);
                        ++iItemPos;
                    }
                    while (g_pEnumProc->GetModuleNext((DWORD)pnmv->lParam, module));
                }
                else
                {
                    TCHAR szMessage[100];
                    LoadString(g_hInstance, IDS_ERROR_NOT_AVAILABLE, szMessage, countof(szMessage));
                    lvi.iItem = 0;
                    lvi.pszText = szMessage;
                    ListView_InsertItem(hwndModuleList, &lvi);
                }

                SendMessage(hwndModuleList, WM_SETREDRAW, TRUE, 0);
                InvalidateRect(hwndModuleList, NULL, TRUE);
            }
            else
            {
                HWND hwndModuleList = GetDlgItem(hwnd, IDC_PROCESS_MODULES_LIST);
                ListView_DeleteAllItems(hwndModuleList);
            }
        }
    }
    break;
    case LVN_COLUMNCLICK:
    {
        LPNMLISTVIEW pnmv = (LPNMLISTVIEW)pnmh;
        if (idCtrl == IDC_PROCESS_LIST)
        {
            HWND hwndProcessList = GetDlgItem(hwnd, IDC_PROCESS_LIST);
            g_ProcessListOrder.ToggleSortParams(hwndProcessList, pnmv->iSubItem);
            LISTVIEW_SORT_PARAMS lvSortParams;
            lvSortParams.hwndList = hwndProcessList;
            lvSortParams.iColumnNumber = pnmv->iSubItem;
            lvSortParams.bAscending = g_ProcessListOrder.GetSortOrder();
            switch (pnmv->iSubItem)
            {
            case CID_PROCESS_ID:
                lvSortParams.eCompareType = LISTVIEW_SORT_PARAMS::ICT_INTEGER;
                break;
            case CID_PROCESS_NAME:
                lvSortParams.eCompareType = LISTVIEW_SORT_PARAMS::ICT_STRING;
                break;
            }
            ListView_SortItemsEx(hwndProcessList, &ListViewCompareFunc, (LPARAM)&lvSortParams);
        }
        else if (idCtrl == IDC_PROCESS_MODULES_LIST)
        {
            HWND hwndModuleList = GetDlgItem(hwnd, IDC_PROCESS_MODULES_LIST);
            g_ModulesListOrder.ToggleSortParams(hwndModuleList, pnmv->iSubItem);
            LISTVIEW_SORT_PARAMS lvSortParams;
            lvSortParams.hwndList = hwndModuleList;
            lvSortParams.iColumnNumber = pnmv->iSubItem;
            lvSortParams.bAscending = g_ModulesListOrder.GetSortOrder();
            switch (pnmv->iSubItem)
            {
            case CID_MODULE_NAME:
            case CID_MODULE_VERSION:
                lvSortParams.eCompareType = LISTVIEW_SORT_PARAMS::ICT_STRING;
                break;
            case CID_MODULE_BASE:
                lvSortParams.eCompareType = LISTVIEW_SORT_PARAMS::ICT_HEXADECIMAL;
                break;
            }
            ListView_SortItemsEx(hwndModuleList, &ListViewCompareFunc, (LPARAM)&lvSortParams);
        }
    }
    break;
    }
    return FALSE;
}
Пример #16
0
void CGroupsUI::SetChildVisible(Node* node, bool visible)
{
	if (!node || node == root_node_)
		return;

	if (node->data().child_visible_ == visible)
		return;

	node->data().child_visible_ = visible;

	TCHAR szBuf[MAX_PATH] = {0};
	tString html_text;
	if (node->data().has_child_)
	{
		if (node->data().child_visible_)
			html_text += level_expand_image_;
		else
			html_text += level_collapse_image_;

#if defined(UNDER_WINCE)
		_stprintf(szBuf, _T("<x %d>"), level_text_start_pos_);
#else
		_stprintf_s(szBuf, MAX_PATH - 1, _T("<x %d>"), level_text_start_pos_);
#endif
		html_text += szBuf;

		html_text += node->data().text_;

		CLabelUI* nick_name = static_cast<CLabelUI*>(paint_manager_.FindSubControlByName(node->data().list_elment_, kNickNameControlName));
		if (nick_name != NULL)
		{
			nick_name->SetShowHtml(true);
			nick_name->SetText(html_text.c_str());
		}
	}

	if (!node->data().list_elment_->IsVisible())
		return;

	if (!node->has_children())
		return;

	Node* begin = node->child(0);
	Node* end = node->get_last_child();
	for (int i = begin->data().list_elment_->GetIndex(); i <= end->data().list_elment_->GetIndex(); ++i)
	{
		CControlUI* control = GetItemAt(i);
		if (_tcsicmp(control->GetClass(), _T("ListContainerElementUI")) == 0)
		{
			if (visible) 
			{
				Node* local_parent = ((Node*)control->GetTag())->parent();
				if (local_parent->data().child_visible_ && local_parent->data().list_elment_->IsVisible())
				{
					control->SetVisible(true);
				}
			}
			else
			{
				control->SetVisible(false);
			}
		}
	}
}
Пример #17
0
Node* CGroupsUI::AddNode(const GroupsListItemInfo& item, Node* parent)
{
	if (!parent)
		parent = root_node_;

	TCHAR szBuf[MAX_PATH] = {0};

    CListContainerElementUI* pListElement = NULL;
    if( !m_dlgBuilder.GetMarkup()->IsValid() ) {
        pListElement = static_cast<CListContainerElementUI*>(m_dlgBuilder.Create(_T("group_list_item.xml"), (UINT)0, NULL, &paint_manager_));
    }
    else {
        pListElement = static_cast<CListContainerElementUI*>(m_dlgBuilder.Create((UINT)0, &paint_manager_));
    }
    if (pListElement == NULL)
        return NULL;

	Node* node = new Node;

	node->data().level_ = parent->data().level_ + 1;
	if (item.folder)
		node->data().has_child_ = !item.empty;
	else
		node->data().has_child_ = false;

	node->data().folder_ = item.folder;

	node->data().child_visible_ = (node->data().level_ == 0);

	node->data().text_ = item.nick_name;
	node->data().list_elment_ = pListElement;

	if (!parent->data().child_visible_)
		pListElement->SetVisible(false);

	if (parent != root_node_ && !parent->data().list_elment_->IsVisible())
		pListElement->SetVisible(false);

	CRect rcPadding = text_padding_;
	for (int i = 0; i < node->data().level_; ++i)
	{
		rcPadding.left += level_text_start_pos_;		
	}
	pListElement->SetPadding(rcPadding);

	CButtonUI* log_button = static_cast<CButtonUI*>(paint_manager_.FindSubControlByName(pListElement, kLogoButtonControlName));
	if (log_button != NULL)
	{
		if (!item.folder && !item.logo.empty())
		{
#if defined(UNDER_WINCE)
			_stprintf(szBuf, _T("%s"), item.logo.c_str());
#else
			_stprintf_s(szBuf, MAX_PATH - 1, _T("%s"), item.logo.c_str());
#endif
			log_button->SetNormalImage(szBuf);
		}
		else
		{
			CContainerUI* logo_container = static_cast<CContainerUI*>(paint_manager_.FindSubControlByName(pListElement, kLogoContainerControlName));
			if (logo_container != NULL)
				logo_container->SetVisible(false);
		}
        log_button->SetTag((UINT_PTR)pListElement);
        log_button->OnEvent += MakeDelegate(&OnLogoButtonEvent);
	}

	tString html_text;
	if (node->data().has_child_)
	{
		if (node->data().child_visible_)
			html_text += level_expand_image_;
		else
			html_text += level_collapse_image_;

#if defined(UNDER_WINCE)
		_stprintf(szBuf, _T("<x %d>"), level_text_start_pos_);
#else
		_stprintf_s(szBuf, MAX_PATH - 1, _T("<x %d>"), level_text_start_pos_);
#endif
		html_text += szBuf;
	}

	if (item.folder)
	{
		html_text += node->data().text_;
	}
	else
	{
#if defined(UNDER_WINCE)
		_stprintf(szBuf, _T("%s"), item.nick_name.c_str());
#else
		_stprintf_s(szBuf, MAX_PATH - 1, _T("%s"), item.nick_name.c_str());
#endif
		html_text += szBuf;
	}

	CLabelUI* nick_name = static_cast<CLabelUI*>(paint_manager_.FindSubControlByName(pListElement, kNickNameControlName));
	if (nick_name != NULL)
	{
		if (item.folder)
			nick_name->SetFixedWidth(0);

		nick_name->SetShowHtml(true);
		nick_name->SetText(html_text.c_str());
	}

	if (!item.folder && !item.description.empty())
	{
		CLabelUI* description = static_cast<CLabelUI*>(paint_manager_.FindSubControlByName(pListElement, kDescriptionControlName));
		if (description != NULL)
		{
#if defined(UNDER_WINCE)
			_stprintf(szBuf, _T("<x 20><c #808080>%s</c>"), item.description.c_str());
#else
			_stprintf_s(szBuf, MAX_PATH - 1, _T("<x 20><c #808080>%s</c>"), item.description.c_str());
#endif
			description->SetShowHtml(true);
			description->SetText(szBuf);
		}
	}

	pListElement->SetFixedHeight(kGroupListItemNormalHeight);
	pListElement->SetTag((UINT_PTR)node);
	int index = 0;
	if (parent->has_children())
	{
		Node* prev = parent->get_last_child();
		index = prev->data().list_elment_->GetIndex() + 1;
	}
	else 
	{
		if (parent == root_node_)
			index = 0;
		else
			index = parent->data().list_elment_->GetIndex() + 1;
	}
	if (!CListUI::AddAt(pListElement, index))
	{
		delete pListElement;
		delete node;
		node = NULL;
	}

	parent->add_child(node);
	return node;
}
Пример #18
0
void StatisticsModel::SaveDatabase()
{
    TCHAR command[256]={ 0 };

    Lock();

    // Delete all records - Protocol
    SQLite::Exec(_T("Delete From Protocol;"), true);

    // Insert records - Protocol
    std::map<int, StModelItem>::iterator it;
    for(it = _items.begin(); it != _items.end(); ++it) // Loop of Process
    {
        int puid = it->first;

        if( puid == PROCESS_ALL )
        {
            continue;
        }

        // TCP
        _stprintf_s(command, _countof(command), 
            _T("Insert Into Protocol Values(%d, %d, %I64d, %I64d, %I64d, %I64d);"), 
            puid, TRA_TCP, 
            it->second.tx.tcpBytes, 
            it->second.rx.tcpBytes, 
            it->second.tx.tcpPackets, 
            it->second.rx.tcpPackets);
        SQLite::Exec(command, true);

        // UDP
        _stprintf_s(command, _countof(command), 
            _T("Insert Into Protocol Values(%d, %d, %I64d, %I64d, %I64d, %I64d);"), 
            puid, TRA_UDP, 
            it->second.tx.udpBytes, 
            it->second.rx.udpBytes, 
            it->second.tx.udpPackets, 
            it->second.rx.udpPackets);
        SQLite::Exec(command, true);

        // ICMP
        _stprintf_s(command, _countof(command), 
            _T("Insert Into Protocol Values(%d, %d, %I64d, %I64d, %I64d, %I64d);"), 
            puid, TRA_ICMP, 
            it->second.tx.icmpBytes, 
            it->second.rx.icmpBytes, 
            it->second.tx.icmpPackets, 
            it->second.rx.icmpPackets);
        SQLite::Exec(command, true);

        // OTHER
        _stprintf_s(command, _countof(command), 
            _T("Insert Into Protocol Values(%d, %d, %I64d, %I64d, %I64d, %I64d);"), 
            puid, TRA_OTHER, 
            it->second.tx.otherBytes, 
            it->second.rx.otherBytes, 
            it->second.tx.otherPackets, 
            it->second.rx.otherPackets);
        SQLite::Exec(command, true);
    }

    // Insert or update records - PacketSize
    for(it = _items.begin(); it != _items.end(); ++it) // Loop of Process
    {
        int puid = it->first;

        if( puid == PROCESS_ALL )
        {
            continue;
        }

        if( it->second.newItem == true ) // Insert
        {
            for(int i = 0; i < 1501; i++)
            {
                _stprintf_s(command, _countof(command), 
                    _T("Insert Into PacketSize Values(%d, %d, 0, 0, %I64d, %I64d);"), 
                    puid, i, it->second.txPacketSize[i], it->second.rxPacketSize[i]);

                SQLite::Exec(command, true);
            }
        }
        else // Update
        {
            for(int i = 0; i < 1501; i++)
            {
                if( it->second.txPacketSize[i] > it->second.txPrevPacketSize[i] ||
                    it->second.rxPacketSize[i] > it->second.rxPrevPacketSize[i] )
                {
                    _stprintf_s(command, _countof(command), 
                        _T("Update PacketSize Set TxPackets = %I64d, RxPackets = %I64d ")
                        _T("Where ProcessUid = %d And PacketSize = %d;"), 
                        it->second.txPacketSize[i], it->second.rxPacketSize[i], puid, i);

                    SQLite::Exec(command, true);
                }
            }
        }
    }

    // Insert or update records - Rate
    for(it = _items.begin(); it != _items.end(); ++it) // Loop of Process
    {
        int puid = it->first;

        if( puid == PROCESS_ALL )
        {
            continue;
        }

        if( it->second.newItem == true ) // Insert
        {
            for(int i = 0; i < 1025; i++)
            {
                _stprintf_s(command, _countof(command), 
                    _T("Insert Into Rate Values(%d, %d, %I64d, %I64d);"), 
                    puid, i, it->second.txRate[i], it->second.rxRate[i]);

                SQLite::Exec(command, true);
            }
        }
        else // Update
        {
            for(int i = 0; i < 1025; i++)
            {
                if( it->second.txRate[i] > it->second.txPrevRate[i] ||
                    it->second.rxRate[i] > it->second.rxPrevRate[i] )
                {
                    _stprintf_s(command, _countof(command), 
                        _T("Update Rate Set TxSeconds = %I64d, RxSeconds = %I64d ")
                        _T("Where ProcessUid = %d And Rate = %d;"), 
                        it->second.txRate[i], it->second.rxRate[i], puid, i);

                    SQLite::Exec(command, true);
                }
            }
        }
    }

    Unlock();

    // Flush
    SQLite::Flush();
}
Пример #19
0
// 异常处理回调
int SEH_ExceptionAccessViolationFilter(LPEXCEPTION_POINTERS p_exinfo)
{
	TCHAR szErrMsg[BUFSIZ];
	switch (p_exinfo->ExceptionRecord->ExceptionCode)
	{
	case EXCEPTION_ACCESS_VIOLATION:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("存储保护异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_DATATYPE_MISALIGNMENT:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("数据类型未对齐异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_BREAKPOINT:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("中断异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_SINGLE_STEP:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("单步中断异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("数组越界异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_FLT_DENORMAL_OPERAND:
	case EXCEPTION_FLT_DIVIDE_BY_ZERO:
	case EXCEPTION_FLT_INEXACT_RESULT:
	case EXCEPTION_FLT_INVALID_OPERATION:
	case EXCEPTION_FLT_OVERFLOW:
	case EXCEPTION_FLT_STACK_CHECK:
	case EXCEPTION_FLT_UNDERFLOW:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("浮点数计算异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_INT_DIVIDE_BY_ZERO:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("被0除异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_INT_OVERFLOW:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("数据溢出异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_IN_PAGE_ERROR:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("页错误异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_ILLEGAL_INSTRUCTION:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("非法指令异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_STACK_OVERFLOW:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("堆栈溢出异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	case EXCEPTION_INVALID_HANDLE:
		_stprintf_s(szErrMsg, BUFSIZ - 1, _T("无效句病异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	default:
		if (p_exinfo->ExceptionRecord->ExceptionCode & (1 << 29))
			_stprintf_s(szErrMsg, BUFSIZ - 1, _T("用户自定义的软件异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		else
			_stprintf_s(szErrMsg, BUFSIZ - 1, _T("其它异常,错误代码:%x\n"), p_exinfo->ExceptionRecord->ExceptionCode);
		break;
	}

	OutputDebugString(szErrMsg);
	SetLastError(p_exinfo->ExceptionRecord->ExceptionCode);
	return 1;
}
Пример #20
0
/**
 * @return true if the log was loaded successfully.
 */
BOOL CTextLogFile::LoadEntries(void)
{
#ifdef _DEBUG
	DWORD dwStartTime = GetTickCount();
#endif
	BOOL bResult = FALSE;
	PCTSTR pszLogFileName = GetLogFileName();
	HANDLE hFile = CreateFile(pszLogFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile != INVALID_HANDLE_VALUE)
	{
		DWORD dwFileSize = (DWORD)GetFileSize(hFile, NULL);
		if (dwFileSize == 0)
		{
			// ignore empty files
			CloseHandle(hFile);
			return TRUE;
		}
		DWORD dwBufferSize = min(dwFileSize, g_dwMaxBufferSize);
		PBYTE pFileBuffer = new BYTE[dwBufferSize];
		if (pFileBuffer)
		{
			BYTE arrUTF8Preamble[sizeof(g_arrUTF8Preamble)];
			DWORD dwWritten = 0;
			if (ReadFile(hFile, arrUTF8Preamble, sizeof(arrUTF8Preamble), &dwWritten, NULL) &&
				dwWritten == sizeof(arrUTF8Preamble) && memcmp(arrUTF8Preamble, g_arrUTF8Preamble, sizeof(arrUTF8Preamble)) == 0)
			{
				bResult = TRUE;
				DWORD dwCurrentPos = 0, dwLineStart = 0;
				for (;;)
				{
					dwWritten = 0;
					DWORD dwFreeSize = dwBufferSize - dwCurrentPos;
					if (! ReadFile(hFile, pFileBuffer + dwCurrentPos, dwFreeSize, &dwWritten, NULL))
						goto end;
					BOOL bEndOfFile = dwWritten < dwFreeSize;
					dwWritten += dwCurrentPos;
					dwCurrentPos = 0;
					if (dwWritten == 0)
						goto end;
					for (;;)
					{
						if (dwCurrentPos >= dwWritten && ! bEndOfFile)
						{
							if (dwLineStart > 0)
							{
								dwCurrentPos -= dwLineStart;
								MoveMemory(pFileBuffer, pFileBuffer + dwLineStart, dwCurrentPos);
								dwLineStart = 0;
							}
							else
							{
								dwBufferSize *= 2;
								PBYTE pNewFileBuffer = new BYTE[dwBufferSize];
								if (! pNewFileBuffer)
								{
									bResult = FALSE;
									goto end;
								}
								CopyMemory(pNewFileBuffer, pFileBuffer, dwCurrentPos);
								delete[] pFileBuffer;
								pFileBuffer = pNewFileBuffer;
							}
							break;
						}
						if (dwCurrentPos < dwWritten ? pFileBuffer[dwCurrentPos] == '\r' || pFileBuffer[dwCurrentPos] == '\n' : bEndOfFile)
						{
							if (dwLineStart < dwCurrentPos && ! AddToTail(pFileBuffer + dwLineStart, dwCurrentPos - dwLineStart, true))
							{
								bResult = FALSE;
								goto end;
							}
							if (dwCurrentPos == dwWritten) // bEndOfFile == TRUE, see condition above
							{
								bResult = TRUE;
								goto end;
							}
							dwLineStart = dwCurrentPos + 1;
						}
						++dwCurrentPos;
					}
				}
			}
end:
			if (! bResult)
				FreeEntries();
			delete[] pFileBuffer;
		}
		CloseHandle(hFile);
	}
	else
	{
		DWORD dwLastError = GetLastError();
		if (dwLastError == ERROR_FILE_NOT_FOUND ||
			dwLastError == ERROR_PATH_NOT_FOUND ||
			GetFileAttributes(pszLogFileName) == INVALID_FILE_ATTRIBUTES)
		{
			bResult = TRUE; // ignore missing files
		}
	}
#ifdef _DEBUG
	DWORD dwEndTime = GetTickCount();
	TCHAR szMessage[128];
	_stprintf_s(szMessage, countof(szMessage), _T("CTextLogFile::LoadEntries(): %lu entries, %lu bytes, %lu milliseconds\r\n"), GetNumEntries(), GetNumBytes(), dwEndTime - dwStartTime);
	OutputDebugString(szMessage);
#endif
	return bResult;
}
int CDownloadThread::TransferDataPost(BOOL bWithFile)
{
	if(!bWithFile) // 不是用文件下载数据
	{
		ATLASSERT(NULL != m_pRead && m_nLength > 0 && NULL != m_pReadLength);
		if (NULL == m_pRead || m_nLength <= 0 || NULL == m_pReadLength)
			return ERR_PARAM;
	}

	CUrlCrack url;
	if (!url.Crack(m_strDownURl.c_str()))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_URLCRACKERROR,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的url = %s Crack 异常!", m_strDownURl.c_str()));
		return ERR_URLCRACKERROR;
	}

	NEED_STOP;

	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPEN,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetOpen异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		return ERR_INTOPEN;
	}

	NEED_STOP;
	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);

	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTCONNECT,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetConnect异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTCONNECT;
	}

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;

	DWORD dwFlags = 0;
	if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort())
	{
		dwFlags = INTERNET_FLAG_SECURE;
		
	}
	else if(INTERNET_DEFAULT_HTTP_PORT == url.GetPort())
	{
		dwFlags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_KEEP_CONNECTION ;
	}

	m_hInetFile = HttpOpenRequest(m_hInetConnection, _T("POST"), url.GetPath(), NULL, NULL, ppszAcceptTypes, dwFlags, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPENREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpOpenRequest异常!LastErrCode = %d", GetLastError()));
		
		CloseHandles();
		return ERR_INTOPENREQ;
	}

	if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort())
	{
		DWORD dwOptionFlags;
		DWORD dwBuffLen = sizeof(dwOptionFlags);

		InternetQueryOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwOptionFlags, &dwBuffLen);

		dwOptionFlags |= (SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID);
		InternetSetOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			&dwOptionFlags, sizeof (dwOptionFlags) );

	}

	NEED_STOP;
	
	HttpAddRequestHeaders(m_hInetFile, _T("Content-Type: application/x-www-form-urlencoded\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);
	HttpAddRequestHeaders(m_hInetFile, _T("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 
	HttpAddRequestHeaders(m_hInetFile, _T("Accept-Language: zh-CN"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	TCHAR szHeaders[1024];
	
	_stprintf_s(szHeaders, _countof(szHeaders), _T("Moneyhubuid: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 

	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, (LPVOID)m_strSendData.c_str (), m_dwPostDataLength);
	if (!bSend)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTSENDREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpSendRequest异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTSENDREQ;
	}

	NEED_STOP;
	
	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUREYINFO,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTQUREYINFO;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_OK)
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			
			CloseHandles();
			return ERR_INTFILENOTFOUND;
		}
	}

	NEED_STOP;
	
	if (bWithFile)
	{
		m_hSaveFile = CreateFile(m_strSaveFile.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (m_hSaveFile == INVALID_HANDLE_VALUE)
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_CREATEFILE,
				CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的CreateFile异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			CloseHandles();
			return ERR_CREATEFILE;
		}
	}
	
	NEED_STOP;

	LPBYTE lpszData = NULL;
	DWORD dwSize = 0;
	
	while (true)   
	{   
		NEED_STOP;

		if (!InternetQueryDataAvailable(m_hInetFile, &dwSize, 0, 0))
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUERYDATAAVAILABLE,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetQueryDataAvailable异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			// ERR_INTQUERYDATAAVAILABLE
			break;
		}

		
		lpszData = new BYTE[dwSize];
		

		DWORD dwDownloaded = 0;

		if (!InternetReadFile(m_hInetFile, (LPVOID)lpszData, dwSize, &dwDownloaded))   
		{   
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTREADFILE,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的InternetReadFile异常!LastErrCode = %d", GetLastError()));
			//OutputDebugString(strErr);
			delete []lpszData;
			CloseHandles();
			return ERR_INTREADFILE;  
		}   
		else   
		{   
			if (bWithFile) // 用文件
			{
				DWORD dwBytesWritten = 0;
				if (!WriteFile(m_hSaveFile, lpszData, dwDownloaded, &dwBytesWritten, NULL))
				{
					CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_WRITEFILE,
						CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataPost的WriteFile异常!LastErrCode = %d", GetLastError()));
					delete []lpszData;
					CloseHandles();
					return ERR_WRITEFILE;
				}
			}
			else
			{
				if (m_nLength < (*m_pReadLength) + dwDownloaded)
				{
					delete []lpszData;
					CloseHandles();
					return ERR_WRITEFILE;	
				}

				memcpy(m_pRead + (*m_pReadLength), lpszData, dwDownloaded);
				*m_pReadLength += dwDownloaded;
			}

			delete []lpszData;   

			if (dwDownloaded == 0)   
				break;   
		}   
	}

	CloseHandles();
	
	return ERR_SUCCESS;
}
int CDownloadThread::TransferDataGet()
{
	CUrlCrack url;
	if (!url.Crack(m_strDownURl.c_str()))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_URLCRACKERROR,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的url = %s Crack 异常!", m_strDownURl.c_str()));
		return ERR_URLCRACKERROR;
	}

	NEED_STOP;
	
	m_hInetSession = ::InternetOpen(MONEYHUB_USERAGENT, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (m_hInetSession == NULL)
	{
		NEED_STOP;
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPEN,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的InetOpen异常!LastErrCode = %d", GetLastError()));
		return ERR_INTOPEN;
	}
	
	NEED_STOP;
	
	DWORD dwTimeOut = 60000;
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONTROL_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_SEND_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_RECEIVE_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	InternetSetOptionEx(m_hInetSession, INTERNET_OPTION_CONNECT_TIMEOUT, &dwTimeOut, sizeof(DWORD), 0);
	
	m_hInetConnection = ::InternetConnect(m_hInetSession, url.GetHostName(), url.GetPort(), NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD)this);
	if (m_hInetConnection == NULL)
	{
		NEED_STOP;
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTCONNECT,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的连接异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTCONNECT;
	}
	
	NEED_STOP;

	LPCTSTR ppszAcceptTypes[2];
	ppszAcceptTypes[0] = _T("*/*"); 
	ppszAcceptTypes[1] = NULL;
	
	DWORD dwFlags = 0;
	if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort())
	{
		dwFlags = INTERNET_FLAG_SECURE;

	}
	else if(INTERNET_DEFAULT_HTTP_PORT == url.GetPort())
	{
		dwFlags = INTERNET_FLAG_RELOAD /*| INTERNET_FLAG_DONT_CACHE*/ | INTERNET_FLAG_KEEP_CONNECTION;
	}

	
	m_hInetFile = HttpOpenRequest(m_hInetConnection, NULL, url.GetPath(), NULL, NULL, ppszAcceptTypes, dwFlags, (DWORD)this);
	if (m_hInetFile == NULL)
	{
		NEED_STOP;
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTOPENREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的连接异常!LastErrCode = %d", GetLastError()));
		//OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTOPENREQ;
	}

	if(INTERNET_DEFAULT_HTTPS_PORT == url.GetPort())
	{
		DWORD dwOptionFlags;
		DWORD dwBuffLen = sizeof(dwOptionFlags);

		InternetQueryOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			(LPVOID)&dwOptionFlags, &dwBuffLen);

		dwOptionFlags |= (SECURITY_FLAG_IGNORE_UNKNOWN_CA | SECURITY_FLAG_IGNORE_CERT_CN_INVALID);
		InternetSetOption (m_hInetFile, INTERNET_OPTION_SECURITY_FLAGS,
			&dwOptionFlags, sizeof (dwOptionFlags) );

	}

	NEED_STOP;

//	m_wcsOriginalFileName = m_strSaveFile;
	TranslanteToBreakDownloadName(m_strSaveFile, m_wcsBreakFileName);
	//GetBreakDownloadName();
	
	TCHAR szHeaders[100];
	
	_stprintf_s(szHeaders, _countof(szHeaders), _T("Moneyhubuid: %s\r\n"), m_strHWID.c_str());
	HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 
	HttpAddRequestHeaders(m_hInetFile, _T("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 1.1.4322; .NET4.0C; .NET4.0E)\r\n"), -1, HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE); 
	
	if(m_bBreakDownload)
	{
		_stprintf_s(szHeaders,_countof(szHeaders),_T("Range: bytes=%d-"), IsBreakPointFile(m_wcsBreakFileName.c_str()) );
  		HttpAddRequestHeaders(m_hInetFile, szHeaders, -1, HTTP_ADDREQ_FLAG_ADD_IF_NEW ) ;
	}
	
	BOOL bSend = ::HttpSendRequest(m_hInetFile, NULL, 0, NULL, 0);
	if (!bSend)
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTSENDREQ,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的发送请求异常!LastErrCode = %d", GetLastError()));
		int Error = GetLastError();
		CloseHandles();
		if(Error == ERROR_INTERNET_TIMEOUT && m_bBreakDownload)
			return ERROR_INTERNET_TIMEOUT;

		return ERR_INTSENDREQ;
	}

	NEED_STOP;
	
	TCHAR szStatusCode[32];
	DWORD dwInfoSize = sizeof(szStatusCode);
	if (!HttpQueryInfo(m_hInetFile, HTTP_QUERY_STATUS_CODE, szStatusCode, &dwInfoSize, NULL))
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTQUREYINFO,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
//		OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTQUREYINFO;
	}
	else
	{
		long nStatusCode = _ttol(szStatusCode);
		if (nStatusCode != HTTP_STATUS_PARTIAL_CONTENT && nStatusCode != HTTP_STATUS_OK)
		{
			CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的!= HTTP_STATUS_OK异常!LastErrCode = %d", GetLastError()));

//		OutputDebugString(strErr);
			CloseHandles();
			return ERR_INTFILENOTFOUND;
		}
	}


	TCHAR szContentLength[32];
	dwInfoSize = sizeof(szContentLength);
	if (::HttpQueryInfo(m_hInetFile, HTTP_QUERY_CONTENT_LENGTH, szContentLength, &dwInfoSize, NULL))
	{
		if(m_bBreakDownload)
			m_ui64FileSize = (UINT64)_ttoi64(szContentLength) + IsBreakPointFile(m_wcsBreakFileName.c_str());
		else
			m_ui64FileSize = (UINT64)_ttoi64(szContentLength);
		m_ui64TotalRead = 0;
	}
	else 
	{
		CRecordProgram::GetInstance()->FeedbackError(MY_ERROR_PRO_CORE, ERR_INTFILENOTFOUND,
			CRecordProgram::GetInstance()->GetRecordInfo(L"TransferDataGet的HttpQueryInfo异常!LastErrCode = %d", GetLastError()));
//		OutputDebugString(strErr);
		CloseHandles();
		return ERR_INTFILENOTFOUND;
	}

	NEED_STOP;

	if(m_bBreakDownload)
		return DownLoadBreakpointFile();
	else
		return DownloadNoBreakFile();
}
Пример #23
0
void CRegDlg::OnBnClickedOk()
{
	CString m_regNo, m_Marchine;
	GetDlgItem(IDC_EDIT_REG)->GetWindowText(m_regNo);
	GetDlgItem(IDC_EDIT_MATCHIN)->GetWindowText(m_Marchine);

	if (m_regNo.IsEmpty())
	{
		MessageBox(_T("ÇëÊäÈë×¢²áÂë!"),_T("EtermServer·þÎñ¶Ë×¢²á"),MB_OK|MB_ICONEXCLAMATION);
		GetDlgItem(IDC_EDIT_MATCHIN)->SetFocus();
		return;
	}

	USES_CONVERSION;

	Encrypt encrypt;
	unsigned char key[] = "&feghtyj";
	CString strValid = CString(A2T(encrypt.decrypt(key, (char*)T2A(m_regNo))));

	if (m_Marchine == strValid)
	{
		CRegistry reg(HKEY_LOCAL_MACHINE);
		BOOL bRet = reg.Open(_T("SOFTWARE\0"));
		if (bRet)
		{
			BOOL bRet = reg.Open(_T("EtermServer\0"));
			if (!bRet)
				bRet = reg.CreateKey(_T("EtermServer"));
			bRet = reg.Open(_T("Register\0"));
			if (!bRet)
				bRet = reg.CreateKey(_T("Register"));
			bRet = reg.Write(_T(""), m_regNo);

			if (bRet)
			{
				MessageBox(_T("×¢²á³É¹¦!"), _T("EtermServer·þÎñ¶Ë×¢²á"), MB_OK | MB_ICONINFORMATION);
				CDialogEx::OnOK();
			}
		}
		if (!bRet)
		{
			FILE* file = NULL;
			TCHAR szFile[1024] = { 0 };
			_stprintf_s(szFile, _T("%s\\register.dat"), Global::szAppPath);
			errno_t no = _tfopen_s(&file, szFile, _T("w"));
			if (no == 0)
			{
				char szBuf[1024] = { 0 };
				fputs(CT2A(m_regNo), file);
				fclose(file);

				MessageBox(_T("×¢²á³É¹¦!"), _T("EtermServer·þÎñ¶Ë×¢²á"), MB_OK | MB_ICONINFORMATION);
				CDialogEx::OnOK();			
			}
			else
			{
				MessageBox(_T("×¢²áʧ°Ü!"), _T("EtermServer·þÎñ¶Ë×¢²á"), MB_OK | MB_ICONEXCLAMATION);
			}
		}
	}
	else
	{
		MessageBox(_T("×¢²áʧ°Ü!"), _T("EtermServer·þÎñ¶Ë×¢²á"), MB_OK | MB_ICONEXCLAMATION);
	}
}
// Execute the requested client command
DWORD Execute( HANDLE hPipe, RemComMessage* pMsg, DWORD* pReturnCode )
{
	PROCESS_INFORMATION pi;

	STARTUPINFO si;
	::ZeroMemory( &si, sizeof(si) );
	si.cb = sizeof(si);

	SECURITY_ATTRIBUTES saAttr;
	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
	saAttr.bInheritHandle = true;
	saAttr.lpSecurityDescriptor = NULL;
	HANDLE hStdoutRead = INVALID_HANDLE_VALUE, hStdoutWrite = INVALID_HANDLE_VALUE;
	HANDLE hStdinRead = INVALID_HANDLE_VALUE, hStdinWrite = INVALID_HANDLE_VALUE;

	if (!CreatePipe(&hStdoutRead, &hStdoutWrite, &saAttr, 0))
		return 20000+GetLastError();

	if (!SetHandleInformation(hStdoutRead, HANDLE_FLAG_INHERIT, 0))
		return 30000+GetLastError();	// don't inherit the reader end

	if (!CreatePipe(&hStdinRead, &hStdinWrite, &saAttr, 0))
		return 40000+GetLastError();

	if (!SetHandleInformation(hStdinWrite, HANDLE_FLAG_INHERIT, 0))
		return 50000+GetLastError();	// don't inherit the reader end

	si.hStdInput = hStdinRead;
	si.hStdOutput = hStdoutWrite;
	si.hStdError = hStdoutWrite;
	si.dwFlags |= STARTF_USESTDHANDLES;
	
	*pReturnCode = 0;

	// Initializes command
	// cmd.exe /c /q allows us to execute internal dos commands too.
	TCHAR szCommand[_MAX_PATH];
	_stprintf_s( szCommand, sizeof(szCommand), _T("cmd.exe /q /c \"%s\""), pMsg->szCommand );

	if (!::ImpersonateNamedPipeClient(hPipe))
		return 60000+GetLastError();

	HANDLE hImpersonationToken,hPrimaryToken;
	if (!::OpenThreadToken(::GetCurrentThread(),TOKEN_ALL_ACCESS,TRUE,&hImpersonationToken))
		return 70000+GetLastError();

	if (!::DuplicateTokenEx(hImpersonationToken,MAXIMUM_ALLOWED,0,
		SecurityIdentification, TokenPrimary,&hPrimaryToken))
		return 80000+GetLastError();
	CloseHandle(hImpersonationToken);
	RevertToSelf();

   // Start the requested process
	if ( CreateProcessAsUser(hPrimaryToken, 
         NULL, 
         szCommand, 
         NULL,
         NULL, 
         TRUE,
         pMsg->dwPriority | CREATE_NO_WINDOW,
         NULL, 
         pMsg->szWorkingDir[0] != _T('\0') ? pMsg->szWorkingDir : NULL, 
         &si, 
         &pi ) )
   {
		HANDLE hProcess = pi.hProcess;
		// these handles are meant only for the child process, otherwise we'll block forever
		CloseHandle(hStdinRead);
		CloseHandle(hStdoutWrite);

		// pump the stdin from the client to the child process
		// in a different thread
		CopyThreadParams* ctp = new CopyThreadParams();
		ctp->hPipe = hPipe;
		ctp->hStdin = hStdinWrite;
		_beginthread(CopyStream,0,ctp);

		// feed the output from the child process to the client
		while (true) {
			byte buf[1024];
			DWORD dwRead = 0, dwWritten;

			if (!::ReadFile(hStdoutRead,buf+4,sizeof(buf)-4,&dwRead,NULL) || dwRead==0)
				break;

			*((DWORD*)buf) = dwRead;
			::WriteFile(hPipe, buf, sizeof(DWORD)+dwRead, &dwWritten, NULL);
		}

		*pReturnCode = 0;

		// Waiting for process to terminate
        WaitForSingleObject( hProcess, INFINITE );
        GetExitCodeProcess( hProcess, pReturnCode );
		return 0;
	} else {
		// error code 1314 here means the user of this process
		// doesn't have the privilege to call CreateProcessAsUser.
		// when this is run as a service, the LOCAL_SYSTEM user
		// has a privilege to do it, but if you run this under
		// the debugger, your user account might not have that privilege.
		//
		// to fix that, go to control panel / administartive tools / local security policy
		// user rights / replace process token level
		// and make sure your user is in.
		// once the above is set, the system needs to be restarted.
		return 10000+GetLastError();
	}
}
Пример #25
0
void LoadLangDll()
{
	if ((g_langid != g_ShellCache.GetLangID())&&((g_langTimeout == 0)||(g_langTimeout < GetTickCount())))
	{
		g_langid = g_ShellCache.GetLangID();
		DWORD langId = g_langid;
		TCHAR langDll[MAX_PATH*4];
		HINSTANCE hInst = NULL;
		TCHAR langdir[MAX_PATH] = {0};
		char langdirA[MAX_PATH] = {0};
		if (GetModuleFileName(g_hmodThisDll, langdir, _countof(langdir))==0)
			return;
		if (GetModuleFileNameA(g_hmodThisDll, langdirA, _countof(langdirA))==0)
			return;
		TCHAR * dirpoint = _tcsrchr(langdir, '\\');
		char * dirpointA = strrchr(langdirA, '\\');
		if (dirpoint)
			*dirpoint = 0;
		if (dirpointA)
			*dirpointA = 0;
		dirpoint = _tcsrchr(langdir, '\\');
		dirpointA = strrchr(langdirA, '\\');
		if (dirpoint)
			*dirpoint = 0;
		if (dirpointA)
			*dirpointA = 0;
		strcat_s(langdirA, "\\Languages");
//		bindtextdomain ("subversion", langdirA);

		BOOL bIsWow = FALSE;
		IsWow64Process(GetCurrentProcess(), &bIsWow);

		do
		{
			if (bIsWow)
				_stprintf_s(langDll, _T("%s\\Languages\\TortoiseProc32%lu.dll"), langdir, langId);
			else
				_stprintf_s(langDll, _T("%s\\Languages\\TortoiseProc%lu.dll"), langdir, langId);
			BOOL versionmatch = TRUE;

			struct TRANSARRAY
			{
				WORD wLanguageID;
				WORD wCharacterSet;
			};

			DWORD dwReserved,dwBufferSize;
			dwBufferSize = GetFileVersionInfoSize((LPTSTR)langDll,&dwReserved);

			if (dwBufferSize > 0)
			{
				LPVOID pBuffer = (void*) malloc(dwBufferSize);

				if (pBuffer != (void*) NULL)
				{
					UINT        nInfoSize = 0;
					UINT        nFixedLength = 0;
					LPSTR       lpVersion = NULL;
					VOID*       lpFixedPointer;
					TRANSARRAY* lpTransArray;
					TCHAR       strLangProductVersion[MAX_PATH];

					if (GetFileVersionInfo((LPTSTR)langDll,
						dwReserved,
						dwBufferSize,
						pBuffer))
					{
						// Query the current language
						if (VerQueryValue(	pBuffer,
							_T("\\VarFileInfo\\Translation"),
							&lpFixedPointer,
							&nFixedLength))
						{
							lpTransArray = (TRANSARRAY*) lpFixedPointer;

							_stprintf_s(strLangProductVersion, _T("\\StringFileInfo\\%04x%04x\\ProductVersion"),
								lpTransArray[0].wLanguageID, lpTransArray[0].wCharacterSet);

							if (VerQueryValue(pBuffer,
								(LPTSTR)strLangProductVersion,
								(LPVOID *)&lpVersion,
								&nInfoSize))
							{
								versionmatch = (_tcscmp((LPCTSTR)lpVersion, _T(STRPRODUCTVER)) == 0);
							}

						}
					}
					free(pBuffer);
				} // if (pBuffer != (void*) NULL)
			} // if (dwBufferSize > 0)
			else
				versionmatch = FALSE;

			if (versionmatch)
				hInst = LoadLibrary(langDll);
			if (hInst != NULL)
			{
				if (g_hResInst != g_hmodThisDll)
					FreeLibrary(g_hResInst);
				g_hResInst = hInst;
			}
			else
			{
				DWORD lid = SUBLANGID(langId);
				lid--;
				if (lid > 0)
				{
					langId = MAKELANGID(PRIMARYLANGID(langId), lid);
				}
				else
					langId = 0;
			}
		} while ((hInst == NULL) && (langId != 0));
		if (hInst == NULL)
		{
			// either the dll for the selected language is not present, or
			// it is the wrong version.
			// fall back to English and set a timeout so we don't retry
			// to load the language dll too often
			if (g_hResInst != g_hmodThisDll)
				FreeLibrary(g_hResInst);
			g_hResInst = g_hmodThisDll;
			g_langid = 1033;
			// set a timeout of 10 seconds
			if (g_ShellCache.GetLangID() != 1033)
				g_langTimeout = GetTickCount() + 10000;
		}
		else
			g_langTimeout = 0;
	} // if (g_langid != g_ShellCache.GetLangID())
}
Пример #26
0
BOOL CProfileHelper::WritePrivateProfileInt(LPCTSTR lpszSection, LPCTSTR lpszEntry, int nValue, LPCTSTR lpszProfileName)
{
    TCHAR szInt[MAX_INT_STR];
    _stprintf_s(szInt, MAX_INT_STR, _T("%d"), nValue);
    return WritePrivateProfileString(lpszSection, lpszEntry, szInt, lpszProfileName);
}
Пример #27
0
//-----------------------------------------------------------------------------------------------------------   
// 函数: SearchInReg   
// 功能: 在注册表指定位置搜索某指定字符串.   
// 参数: [in] LPONSEARCHPROC fnOnSearchProc - 搜索回调函数   
//       [in] const TCHAR* ptszRegPath - 搜索路径(直接包含根键并支持缩写)   
//       [in] const TCHAR* ptszSearchKey - 搜索关键字符串   
//       [in] bool isFuzzy = true - 是否采用模糊方式   
//       [in] bool isSearchKey = true - 是否搜索键   
//       [in] bool isSearchValueName = true - 是否搜索值名   
//       [in] bool isSearchValueData = true - 是否搜索值   
// 返回: void   
// 说明: 若要统计搜索数量, 请使用外部变量在回调函数中自行统计.   
//-----------------------------------------------------------------------------------------------------------   
void Registry::SearchInReg(void* p,LPONSEARCHPROC fnOnSearchProc, const TCHAR* ptszRegPath, 
						   const TCHAR* ptszSearchKey, bool isFuzzy /* = true */, bool isSearchKey /* = true */, 
						   bool isSearchValueName /* = true */, bool isSearchValueData /* = true */)   
{   
	// 参数无效   
	if (NULL == ptszRegPath || 0 == ::_tcslen(ptszRegPath) || NULL == ptszSearchKey || 0 == ::_tcslen(ptszSearchKey))   
	{   
		return;   
	}   
	// 什么都不搜索   
	if (false == isSearchKey && false == isSearchValueName && false == isSearchValueData)   
	{   
		return;   
	}   
	const long MAX_KEY = 255;                       // 键最大长度   
	const long MAX_VALUENAME = 16383;               // 值名最大长度   
	TCHAR* ptszRegPathCopy = NULL;                  // ptszRegPath 字符串拷贝   
	TCHAR* ptszRegSubPath = NULL;                   // 子键路径字符串   
	HKEY hPredKey = NULL;                           // 系统预设主键句柄   
	HKEY hKey = NULL;                               // 操作键句柄   
	DWORD dwSubKeyCount = 0;                        // 当前子键数   
	DWORD dwValueCount = 0;                         // 当前键值数   
	DWORD cbSubKey = MAX_KEY;                       // 子键字符串长度   
	TCHAR ptszSubKey[MAX_KEY] = _T("");             // 子键字符串   
	DWORD dwValueNameLength = MAX_VALUENAME;        // 值名字符串长度   
	TCHAR ptszValueName[MAX_VALUENAME] = _T("");    // 值名字符串   
	DWORD dwType = 0;                               // 键值数据类型   
	DWORD cbData = 0;                               // 键值数据大小(byte)   
	BYTE* lpData = NULL;                            // 键值数据   
	// ptszRegPath 字符串做为常量传入, 不允许修改,    
	// 所以需创建 Reg 字符串的拷贝, 用于后续操作.   
	ptszRegPathCopy = (TCHAR*)::malloc((::_tcslen(ptszRegPath) + 1) * sizeof(TCHAR));   
	::_tcscpy_s(ptszRegPathCopy, ::_tcslen(ptszRegPath) + 1, ptszRegPath);   
	// 提取系统预设主键字符串   
	::_tcsstr(ptszRegPathCopy, _T("\\"))[0] = _T('\0');   
	// 判断获取 hPredKey   
	if (0 == ::_tcsicmp(ptszRegPathCopy, _T("HKEY_CLASSES_ROOT")) ||    
		0 == ::_tcsicmp(ptszRegPathCopy, _T("HKCR")))   
	{   
		hPredKey = HKEY_CLASSES_ROOT;   
	}   
	else if (0 == ::_tcsicmp(ptszRegPathCopy, _T("HKEY_LOCAL_MACHINE")) ||    
		0 == ::_tcsicmp(ptszRegPathCopy, _T("HKLM")))   
	{   
		hPredKey = HKEY_LOCAL_MACHINE;   
	}   
	else if (0 == ::_tcsicmp(ptszRegPathCopy, _T("HKEY_CURRENT_USER")) ||    
		0 == ::_tcsicmp(ptszRegPathCopy, _T("HKCU")))   
	{   
		hPredKey = HKEY_CURRENT_USER;   
	}   
	else if (0 == ::_tcsicmp(ptszRegPathCopy, _T("HKEY_USERS")) ||    
		0 == ::_tcsicmp(ptszRegPathCopy, _T("HKU")))   
	{   
		hPredKey = HKEY_USERS;   
	}   
	else if (0 == ::_tcsicmp(ptszRegPathCopy, _T("HKEY_PERFORMANCE_DATA")) ||    
		0 == ::_tcsicmp(ptszRegPathCopy, _T("HKPD")))   
	{   
		hPredKey = HKEY_PERFORMANCE_DATA;   
	}   
	else if (0 == ::_tcsicmp(ptszRegPathCopy, _T("HKEY_PERFORMANCE_TEXT")) ||    
		0 == ::_tcsicmp(ptszRegPathCopy, _T("HKPT")))   
	{   
		hPredKey = HKEY_PERFORMANCE_TEXT;   
	}   
	else if (0 == ::_tcsicmp(ptszRegPathCopy, _T("HKEY_PERFORMANCE_NLSTEXT")) ||    
		0 == ::_tcsicmp(ptszRegPathCopy, _T("HKPN")))   
	{   
		hPredKey = HKEY_PERFORMANCE_NLSTEXT;   
	}   
	else if (0 == ::_tcsicmp(ptszRegPathCopy, _T("HKEY_CURRENT_CONFIG")) ||    
		0 == ::_tcsicmp(ptszRegPathCopy, _T("HKCC")))   
	{   
		hPredKey = HKEY_CURRENT_CONFIG;   
	}   
	else if (0 == ::_tcsicmp(ptszRegPathCopy, _T("HKEY_DYN_DATA")) ||    
		0 == ::_tcsicmp(ptszRegPathCopy, _T("HKDD")))   
	{   
		hPredKey = HKEY_DYN_DATA;   
	}   
	else  
	{   
		return;   
	}   
	if (NULL != ptszRegPathCopy)   
	{   
		::free(ptszRegPathCopy);   
		ptszRegPathCopy = NULL;   
	}   
	// 创建 ptszRegPath 字符串的新拷贝   
	ptszRegPathCopy = (TCHAR*)::malloc((::_tcslen(ptszRegPath) + 1) * sizeof(TCHAR));   
	::_tcscpy_s(ptszRegPathCopy, ::_tcslen(ptszRegPath) + 1, ptszRegPath);   
	// 提取子键路径字符串   
	ptszRegSubPath = ::_tcsstr(ptszRegPathCopy, _T("\\"));   
	if (NULL != ptszRegSubPath)   
	{   
		ptszRegSubPath++;   
		if (ERROR_SUCCESS != ::RegOpenKeyEx(hPredKey, ptszRegSubPath, 0, KEY_READ, &hKey))   
		{   
			return;   
		}   
	}   
	else  
	{   
		hKey = hPredKey;   
	}   
	if (NULL != ptszRegPathCopy)   
	{   
		::free(ptszRegPathCopy);   
		ptszRegPathCopy = NULL;   
	}   
	// 获取键信息(主要是子键数和键值数, 用于下面遍历)   
	// 注: 也可以不用主动获取数量, 而由枚举函数(RegEnumXXX)返回 ERROR_NO_MORE_ITEMS 来判断枚举结束.   
	if (ERROR_SUCCESS != ::RegQueryInfoKey(hKey, NULL, NULL, NULL, &dwSubKeyCount, NULL, NULL, &dwValueCount, NULL, NULL, NULL, NULL))   
	{   
		if (NULL != hKey)   
		{   
			::RegCloseKey(hKey);   
			hKey = NULL;   
		}   
		return;   
	}   
	// 遍历子键   
	if (0 != dwSubKeyCount)   
	{   
		for (DWORD i = 0; i < dwSubKeyCount; i++)   
		{   
			cbSubKey = MAX_KEY;   
			if (ERROR_SUCCESS == ::RegEnumKeyEx(hKey, i, ptszSubKey, &cbSubKey, NULL, NULL, NULL, NULL))   
			{   
				TCHAR ptszNextPath[1024]; // 1024 为预估大小, 不够则适当加大   
				_stprintf_s(ptszNextPath, 1024, _T("%s\\%s"), ptszRegPath, ptszSubKey);   
				SearchInReg(p,fnOnSearchProc, ptszNextPath, ptszSearchKey, isFuzzy, isSearchKey, isSearchValueName, isSearchValueData); // 递归   
				// 回调处理搜索过程   
				fnOnSearchProc(p,false, ptszNextPath, NULL, hKey);   
				// 比对子键   
				if (true == isSearchKey &&                          // 判断是否要求比对子键   
					true == isFuzzy ?                               // 判断是否采用模糊方式   
					NULL != ::_tcsstr(ptszSubKey, ptszSearchKey) :  // 采用模糊方式比对   
				0 == ::_tcsicmp(ptszSearchKey, ptszSubKey))     // 采用非模糊方式比对   
				{   
					// 回调处理搜索结果   
					TCHAR* ptszResultText = NULL;   // 结果字段(用于显示)   
					TCHAR* ptszMatched = NULL;      // 被匹配部分的字段   
					HKEY hResultKey = NULL;         // 当前键的句柄, 用于在回调中对该键操作   
					ptszResultText = (TCHAR*)::malloc((::_tcslen(ptszNextPath) + 1) * sizeof(TCHAR));   
					::_tcscpy_s(ptszResultText, ::_tcslen(ptszNextPath) + 1, ptszNextPath);   
					ptszMatched = (TCHAR*)::malloc((::_tcslen(ptszSubKey) + 1) * sizeof(TCHAR));   
					::_tcscpy_s(ptszMatched, ::_tcslen(ptszSubKey) + 1, ptszSubKey);   
					::RegOpenKeyEx(hKey, ptszSubKey, 0, KEY_ALL_ACCESS, &hResultKey);   
					fnOnSearchProc(p,true, ptszResultText, ptszMatched, hKey);   
					// 清理   
					if (NULL != ptszResultText)   
					{   
						::free(ptszResultText);   
						ptszResultText = NULL;   
					}   
					if (NULL != ptszMatched)   
					{   
						::free(ptszMatched);   
						ptszMatched = NULL;   
					}   
					if (NULL != hResultKey)   
					{   
						::RegCloseKey(hResultKey);   
						hResultKey = NULL;   
					}   
				}   
			}   
		}   
	}   
	// 遍历键值   
	if (0 != dwValueCount)   
	{   
		for (DWORD i = 0; i < dwValueCount; i++)   
		{   
			if (ERROR_SUCCESS == ::RegEnumValue(hKey, i, ptszValueName, &dwValueNameLength, NULL, &dwType, NULL, &cbData))   
			{   
				// 比对值名   
				if (true == isSearchValueName &&                        // 判断是否要求比对值名   
					true == isFuzzy ?                                   // 判断是否采用模糊方式   
					NULL != ::_tcsstr(ptszValueName, ptszSearchKey) :   // 采用模糊方式比对   
				0 == ::_tcsicmp(ptszSearchKey, ptszValueName))      // 采用非模糊方式比对   
				{   
					// 回调处理搜索结果   
					TCHAR* ptszResultText = NULL;   // 结果字段(用于显示)   
					TCHAR* ptszMatched = NULL;      // 匹配部分字段   
					HKEY hResultKey = NULL;         // 当前键的句柄, 用于在回调中对该键操作   
					ptszResultText = (TCHAR*)::malloc((::_tcslen(ptszRegPath) + ::_tcslen(ptszValueName) + 4) * sizeof(TCHAR));   
					_stprintf_s(ptszResultText, ::_tcslen(ptszRegPath) + ::_tcslen(ptszValueName) + 4, _T("%s \"%s\""), ptszRegPath, ptszValueName);   
					ptszMatched = (TCHAR*)::malloc((::_tcslen(ptszValueName) + 1) * sizeof(TCHAR));   
					::_tcscpy_s(ptszMatched, ::_tcslen(ptszValueName) + 1, ptszValueName);   
					::RegOpenKeyEx(hKey, ptszSubKey, 0, KEY_ALL_ACCESS, &hResultKey);   
					fnOnSearchProc(p,true, ptszResultText, ptszMatched, hKey);   
					// 清理   
					if (NULL != ptszResultText)   
					{   
						::free(ptszResultText);   
						ptszResultText = NULL;   
					}   
					if (NULL != ptszMatched)   
					{   
						::free(ptszMatched);   
						ptszMatched = NULL;   
					}   
					if (NULL != hResultKey)   
					{   
						::RegCloseKey(hResultKey);   
						hResultKey = NULL;   
					}   
				}   
				// 判断若该值为字符串格式且不为空, 则对值进行比对.   
				if ((REG_SZ == dwType || REG_MULTI_SZ == dwType || REG_EXPAND_SZ == dwType) && 0 != cbData)   
				{   
					lpData = (BYTE*)::malloc(cbData);   
					if (ERROR_SUCCESS == ::RegQueryValueEx(hKey, ptszValueName, NULL, NULL, lpData, &cbData))   
					{   
						// 将值转换为字符串类型   
						TCHAR* ptszValueData = (TCHAR*)::malloc(cbData);   
						::_tcscpy_s(ptszValueData, cbData / sizeof(TCHAR), (TCHAR*)lpData);   
						// 对比值   
						if (true == isSearchValueData &&                        // 判断是否要求比对值   
							true == isFuzzy ?                                   // 判断是否采用模糊方式   
							NULL != ::_tcsstr(ptszValueData, ptszSearchKey) :   // 采用模糊方式比对   
						0 == ::_tcsicmp(ptszSearchKey, ptszValueData))      // 采用非模糊方式比对   
						{   
							// 回调处理搜索结果   
							TCHAR* ptszResultText = NULL;   // 结果字段(用于显示)   
							TCHAR* ptszMatched = NULL;      // 匹配部分字段   
							HKEY hResultKey = NULL;         // 当前键的句柄, 用于在回调中对该键操作   
							ptszResultText = (TCHAR*)::malloc((::_tcslen(ptszRegPath) + ::_tcslen(ptszValueName) + ::_tcslen(ptszValueData) + 8) * sizeof(TCHAR));   
							_stprintf_s(ptszResultText, ::_tcslen(ptszRegPath) + ::_tcslen(ptszValueName) + ::_tcslen(ptszValueData) + 8, _T("%s \"%s\"=\"%s\""), ptszRegPath, ptszValueName, ptszValueData);   
							ptszMatched = (TCHAR*)::malloc((::_tcslen(ptszValueData) + 1) * sizeof(TCHAR));   
							::_tcscpy_s(ptszMatched, ::_tcslen(ptszValueData) + 1, ptszValueData);   
							::RegOpenKeyEx(hKey, ptszSubKey, 0, KEY_ALL_ACCESS, &hResultKey);   
							fnOnSearchProc(p,true, ptszResultText, ptszMatched, hKey);   
							// 清理   
							if (NULL != ptszResultText)   
							{   
								::free(ptszResultText);   
								ptszResultText = NULL;   
							}   
							if (NULL != ptszMatched)   
							{   
								::free(ptszMatched);   
								ptszMatched = NULL;   
							}   
							if (NULL != hResultKey)   
							{   
								::RegCloseKey(hResultKey);   
								hResultKey = NULL;   
							}   
						}   
						// 清理   
						if (NULL != ptszValueData)   
						{   
							::free(ptszValueData);   
							ptszValueData = NULL;   
						}   
					}   
					// 清理   
					if (NULL != lpData)   
					{   
						::free(lpData);   
						lpData = NULL;   
					}   
				}   
			}   
		}   
	}   
	// 清理   
	if (NULL != hKey)   
	{   
		::RegCloseKey(hKey);   
		hKey = NULL;   
	}   
}
Пример #28
0
LONG CMiniDumper::TopLevelFilter(struct _EXCEPTION_POINTERS *pExceptionInfo)
{
	//Only dump once.
	if(m_bHaveDumped)
		return 0;

	m_bHaveDumped = TRUE;
	LONG retval = EXCEPTION_CONTINUE_SEARCH;

	// firstly see if dbghelp.dll is around and has the function we need
	// look next to the EXE first, as the one in System32 might be old 
	// (e.g. Windows 2000)
	HMODULE hDll = NULL;
	TCHAR szDbgHelpPath[_MAX_PATH] = {0};

	if(GetModuleFileName( NULL, szDbgHelpPath, _MAX_PATH ))
	{
		PathRemoveFileSpec(szDbgHelpPath);
		PathAppend(szDbgHelpPath, _T("DBGHELP.DLL"));
		hDll = ::LoadLibrary( szDbgHelpPath );
	}
	if(hDll == NULL)		// load any version we can
		hDll = ::LoadLibrary(_T("DBGHELP.DLL"));

	if(hDll == NULL)
	{
		ASSERT(FALSE);
		return retval;
	}

	LPCTSTR szResult = NULL;
	MINIDUMPWRITEDUMP pDump = (MINIDUMPWRITEDUMP)::GetProcAddress( hDll, "MiniDumpWriteDump" );
	if(pDump == NULL)
	{
		ASSERT(FALSE);
		return retval;
	}

	TCHAR szDumpPath[_MAX_PATH] = {0};
	TCHAR szScratch [_MAX_PATH] = {0};

	//Save it to the desktop
	SHGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, SHGFP_TYPE_CURRENT, szDumpPath);
	CString szFileName;
	szFileName.Format(_T("%s_%d.dmp"), m_szAppName, BUILD_NO);
	PathAppend(szDumpPath, szFileName);

	CString sMsg = CLocaleTool::Instance()->LoadString(ID_MINIDUMP_CONFIRM, _T("Something bad happened in your program, would you like to save a diagnostic file?"));
	CString sErrFormat = CLocaleTool::Instance()->LoadString(ID_MINIDUMP_REPORT_ERR, _T("Failed to save dump file to '%s' (error %d)"));

	if (::MessageBox(NULL, sMsg, m_szAppName, MB_YESNO )==IDYES)
	{
		HANDLE hFile = ::CreateFile(szDumpPath, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS,
			FILE_ATTRIBUTE_NORMAL, NULL);

		if (hFile!=INVALID_HANDLE_VALUE)
		{
			_MINIDUMP_EXCEPTION_INFORMATION ExInfo;

			ExInfo.ThreadId = ::GetCurrentThreadId();
			ExInfo.ExceptionPointers = pExceptionInfo;
			ExInfo.ClientPointers = NULL;

			// write the dump
			BOOL bOK = pDump( GetCurrentProcess(), GetCurrentProcessId(), hFile, MiniDumpNormal, &ExInfo, NULL, NULL );
			if(bOK)
			{
				CString sFormat = CLocaleTool::Instance()->LoadString(ID_MINIDUMP_REPORT, _T("Saved dump file to '%s'"));
				_stprintf_s(szScratch,_MAX_PATH, sFormat, szDumpPath );
				szResult = szScratch;
				retval = EXCEPTION_EXECUTE_HANDLER;
			}
			else
			{
				_stprintf_s(szScratch, _MAX_PATH, sErrFormat, szDumpPath, GetLastError() );
				szResult = szScratch;
			}
			::CloseHandle(hFile);
		}
		else
		{
			_stprintf_s(szScratch, _MAX_PATH, sErrFormat, szDumpPath, GetLastError());
			szResult = szScratch;
		}
	}

	if (szResult)
		::MessageBox( NULL, szResult, m_szAppName, MB_OK );

	return retval;
}
Пример #29
0
/*---------------------------------------------------------------------------*\
 * NAME: ChangeAppIDLaunchAndActivateACL                                     *
 * --------------------------------------------------------------------------*
 * DESCRIPTION: Modifies an AppID's launch access control list.              *
 * The system uses the AppID launch ACL to determine if a principal          *
 * (a user or group of users) is allowed to launch the COM server            *
 * associated with the AppID.                                                *
 * --------------------------------------------------------------------------*
 *  ARGUMENTS:                                                               *
 *                                                                           *
 *  tszAppID - The Application ID you wish to modify                         *
 *  (e.g. "{99999999-9999-9999-9999-00AA00BBF7C7}")                          *
 *                                                                           *
 *  tszPrincipal - Name of user or group (e.g. "redmond\johndoe")            *
 *                                                                           *
 *  fSetPrincipal - TRUE if you want to add/update the principal's entry     *
 *  in the ACL, FALSE if you want to remove the principal from the ACL       *
 *                                                                           *
 *  fPermit - TRUE if you want to allow the principal to launch the object   *
 *  FALSE if you want to prevent the principal from launching the object     *
 *                                                                           *
 *  dwAccessMask - Specifies what type of access the principal is to be      *
 *  given.  Can be any combination of the COM_RIGHTS_* values                *
 *                                                                           *
 * --------------------------------------------------------------------------*
 * RETURNS: WIN32 Error Code                                                 *
\*---------------------------------------------------------------------------*/
DWORD ChangeAppIDLaunchAndActivateACL (
    LPTSTR tszAppID,
    LPTSTR tszPrincipal,
    BOOL fSetPrincipal,
    BOOL fPermit,
    DWORD dwAccessMask
    )
{
    TCHAR   tszKeyName [256] = {0};
    DWORD dwReturnValue = ERROR_SUCCESS;

    _stprintf_s (tszKeyName, 
                 RTL_NUMBER_OF(tszKeyName),
                 tszAppID [0] == '{' ? _T("APPID\\%s") : _T("APPID\\{%s}"), 
                 tszAppID);

    if (fSetPrincipal)
    {
        dwReturnValue = 
            RemovePrincipalFromNamedValueSD (HKEY_CLASSES_ROOT, 
                                             tszKeyName, 
                                             _T("LaunchPermission"), 
                                             tszPrincipal, 
                                             fPermit ? ACCESS_ALLOWED_ACE_TYPE : 
                                             ACCESS_DENIED_ACE_TYPE);

        if(dwReturnValue != ERROR_SUCCESS) return dwReturnValue;
        
        dwReturnValue = 
            UpdatePrincipalInNamedValueSD(HKEY_CLASSES_ROOT, 
                                          tszKeyName, 
                                          _T("LaunchPermission"), 
                                          tszPrincipal, 
                                          dwAccessMask, 
                                          TRUE, 
                                          fPermit ? ACCESS_DENIED_ACE_TYPE : 
                                          ACCESS_ALLOWED_ACE_TYPE);

        if(dwReturnValue != ERROR_SUCCESS) return dwReturnValue;

        dwReturnValue = 
            AddPrincipalToNamedValueSD (HKEY_CLASSES_ROOT, 
                                        tszKeyName, 
                                        _T("LaunchPermission"), 
                                        tszPrincipal, 
                                        fPermit, 
                                        dwAccessMask,
                                        SDTYPE_APPLICATION_LAUNCH);
    } 
    else
    {
        dwReturnValue =  
            RemovePrincipalFromNamedValueSD (HKEY_CLASSES_ROOT, 
                                             tszKeyName, 
                                             _T("LaunchPermission"), 
                                             tszPrincipal, 
                                             ACE_TYPE_ALL);
    }

    return dwReturnValue;
}
Пример #30
0
//+++++++++++++++++++++++++++++++++++++++++++++++++
// ゲーム本編の更新処理
//-------------------------------------------------
// ゲームのメイン処理部分
//--in---------------------------------------------
// ウィンドウハンドル
//--out--------------------------------------------
// なし
//+++++++++++++++++++++++++++++++++++++++++++++++++
void GameMain(HWND hWnd)
{
#if (DEBUG_ON)

	TCHAR	str[256];
	g_szDebug[0] = _T('\0');	//デバッグ ストリング バッファ初期化
	_stprintf_s(str, _T("FPS = %.1f PLAYER_POS: X:%.1f Y:%.1f Z:%.1f \n NUM: 1:%f 2:%f 3:%f \n"), GetFPS(), x, y, z, num1, num2, num3);
	lstrcat(g_szDebug, str);

#endif
	VECTOR3 vecx, vecy;
	//画面遷移
	switch(g_nStatus)
	{
	case INIT:
		CreateClass();			//クラス領域の確保とロード
		p_Field->Init();			//フィールド
		p_Result->Init();
		g_loadFlg = false;
		SetThread();
		g_nStatus = LOADING;	//スルー
	case LOADING:
		if(g_loadFlg)
		{
			g_nStatus = STARTINIT;
			CloseHandle(Loadhandle);
		}
		break;
	case STARTINIT:
		p_Op->Init();				//オープニング
		p_Camera->ResetOp();		//カメラのリセット
		g_nStatus = START;

		break;
	case START:
		p_Camera->SetOpCamera();	//カメラのセット
		if(p_Op->Update())
			g_nStatus = MENU_INIT;
		break;
	case MENU_INIT:
		p_Camera->ResetOp();		//カメラのリセット
		p_Select->Init();
		g_nStatus = MENU;
		break;
	case MENU:
		p_Camera->SetOpCamera();	//カメラのセット
		if(p_Select->Update())
		{
			switch(p_Select->GetSelect())
			{
			case 0:
				p_SE->PlaySE(YES);
				g_nStatus = GAME_INIT_START;
				p_Select->Release();
				break;
			case 1:
				break;
			case 2:
				break;
			case 3:
				g_nStatus = END;
				p_Select->Release();
				break;
			default:break;
			}
		}
		num3 = (float)p_Select->GetSelect();
		break;
	case GAME_INIT_START:
		g_loadFlg = false;
		p_Ambient->Init();			//環境
		p_Score->Init();			//スコアの初期化
		p_Player->Init();			//プレイヤー
		p_Enemy->Init(p_Player);	//エネミー
		p_PlayerHpBar->Init();		//プレイヤーバー
		p_BossHpBar->Init();		//ボスバー
		p_2D->Init();
		
		//SetThread();
		g_nStatus = GAME_INIT;	//スルー
	case GAME_INIT:
		//生成
		//p_Score->Load();
		//p_Ambient->Load();
		//p_Player->Load();
		//p_Enemy->Load();
		//p_BossHpBar->Load();
		p_2D->Load();
		p_EffectMng->Load();

		//リセット
		p_Ambient->Reset();			//環境のリセット
		p_Player->Reset();			//プレイヤーのリセット
		p_Score->Reset();			//スコアのリセット
		p_Enemy->Reset();			//エネミーのリセット
		p_Camera->ResetGame();		//カメラのリセット
		p_PlayerHpBar->Reset();
		p_BossHpBar->Reset();
		p_Time->Reset();
		g_CubeFlg = true;
		//SetExecTime(timeGetTime());
		//if(g_loadFlg)
		//{
		//	CloseHandle(Loadhandle);
			g_nStatus = GAME_FILLER_START;
		//}
		break;
	case GAME_FILLER_START:
		if(p_2D->Update())
		{
			g_nStatus = GAME;
			p_2D->Reset();
			p_Time->Start();
			p_2D->m_Cnt = 0;
			p_SE->PlayBG(BG_GAME_NORMAL);
		}

		break;
	case GAME_RESET:	//リセット
		p_Player->Reset();			//プレイヤーのリセット
		p_Camera->ResetGame();		//カメラのリセット
		p_PlayerHpBar->Reset();
		p_BossHpBar->Reset();
		g_nStatus = GAME;
		break;
	case GAME:
		if(GetAsyncKeyState(VK_F12)&0x0001)
			g_CubeFlg ^= 1;
		p_Time->Update();
		p_Score->Update(p_Enemy->m_DeadCnt, p_Enemy->m_BossCnt);	//スコア
		p_Field->Update();			//地形
		p_Camera->GetVecCamera();	//カメラ
		p_Enemy->Update();			//エネミー
		p_Player->Update(p_Camera->vecx, p_Camera->vecz);	//プレイヤー
		p_Collision->Update();		//衝突判定
		p_Ambient->Update(p_Enemy->m_DeadCnt, p_Enemy->m_pEnemyBoss->m_AppearBoss);
		p_PlayerHpBar->Update(p_Player->m_Life, 100);	//プレイヤーのHPバー
		p_BossHpBar->Update(p_Enemy->m_pEnemyBoss->m_Life, 100);	//ボスのHPバー

		//ボスが生きていてL1が押された時Z注目をする
		if(pInput->GetBtnState(BTN_L1) == PRESS && p_Enemy->m_pEnemyBoss->m_Live)
		{
			p_Camera->SetOperatable(false);
		}
		//L1が離されたときは通常処理に戻す
		else if( pInput->GetBtnState(BTN_L1) == RLS )
		{
			p_Camera->SetOperatable(true);
		}

		if(pInput->GetBtnState(BTN_L2) == PRESS && pInput->GetBtnState(BTN_B) == PRESS )
		{
			p_Enemy->m_DeadCnt = 100; //デバグボス出現用
		}
		p_Camera->Update(p_Player->m_Pos, p_Enemy->m_pEnemyBoss->m_Pos);
		p_EffectMng->UpDate();
		
		{	
			//デバック表示用
			x = p_Player->m_Pos.x;
			y = p_Player->m_Pos.y;
			z = p_Player->m_Pos.z;
			num1 = p_Player->m_Matrix._11;
			num2 = (float)p_Enemy->m_pEnemyBoss->m_Life;
			//rad = p_Player->m_Matrix._13;
			//num3 = (float)p_Player->m_Life;
			num3 = p_PlayerHpBar->nM;
		}
		

		//結果
		if(p_Enemy->m_BossCnt)
			g_nStatus = GAME_FILLER_END;
		
		if(p_Player->m_bRetry)
			g_nStatus = GAME_FILLER_END;

#if (DEBUG_ON)
		//デバック用
		if(GetAsyncKeyState(VK_RETURN) & 0x0001)
			g_nStatus = GAME_FILLER_END;
#endif
		break;
	case GAME_FILLER_END:
			g_nStatus = RESULT_INIT;

		break;
	case RESULT_INIT:
		
		p_SE->StopBG(BG_GAME_BOSS);
		p_SE->PlayBG(BG_RESULT);
		p_Camera->ResetOp();		//カメラのリセット	OPと同じ
		p_Camera->SetOpCamera();	//カメラのセット
		
		p_Result->Init();
		g_nStatus = RESULT;
		break;
	case RESULT:
		if(p_Result->Update())
		{
			p_SE->StopBG(BG_RESULT);
			p_Result->Release();
			g_nStatus = MENU_INIT;
		}
		break;
	case ENDINIT:
			//g_nStatus = MENU_INIT;
		break;
	case END:
		p_SE->del();			//サウンドの開放
		DeCreateClass();		//クラスの解放
		g_bEnd = true;			//ゲーム終了
		return;
	default:break;
	}
	
	if(pInput != NULL)
	{
		pInput->Update();
		
		//プレゼン用
		if(pInput->GetBtnState(BTN_L1) == PRESS && pInput->GetBtnState(BTN_R1) == PRESS
		&& pInput->GetBtnState(BTN_L2) == PRESS && pInput->GetBtnState(BTN_R2) == PRESS)
		{
			p_SE->Reset();		//サウンドリセット
			g_nStatus = STARTINIT;
		}
	}
}