コード例 #1
0
ファイル: NotifyWnd.cpp プロジェクト: zcp0415/CloudDesktop
//纯文本式的右下角浮出窗口过程
LRESULT CALLBACK NotifyWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	LPNOTIFYWND_DATA pInfo = NULL;
	RECT rc;
	POINT pt;

	//这是一个广播消息
	if(message == g_NotifyInfo.nMsg_ExitNow)
	{
		pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);

		//通知主窗口退出(即客户端主程序退出)
		if(pInfo != NULL && pInfo->mode == MODE_TEXT)
			PostMessage(g_NotifyInfo.hWndMainFrm, WM_EXITNOW, 0, 0);
		return TRUE;
	}

	switch (message)
	{
	case WM_NCCREATE:
		{
			SIZE _size = { 0 };
			LPCREATESTRUCT pCreateStruct = (LPCREATESTRUCT)lParam;

			LPCTSTR pStr = _T("啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊");
			pInfo = (LPNOTIFYWND_DATA)malloc(sizeof(NOTIFYWND_DATA));
			memset(pInfo, 0, sizeof(NOTIFYWND_DATA));
		
			pInfo->mode = (int)(pCreateStruct->lpCreateParams);
			//创建内存位图和DC
			HDC hdc = GetDC(hWnd);
			pInfo->hMemDC = CreateCompatibleDC(hdc);
			HGDIOBJ hOldFont = SelectObject(pInfo->hMemDC, g_NotifyInfo.hFontContent);
			GetTextExtentPoint32(pInfo->hMemDC, pStr, _tcslen(pStr), &_size);
			pInfo->hMemBm = CreateCompatibleBitmap(hdc, _size.cx + g_NotifyInfo.imgSize + 48, 600);
			ReleaseDC(hWnd, hdc);

			SelectObject(pInfo->hMemDC, hOldFont);
			SelectObject(pInfo->hMemDC, pInfo->hMemBm);

			pInfo->contentWidth = _size.cx + g_NotifyInfo.gap;
			pInfo->titleHeight = _size.cy;

			pInfo->rcIcon.left = 3 + g_NotifyInfo.gap;
			pInfo->rcTitle.left = pInfo->rcIcon.left + g_NotifyInfo.iconSize + g_NotifyInfo.gap;
			pInfo->rcTitle.top = 3 + g_NotifyInfo.gap;
			pInfo->rcTitle.bottom = pInfo->rcTitle.top + pInfo->titleHeight;

			pInfo->rcIcon.top = (pInfo->rcTitle.top + pInfo->rcTitle.bottom - g_NotifyInfo.iconSize)/2;
			pInfo->rcIcon.right = pInfo->rcIcon.left + g_NotifyInfo.iconSize;
			pInfo->rcIcon.bottom = pInfo->rcIcon.top + g_NotifyInfo.iconSize;
			
			pInfo->rcContentOutter.left = 3;
			pInfo->rcContentOutter.top = pInfo->rcTitle.bottom + g_NotifyInfo.gap;

			pInfo->rcImg.left = pInfo->rcContentOutter.left + g_NotifyInfo.gap;
			pInfo->rcImg.top = pInfo->rcContentOutter.top + g_NotifyInfo.gap;
			pInfo->rcImg.right = pInfo->rcImg.left + g_NotifyInfo.imgSize;
			pInfo->rcImg.bottom = pInfo->rcImg.top + g_NotifyInfo.imgSize;			

			SetWindowPos(hWnd, HWND_TOPMOST, -10000, -10000, 
				pInfo->wndWidth, pInfo->wndHeight, SWP_HIDEWINDOW);

			pInfo->tme.cbSize = sizeof(TRACKMOUSEEVENT);
			pInfo->tme.dwFlags = TME_LEAVE; //我们需要 WM_MOUSELEAVE 消息;
			pInfo->tme.hwndTrack = hWnd;

			SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pInfo);
		}
		return TRUE;

	case WM_PAINT:
		{
			pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
			if(pInfo == NULL) return TRUE;

			PAINTSTRUCT ps;
			HDC hdc = BeginPaint(hWnd, &ps);

			BitBlt(hdc, 0, 0, pInfo->wndWidth, pInfo->wndHeight, pInfo->hMemDC, 0, 0, SRCCOPY);

			//绘制closebtn(有进度条时,不能关闭)
			int imgIndex = IMG_NORMAL;
			if(pInfo->bMouseOnClose)
			{
				imgIndex = (pInfo->bMouseDown && pInfo->bCloseBtnPushed)? IMG_PUSHED : IMG_HOVER;
			}
			g_NotifyInfo.pImgCloseBtns->TransparentBlt(hdc,
				pInfo->rcCloseBtn.left,
				pInfo->rcCloseBtn.top,
				g_NotifyInfo.closeBtnSize,
				g_NotifyInfo.closeBtnSize,
				imgIndex * g_NotifyInfo.closeBtnSize,
				0,
				g_NotifyInfo.closeBtnSize,
				g_NotifyInfo.closeBtnSize,
				RGB(255, 0, 255));
			EndPaint(hWnd, &ps);
		}
		return TRUE;

	case WM_ERASEBKGND:
		return TRUE;

	case WM_UPDATEPROGRESS:
		pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
		if(pInfo == NULL) return TRUE;
		
		if(pInfo->mode == MODE_PROGRESS)
		{
			LPCTSTR pStr = (LPCTSTR)lParam;
			if(pStr != NULL)
				_tcscpy_s(pInfo->szProgressText, _ARRAYSIZE(pInfo->szProgressText), pStr);
			pInfo->progress = (int)wParam;

			//绘制进度条
			HGDIOBJ hOldFont = SelectObject(pInfo->hMemDC, g_NotifyInfo.hFontContent);
			SetTextColor(pInfo->hMemDC, g_NotifyInfo.clrContent);
				
			FillRect(pInfo->hMemDC, &pInfo->rcProgressText, (HBRUSH)GetStockObject(WHITE_BRUSH));
			DrawText(pInfo->hMemDC, pInfo->szProgressText, -1,
				&pInfo->rcProgressText, DT_LEFT | DT_TOP | DT_SINGLELINE);

			SelectObject(pInfo->hMemDC, hOldFont);

			FillRect(pInfo->hMemDC, &pInfo->rcProgressBar, (HBRUSH)GetStockObject(WHITE_BRUSH));
			CopyRect(&rc, &pInfo->rcProgressBar);
			rc.right = pInfo->rcProgressBar.left + 
				(pInfo->rcProgressBar.right - pInfo->rcProgressBar.left) * pInfo->progress / 100;

			FillRect(pInfo->hMemDC, &rc, GetSysColorBrush(COLOR_ACTIVECAPTION)); //pInfo->hBrush);

			if(pInfo->progress >= 100)
			{
				//5 秒后自动隐藏
				pInfo->bDownloading = FALSE;
				SetTimer(hWnd, TIMERID_NOTIFY_HIDE, 2000, NULL);
			}
			UnionRect(&rc, &pInfo->rcProgressText, &pInfo->rcProgressBar);
			InvalidateRect(hWnd, &rc, FALSE);
		}
		return TRUE;

	case WM_MOUSEMOVE:
		{
			pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
			if(pInfo == NULL) return TRUE;

			pt.x = GET_X_LPARAM(lParam);
			pt.y = GET_Y_LPARAM(lParam);

			BOOL bTmp = PtInRect(&pInfo->rcCloseBtn, pt);
			if(bTmp != pInfo->bMouseOnClose)
			{
				pInfo->bMouseOnClose = bTmp;
				InvalidateRect(hWnd, &pInfo->rcCloseBtn, FALSE);
			}
			TrackMouseEvent(&pInfo->tme);
		}
		break;

	case WM_MOUSELEAVE:
		pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
		if(pInfo == NULL) return TRUE;
		if(pInfo->bMouseOnClose)
		{
			pInfo->bMouseOnClose = FALSE;
			InvalidateRect(hWnd, &pInfo->rcCloseBtn, FALSE);
		}
		break;

	case WM_LBUTTONDOWN:
		pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
		if(pInfo == NULL) return TRUE;

		pt.x = GET_X_LPARAM(lParam);
		pt.y = GET_Y_LPARAM(lParam);
		pInfo->bMouseDown = TRUE;

		if(PtInRect(&pInfo->rcCloseBtn, pt))
		{
			pInfo->bCloseBtnPushed = TRUE;
			InvalidateRect(hWnd, &pInfo->rcCloseBtn, FALSE);
			SetCapture(hWnd);
		}
		break;

	case WM_LBUTTONUP:
		pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
		if(pInfo == NULL) return TRUE;

		pt.x = GET_X_LPARAM(lParam);
		pt.y = GET_Y_LPARAM(lParam);
		pInfo->bMouseDown = FALSE;

		if(pInfo->bCloseBtnPushed)
		{
			pInfo->bCloseBtnPushed = FALSE;
			ReleaseCapture();
			if(PtInRect(&pInfo->rcCloseBtn, pt))
			{
				KillTimer(hWnd, TIMERID_NOTIFY_SHOWING);
				KillTimer(hWnd, TIMERID_NOTIFY_HIDING);
				KillTimer(hWnd, TIMERID_NOTIFY_TIMEOUT);
				KillTimer(hWnd, TIMERID_NOTIFY_HIDE);
				InvalidateRect(hWnd, &pInfo->rcCloseBtn, FALSE);
				//ShowWindow(hDlg, SW_HIDE);
				//用渐隐( AW_BLEND )的方式隐藏窗口,动画时间:200ms
				AnimateWindow(hWnd, 200, AW_HIDE | AW_BLEND);
			}
		}
		break;

	case WM_TIMER:
		pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
		if(pInfo == NULL) return TRUE;

		GetWindowRect(hWnd, &rc);
		switch(wParam)
		{
		case TIMERID_NOTIFY_SHOWING:
			if((rc.bottom - rc.top) >= (pInfo->wndHeight - g_NotifyInfo.dy))
			{
				KillTimer(hWnd, wParam);
				SetWindowPos(hWnd, NULL, rc.left, rc.bottom - pInfo->wndHeight,
					pInfo->wndWidth, pInfo->wndHeight, SWP_NOZORDER | SWP_NOACTIVATE);
			}
			else
			{
				SetWindowPos(hWnd, NULL, rc.left, rc.top - g_NotifyInfo.dy,
					pInfo->wndWidth, (rc.bottom - rc.top) + g_NotifyInfo.dy,
					SWP_NOZORDER | SWP_NOACTIVATE);
			}
			break;

		case TIMERID_NOTIFY_HIDING:
			{
				UINT flags = SWP_NOZORDER | SWP_NOACTIVATE;
				if((rc.bottom - rc.top) <= 0)
				{
					KillTimer(hWnd, wParam);
					flags = flags | SWP_HIDEWINDOW;
				}
				SetWindowPos(hWnd, NULL, rc.left, rc.top + g_NotifyInfo.dy,
					pInfo->wndWidth, rc.bottom - rc.top - g_NotifyInfo.dy,
					flags);
			}
			break;

		case TIMERID_NOTIFY_TIMEOUT:
			{
				KillTimer(hWnd, TIMERID_NOTIFY_SHOWING);
				KillTimer(hWnd, TIMERID_NOTIFY_TIMEOUT);
				KillTimer(hWnd, TIMERID_NOTIFY_HIDE);
				SetTimer(hWnd, TIMERID_NOTIFY_HIDING, INTERVAL_NOTIFYWND, NULL);
			}
			break;
		case TIMERID_NOTIFY_HIDE: //立即隐藏
			{
				KillTimer(hWnd, TIMERID_NOTIFY_SHOWING);
				KillTimer(hWnd, TIMERID_NOTIFY_HIDING);
				KillTimer(hWnd, TIMERID_NOTIFY_TIMEOUT);
				KillTimer(hWnd, TIMERID_NOTIFY_HIDE);
				AnimateWindow(hWnd, 200, AW_HIDE | AW_BLEND);
			}
			break;
		}
		break;

	case WM_POWERBROADCAST:
		{
			//TCHAR szText[256];
			//PBT_APMQUERYSUSPEND
			//_stprintf_s(szText, _ARRAYSIZE(szText), _T("NotifyWnd_PowerEvent: event = %x"), wParam);
			//WriteLogLine(szText);
			pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
			if(pInfo != NULL && pInfo->mode == MODE_TEXT)
				return SendMessage(g_NotifyInfo.hWndMainFrm, WM_POWERBROADCAST, wParam, lParam);
		}
		break;

	case WM_NCDESTROY:
		{
			pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
			if(pInfo == NULL) return TRUE;
			//DeleteCriticalSection(&g_NotifyInfo.cs);

			DeleteObject(pInfo->hMemBm);
			DeleteDC(pInfo->hMemDC);

			free(pInfo);

			SetWindowLongPtr(hWnd, GWLP_USERDATA, NULL);
		}
		break;

	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
コード例 #2
0
ファイル: Profile.cpp プロジェクト: YaoXuanZhi/win32-netmon
BOOL NetmonProfile::GetAutoStart(TCHAR *szAutoStart, int cchLen)
{
    _tcscpy_s(szAutoStart, cchLen, _szAutoStart);
    return TRUE;
}
コード例 #3
0
ファイル: Profile.cpp プロジェクト: YaoXuanZhi/win32-netmon
BOOL NetmonProfile::GetLanguage(TCHAR *szLanguage, int cchLen)
{
    _tcscpy_s(szLanguage, 64, _szLanguage);
    return TRUE;
}
コード例 #4
0
ファイル: java-lang.cpp プロジェクト: Kiskunsag/avian
extern "C" JNIEXPORT void JNICALL 
Java_java_lang_Runtime_exec(JNIEnv* e, jclass, 
                            jobjectArray command, jlongArray process)
{
#if !defined(WINAPI_FAMILY) || WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
  int size = 0;
  for (int i = 0; i < e->GetArrayLength(command); ++i){
    jstring element = (jstring) e->GetObjectArrayElement(command, i);
    size += e->GetStringUTFLength(element) + 1;
  } 
   
  RUNTIME_ARRAY(char, line, size);
  char* linep = RUNTIME_ARRAY_BODY(line);
  for (int i = 0; i < e->GetArrayLength(command); ++i) {
    if (i) *(linep++) = _T(' ');
    jstring element = (jstring) e->GetObjectArrayElement(command, i);
    const char* s =  e->GetStringUTFChars(element, 0);
#ifdef _MSC_VER
    _tcscpy_s(linep, size - (linep - RUNTIME_ARRAY_BODY(line)), s);
#else
    _tcscpy(linep, s);
#endif
    e->ReleaseStringUTFChars(element, s);
    linep += e->GetStringUTFLength(element);
  }
  *(linep++) = _T('\0');
 
  HANDLE in[] = { 0, 0 };
  HANDLE out[] = { 0, 0 };
  HANDLE err[] = { 0, 0 };
  
  makePipe(e, in);
  SetHandleInformation(in[0], HANDLE_FLAG_INHERIT, 0);
  jlong inDescriptor = static_cast<jlong>(descriptor(e, in[0]));
  if(e->ExceptionCheck()) return;
  e->SetLongArrayRegion(process, 2, 1, &inDescriptor);
  makePipe(e, out);
  SetHandleInformation(out[1], HANDLE_FLAG_INHERIT, 0);
  jlong outDescriptor = static_cast<jlong>(descriptor(e, out[1]));
  if(e->ExceptionCheck()) return;
  e->SetLongArrayRegion(process, 3, 1, &outDescriptor);
  makePipe(e, err);
  SetHandleInformation(err[0], HANDLE_FLAG_INHERIT, 0);
  jlong errDescriptor = static_cast<jlong>(descriptor(e, err[0]));
  if(e->ExceptionCheck()) return;
  e->SetLongArrayRegion(process, 4, 1, &errDescriptor);
  
  PROCESS_INFORMATION pi;
  ZeroMemory(&pi, sizeof(pi));
 
  STARTUPINFO si;
  ZeroMemory(&si, sizeof(si));
  si.cb = sizeof(si);
  si.dwFlags = STARTF_USESTDHANDLES;
  si.hStdOutput = in[1];
  si.hStdInput = out[0];
  si.hStdError = err[1];
 
  BOOL success = CreateProcess(0, (LPSTR) RUNTIME_ARRAY_BODY(line), 0, 0, 1,
                               CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
                               0, 0, &si, &pi);

  CloseHandle(in[1]);
  CloseHandle(out[0]);
  CloseHandle(err[1]);
  
  if (not success) {
    throwNew(e, "java/io/IOException", getErrorStr(GetLastError()));
    return;
  }
  
  jlong pid = reinterpret_cast<jlong>(pi.hProcess);
  e->SetLongArrayRegion(process, 0, 1, &pid);
  jlong tid = reinterpret_cast<jlong>(pi.hThread);  
  e->SetLongArrayRegion(process, 1, 1, &tid);
#else
  throwNew(e, "java/io/Exception", strdup("Not supported on WinRT/WinPhone8"));
#endif
}
コード例 #5
0
void 
addXdata() 
{
    AcDbObject* pObj = selectObject(AcDb::kForRead);
    if (!pObj) {
        acutPrintf(_T("Error selecting object\n"));
        return;
    }

    
    // Get the application name and string to be added to
    // xdata.
    //
    TCHAR appName[132], resString[200];
    appName[0] = resString[0] = _T('\0');

    acedGetString(NULL, _T("Enter application name: "),
        appName);
    acedGetString(NULL, _T("Enter string to be added: "),
        resString);

    
    struct  resbuf  *pRb, *pTemp;
    
    pRb = pObj->xData(appName);

    if (pRb != NULL) {

        // If xdata is present, then walk to the
        // end of the list.
        //
        for (pTemp = pRb; pTemp->rbnext != NULL;
                pTemp = pTemp->rbnext)
                { ; }
    } else {
        // If xdata is not present, register the application
        // and add appName to the first resbuf in the list.
        // Notice that there is no -3 group as there is in
        // AutoLISP. This is ONLY the xdata so
        // the -3 xdata-start marker isn't needed.
        // 
        acdbRegApp(appName);

        pRb = acutNewRb(AcDb::kDxfRegAppName);
        pTemp = pRb;
        const size_t nSize = _tcslen(appName) + 1;
        pTemp->resval.rstring
            = (TCHAR*) malloc(nSize * sizeof(TCHAR));
        errno_t err = _tcscpy_s(pTemp->resval.rstring, nSize, appName);
        assert(err == 0);
    }

    // Add user-specified string to the xdata.
    //
    pTemp->rbnext = acutNewRb(AcDb::kDxfXdAsciiString);
    pTemp = pTemp->rbnext;
    const size_t nSize = _tcslen(resString) + 1;
    pTemp->resval.rstring
        = (TCHAR*) malloc(nSize * sizeof(TCHAR));
    errno_t err = _tcscpy_s(pTemp->resval.rstring, nSize, resString);
    assert(err == 0);

    // The following code shows the use of upgradeOpen()
    // to change the entity from read to write.
    //
    pObj->upgradeOpen();
    pObj->setXData(pRb);
    
    pObj->close();
    acutRelRb(pRb);
}
コード例 #6
0
ファイル: TabAES256Dlg.cpp プロジェクト: CoterJiesen/winaes
void CTabAES256Dlg::OnBnClickedBtnAdd()
{

	UINT _curStrLen;
	UINT64 _curFileLen;
	
	UCHAR _cOneFile = 1;

	TCHAR *_lpszInPath = new TCHAR[262144];
	TCHAR *_pathDir = new TCHAR[512];
	TCHAR *_curFilePath = new TCHAR[512];
	TCHAR *_curFileName = new TCHAR[128];
	TCHAR *_curFileLenStr = new TCHAR[128];


	//declare _lp_in_fn and initialize
	LPOPENFILENAME _lp_in_fn;
	_lp_in_fn = new OPENFILENAME;
	memset(_lp_in_fn, 0, sizeof(OPENFILENAME));

	_lp_in_fn->lStructSize = sizeof(OPENFILENAME);
	_lp_in_fn->hwndOwner = this->m_hWnd;
	_lp_in_fn->lpstrFilter = _T("All Files(*.*)\0*.*\0");
	
	_lp_in_fn->lpstrFile = _lpszInPath;
	_lp_in_fn->lpstrFile[0] = _T('\0');
	_lp_in_fn->nMaxFile = 262144;

	_lp_in_fn->lpstrFileTitle = NULL;
	_lp_in_fn->nMaxFileTitle = 0;

	_lp_in_fn->Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER | OFN_ALLOWMULTISELECT;

	if(GetOpenFileName(_lp_in_fn)){

		//Save Base Path
		_tcscpy_s(_pathDir, 512, _lpszInPath);

		UINT _lastFNPos = 0;
		UINT _curFnPos = 0;
		
		while(1)
		{
			if(!_lpszInPath[_curFnPos]){
				if(_curFnPos == _lastFNPos){break;}
				if(_lastFNPos){
					//more than 1 file
					_cOneFile = 0;

					//copy filename
					_tcscpy_s(_curFileName, 128, &_lpszInPath[_lastFNPos]);
					
					//copy base path
					_tcscpy_s(_curFilePath, 512, _pathDir);
					
					//append "\"
					_curStrLen = (UINT)_tcslen(_curFilePath);
					if(_curFilePath[_curStrLen - 1] != 0x5c){
						_curFilePath[_curStrLen + 1] = 0x00;
						_curFilePath[_curStrLen] = 0x5c;
					}

					//append filename
					_tcscat_s(_curFilePath, 512, _curFileName);

					//allocate mem & copy full path
					this->_inFilePath[this->_iFileIndex] = new TCHAR[512];
					_tcscpy_s(_inFilePath[this->_iFileIndex], 512, _curFilePath);

					if(this->_GetFileLen(_curFilePath, &_curFileLen)){
						_stprintf_s(_curFileLenStr, 128, _T("%lld KB"), (_curFileLen / 1024));
					}else{
						_stprintf_s(_curFileLenStr, 128, _T("Open Failed"));
					}

					//add to list
					this->_AddToList(this->_iFileIndex++, _curFilePath, _curFileLenStr, _T("Ready"));
				}
				_lastFNPos = _curFnPos + 1;
			}//Zero
			_curFnPos++;
		}//while

		if (_cOneFile){
			//allocate mem & copy full path
			this->_inFilePath[0] = new TCHAR[512];
			_tcscpy_s(_inFilePath[0], 512, _pathDir);

			if(this->_GetFileLen(_inFilePath[0], &_curFileLen)){
				_stprintf_s(_curFileLenStr, 128, _T("%lld KB"), (_curFileLen / 1024));
			}else{
				_stprintf_s(_curFileLenStr, 128, _T("Open Failed"));
			}
			this->_AddToList(this->_iFileIndex++, _inFilePath[0], _curFileLenStr, _T("Ready"));
		}
	}

	free(_lp_in_fn);
	free(_lpszInPath);
	free(_pathDir);
	free(_curFilePath);
	free(_curFileName);
	free(_curFileLenStr);

}
コード例 #7
0
ファイル: DisplayClassInfo.c プロジェクト: RaMMicHaeL/winspy
//
//  Set the class information on the Class Tab, for the specified window.
//  This function assumes that spy_WndClassEx is completely populated.
//
void SetClassInfo(HWND hwnd)
{
	TCHAR ach[256];

	int i, numstyles, classbytes;
	HWND hwndDlg = WinSpyTab[CLASS_TAB].hwnd;
	UINT_PTR handle;

	*ach = 0;

	if (hwnd)
	{
		GetClassName(hwnd, ach, ARRAYSIZE(ach));

		// be nice and give the proper name for the following class names
		//
		VerboseClassName(ach, ARRAYSIZE(ach), (WORD)GetClassLong(hwnd, GCW_ATOM));
	}

	SetDlgItemText(hwndDlg, IDC_CLASSNAME, ach);

	//class style
	if (hwnd)
	{
		_stprintf_s(ach, ARRAYSIZE(ach), szHexFmt, spy_WndClassEx.style);
	}
	SetDlgItemText(hwndDlg, IDC_STYLE, ach);

	//atom
	if (hwnd)
	{
		_stprintf_s(ach, ARRAYSIZE(ach), _T("%04X"), GetClassLong(hwnd, GCW_ATOM));
	}
	SetDlgItemText(hwndDlg, IDC_ATOM, ach);

	//extra class bytes
	if (hwnd)
	{
		_stprintf_s(ach, ARRAYSIZE(ach), _T("%d"), spy_WndClassEx.cbClsExtra);
	}
	SetDlgItemText(hwndDlg, IDC_CLASSBYTES, ach);

	//extra window bytes
	if (hwnd)
	{
		_stprintf_s(ach, ARRAYSIZE(ach), _T("%d"), spy_WndClassEx.cbWndExtra);
	}
	SetDlgItemText(hwndDlg, IDC_WINDOWBYTES, ach);

	//menu (not implemented)
	if (hwnd)
	{
		_stprintf_s(ach, ARRAYSIZE(ach), szPtrFmt, (void*)GetClassLongPtr(hwnd, GCLP_MENUNAME));
	}
	SetDlgItemText(hwndDlg, IDC_MENUHANDLE, _T("(None)"));

	//cursor handle
	if (hwnd)
	{
		handle = GetClassLongPtr(hwnd, GCLP_HCURSOR);
		FormatHandle(ach, ARRAYSIZE(ach), CursorLookup, NUM_CURSOR_LOOKUP, handle);
	}
	SetDlgItemText(hwndDlg, IDC_CURSORHANDLE, ach);

	//icon handle
	if (hwnd)
	{
		handle = GetClassLongPtr(hwnd, GCLP_HICON);
		FormatHandle(ach, ARRAYSIZE(ach), IconLookup, NUM_ICON_LOOKUP, handle);
	}
	SetDlgItemText(hwndDlg, IDC_ICONHANDLE, ach);

	//background brush handle
	if (hwnd)
	{
		handle = GetClassLongPtr(hwnd, GCLP_HBRBACKGROUND);

		//see hbrBackground description at https://msdn.microsoft.com/en-us/library/windows/desktop/ms633577.aspx
		//first of all, search by COLOR_xxx value
		if (!(handle > 0 && handle <= MAXUINT) || (-1 == FormatConst(ach, ARRAYSIZE(ach), BrushLookup, NUM_BRUSH_STYLES, (UINT)handle - 1)))
		{
			//now search by handle value
			i = FormatHandle(ach, ARRAYSIZE(ach), BrushLookup2, NUM_BRUSH2_LOOKUP, handle);
			if (i != -1)
			{
				int len = PrintHandle(ach, ARRAYSIZE(ach), (UINT_PTR)BrushLookup2[i].handle);
				_stprintf_s(ach + len, ARRAYSIZE(ach) - len, _T("  (%s)"), BrushLookup2[i].szName);
			}
		}
	}

	//set the brush handle text
	SetDlgItemText(hwndDlg, IDC_BKGNDBRUSH, ach);

	//window procedure
	if (hwnd)
	{
		if (spy_WndProc == 0)
		{
			_tcscpy_s(ach, ARRAYSIZE(ach), _T("N/A"));
		}
		else
		{
			_stprintf_s(ach, ARRAYSIZE(ach), szPtrFmt, spy_WndProc);
			if (spy_WndProc != spy_WndClassEx.lpfnWndProc)
				_tcscat_s(ach, ARRAYSIZE(ach), _T(" (Subclassed)"));
		}
	}

	SetDlgItemText(hwndDlg, IDC_WNDPROC, ach);

	SetDlgItemText(WinSpyTab[GENERAL_TAB].hwnd, IDC_WINDOWPROC2, ach);

	//class window procedure
	if (hwnd)
	{
		if (spy_WndClassEx.lpfnWndProc == 0)
			_tcscpy_s(ach, ARRAYSIZE(ach), _T("N/A"));
		else
			_stprintf_s(ach, ARRAYSIZE(ach), szPtrFmt, spy_WndClassEx.lpfnWndProc);
	}

	SetDlgItemText(hwndDlg, IDC_CLASSPROC, ach);


	//instance handle
	if (hwnd)
	{
		_stprintf_s(ach, ARRAYSIZE(ach), szPtrFmt, spy_WndClassEx.hInstance);
	}
	SetDlgItemText(hwndDlg, IDC_INSTANCEHANDLE, ach);

	//
	// fill the combo box with the class styles
	//
	numstyles = 0;
	SendDlgItemMessage(hwndDlg, IDC_STYLELIST, CB_RESETCONTENT, 0, 0);
	if (hwnd)
	{
		for (i = 0; i < NUM_CLASS_STYLES; i++)
		{
			if (spy_WndClassEx.style & ClassLookup[i].value)
			{
				SendDlgItemMessage(hwndDlg, IDC_STYLELIST, CB_ADDSTRING, 0,
					(LPARAM)ClassLookup[i].szName);

				numstyles++;
			}
		}
	}

	SendDlgItemMessage(hwndDlg, IDC_STYLELIST, CB_SETCURSEL, 0, 0);
	EnableDlgItem(hwndDlg, IDC_STYLELIST, numstyles != 0);

	//
	// fill combo box with class extra bytes
	//
	classbytes = spy_WndClassEx.cbClsExtra;

	FillBytesList(hwndDlg, hwnd, classbytes, GetClassWord, GetClassLong, GetClassLongPtr);
}
コード例 #8
0
ファイル: avifile.cpp プロジェクト: BuckeyeDude/Wabbitemu
HRESULT CAviFile::InitMovieCreation(int nFrameWidth, int nFrameHeight, WORD nBitsPerPixel)
{
	int	nMaxWidth=GetSystemMetrics(SM_CXSCREEN),nMaxHeight=GetSystemMetrics(SM_CYSCREEN);

	m_hAviDC = CreateCompatibleDC(NULL);
	if(m_hAviDC==NULL)	
	{
		SetErrorMessage(_T("Unable to Create Compatible DC"));
		return E_FAIL;
	}
	
	if(nFrameWidth > nMaxWidth)	nMaxWidth= nFrameWidth;
	if(nFrameHeight > nMaxHeight)	nMaxHeight = nFrameHeight;

	m_hHeap=HeapCreate(HEAP_NO_SERIALIZE, nMaxWidth*nMaxHeight*4, 0);
	if(m_hHeap==NULL)
	{
		SetErrorMessage(_T("Unable to Create Heap"));
		return E_FAIL;
	}
	
	m_lpBits=HeapAlloc(m_hHeap, HEAP_ZERO_MEMORY|HEAP_NO_SERIALIZE, nMaxWidth*nMaxHeight*4);
	if(m_lpBits==NULL)	
	{	
		SetErrorMessage(_T("Unable to Allocate Memory on Heap"));
		return E_FAIL;
	}

	if(FAILED(AVIFileOpen(&m_pAviFile, m_szFileName, OF_CREATE|OF_WRITE, NULL)))
	{
		SetErrorMessage(_T("Unable to Create the Movie File"));
		return E_FAIL;
	}

	ZeroMemory(&m_AviStreamInfo,sizeof(AVISTREAMINFO));
	m_AviStreamInfo.fccType		= streamtypeVIDEO;
	m_AviStreamInfo.fccHandler	= m_dwFCCHandler;
	m_AviStreamInfo.dwScale		= 1;
	m_AviStreamInfo.dwRate		= m_dwFrameRate;	// Frames Per Second;
	m_AviStreamInfo.dwQuality	= m_dwQuality;		// Quality
	m_AviStreamInfo.dwSuggestedBufferSize = nMaxWidth*nMaxHeight*4;
	SetRect(&m_AviStreamInfo.rcFrame, 0, 0, nFrameWidth, nFrameHeight);
	_tcscpy_s(m_AviStreamInfo.szName, _T("Video Stream"));

	if(FAILED(AVIFileCreateStream(m_pAviFile,&m_pAviStream,&m_AviStreamInfo)))
	{
		SetErrorMessage(_T("Unable to Create Video Stream in the Movie File"));
		return E_FAIL;
	}

	ZeroMemory(&m_AviCompressOptions,sizeof(AVICOMPRESSOPTIONS));
	m_AviCompressOptions.fccType=streamtypeVIDEO;
	m_AviCompressOptions.fccHandler=m_AviStreamInfo.fccHandler;
	m_AviCompressOptions.dwFlags=AVICOMPRESSF_KEYFRAMES|AVICOMPRESSF_VALID;//|AVICOMPRESSF_DATARATE;
	m_AviCompressOptions.dwKeyFrameEvery=1;
	//m_AviCompressOptions.dwBytesPerSecond=1000/8;
	//m_AviCompressOptions.dwQuality=100;

	if(FAILED(AVIMakeCompressedStream(&m_pAviCompressedStream,m_pAviStream,&m_AviCompressOptions,NULL)))
	{
		// One reason this error might occur is if you are using a Codec that is not 
		// available on your system. Check the mmioFOURCC() code you are using and make
		// sure you have that codec installed properly on your machine.
		SetErrorMessage(_T("Unable to Create Compressed Stream: Check your CODEC options"));
		return E_FAIL;
	}

	BITMAPINFO bmpInfo;
	ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
	bmpInfo.bmiHeader.biPlanes		= 1;
	bmpInfo.bmiHeader.biWidth		= nFrameWidth;
	bmpInfo.bmiHeader.biHeight		= nFrameHeight;
	bmpInfo.bmiHeader.biCompression	= BI_RGB;
	bmpInfo.bmiHeader.biBitCount	= nBitsPerPixel;
	bmpInfo.bmiHeader.biSize		= sizeof(BITMAPINFOHEADER);
	bmpInfo.bmiHeader.biSizeImage = bmpInfo.bmiHeader.biWidth*bmpInfo.bmiHeader.biHeight*bmpInfo.bmiHeader.biBitCount / 8;

	if(FAILED(AVIStreamSetFormat(m_pAviCompressedStream,0,(LPVOID)&bmpInfo, bmpInfo.bmiHeader.biSize)))
	{
		// One reason this error might occur is if your bitmap does not meet the Codec requirements.
		// For example, 
		//   your bitmap is 32bpp while the Codec supports only 16 or 24 bpp; Or
		//   your bitmap is 274 * 258 size, while the Codec supports only sizes that are powers of 2; etc...
		// Possible solution to avoid this is: make your bitmap suit the codec requirements,
		// or Choose a codec that is suitable for your bitmap.
		SetErrorMessage(_T("Unable to Set Video Stream Format"));
		return E_FAIL;
	}

	return S_OK;	// Everything went Fine
}
コード例 #9
0
ファイル: broker.cpp プロジェクト: digital-carver/ancho
//----------------------------------------------------------------------
// inject the dll sDllFilename in target process
LRESULT InjectDll(DWORD aProcessId)
{
  if (!aProcessId) {
    return ERROR_INVALID_HANDLE;
  }

  // request debug privileges for writing process memory
  if( !DebugPrivileges( TRUE ) ) {
    return ::GetLastError();
  }

  CHandle process(::OpenProcess( PROCESS_ALL_ACCESS, FALSE, aProcessId ));
  if( !process ) {
    return ::GetLastError();
  }

  // format dll filename
  TCHAR path[ MAX_PATH ] = {0};
  if( !::GetModuleFileName( NULL, path, MAX_PATH ) ) {
    return ::GetLastError();
  }

  TCHAR* sp = _tcsrchr( path, L'\\' ) + 1;
  _tcscpy_s( sp, path + MAX_PATH - sp, sDllFilename );

  // allocate memory for filename
  LPVOID address = ::VirtualAllocEx( process, NULL, sizeof( path ),
      MEM_COMMIT, PAGE_READWRITE );
  if( !address ) {
    return ::GetLastError();
  }

  // NOTE: From here on address has to be VirtualFreeEx'd, so don't return here!
  LRESULT ret = 0;
  // and write filename
  if( ::WriteProcessMemory( process, address, path, sizeof( path ), NULL ) ) {
    // if it worked, create remote thread with LoadLibrary
#ifdef UNICODE
    CHandle thread(::CreateRemoteThread( process, NULL, 0,
        (LPTHREAD_START_ROUTINE)::GetProcAddress( ::GetModuleHandle( L"Kernel32" ),
          "LoadLibraryW" ),
        address, 0, NULL ));
#else
    CHandle thread(::CreateRemoteThread( process, NULL, 0,
        (LPTHREAD_START_ROUTINE)::GetProcAddress( ::GetModuleHandle( L"Kernel32" ),
          "LoadLibraryA" ),
        address, 0, NULL ));
#endif
    if( thread ) {
      ::WaitForSingleObject( thread, INFINITE );
      thread.Close();
    }
    else {
      ret = ::GetLastError();
    }
  }
  else {
    ret = ::GetLastError();
  }
  ::VirtualFreeEx( process, address, sizeof( path ), MEM_RELEASE );

  process.Close();
  DebugPrivileges( FALSE );

  return ret;
}
コード例 #10
0
BOOL CResolveDlg::Execute(LPSTR a_szCmdLine, LPVOID a_lpEnvironment, LPTSTR *r_szReturn, BOOL abAllowOutput)
{
    HANDLE hReadPipe, hWritePipe;
    SECURITY_ATTRIBUTES saAttr;
    memset(&saAttr,0,sizeof(saAttr));
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
    saAttr.bInheritHandle = TRUE;
    saAttr.lpSecurityDescriptor = NULL;
    ::CreatePipe(&hReadPipe, &hWritePipe, &saAttr, 0);

    ::SetEnvironmentVariableA("PATH",gsPath);

    DWORD dwLastError;
    BOOL bCreate;
    STARTUPINFOA si;
    memset(&si,0,sizeof(si));
    si.cb = sizeof(si);
    PROCESS_INFORMATION pi;
    memset(&pi,0,sizeof(pi));

    si.hStdError = hWritePipe;
    si.hStdOutput = hWritePipe;
    si.hStdInput = hReadPipe;
    if (!abAllowOutput)
        si.dwFlags = STARTF_USESTDHANDLES;

    bCreate = ::CreateProcessA(NULL,a_szCmdLine,NULL,NULL,TRUE,
                               NORMAL_PRIORITY_CLASS|(abAllowOutput ? 0 : DETACHED_PROCESS), NULL,
                               NULL, &si, &pi);
    dwLastError = ::GetLastError();

    if (!bCreate)
    {
        CloseHandle(hWritePipe);
        CloseHandle(hReadPipe);
        int nMaxLen = lstrlenA(a_szCmdLine)+100;
        *r_szReturn = (TCHAR*)calloc(nMaxLen,sizeof(TCHAR));
        _tcscpy_s(*r_szReturn, nMaxLen, _T("Command executing failed:\n"));
#ifdef _UNICODE
        MultiByteToWideChar(CP_OEMCP, 0, a_szCmdLine, -1, ((*r_szReturn)+lstrlenW(*r_szReturn)), strlen(a_szCmdLine)+1);
#else
        _tcscat(*r_szReturn, a_szCmdLine);
#endif
        return FALSE;
    }

    // Ожидание завершения
    DWORD dw = -1;
    ::WaitForSingleObject(pi.hProcess, INFINITE);
    ::GetExitCodeProcess(pi.hProcess,&dw);

    CloseHandle(hWritePipe);
    DWORD dwRead, dwAll=0;
    char szBuffer[4096];
    std::vector<char*> szReads;

    for (;;)
    {
        if (!ReadFile(hReadPipe, szBuffer, 4095, &dwRead, NULL) ||
                dwRead==0) break;
        szBuffer[dwRead] = '\0';
        dwAll += dwRead;
        //r_szReturn += szBuffer;
        char* psz = NULL;
        while ((psz = strstr(szBuffer, "\r\n"))!=NULL) *psz = ' ';
        szReads.push_back(_strdup(szBuffer));
    }
    CloseHandle(hReadPipe);

    if (dw!=0)
    {
        int nCmdLen = lstrlenA(a_szCmdLine);
        *r_szReturn = (TCHAR*)calloc(dwAll+nCmdLen+128, sizeof(TCHAR));
        TCHAR *pszDst = *r_szReturn;
        wsprintf(pszDst, _T("%s\nCommand executing failed: 0x%08X\n"), _T("CPP Resolve"), dw);
        pszDst += _tcslen(pszDst);
        //_tcscpy_s(pszDst, dwAll+100, _T("Command executing failed:\n")); pszDst += _tcslen(pszDst);
#ifdef _UNICODE
        MultiByteToWideChar(CP_OEMCP, 0, a_szCmdLine, -1, pszDst, nCmdLen+1);
#else
        _tcscpy_s(pszDst, nCmdLen+1, a_szCmdLine);
#endif
        pszDst += lstrlenW(pszDst);
        *(pszDst++) = _T('\n');
        *pszDst = 0;

        for (UINT i=0; i<szReads.size(); i++)
        {
            char* psz = szReads[i];
#ifdef _UNICODE
            MultiByteToWideChar(CP_OEMCP, 0, psz, -1, pszDst, dwAll);
#else
            strcpy(pszDst, ("Command executing failed:\n"));
#endif
            pszDst += _tcslen(pszDst);
        }

        return FALSE;
    }

    for (UINT i=0; i<szReads.size(); i++)
    {
        char* psz = szReads[i];
        free(psz);
    }

    return TRUE;
}
コード例 #11
0
ファイル: SysInfo.cpp プロジェクト: jiangguang5201314/ZNginx
void ShowCPUInfo(HWND hWnd, WORD wProcessorArchitecture, WORD wProcessorLevel,
                 WORD wProcessorRevision)
{

    TCHAR szCPUArch[64]  = TEXT("(unknown)");
    TCHAR szCPULevel[64] = TEXT("(unknown)");
    TCHAR szCPURev[64]   = TEXT("(unknown)");

    switch (wProcessorArchitecture)
    {
    // Notice that AMD processors are seen as PROCESSOR_ARCHITECTURE_INTEL.
    // In the Registry, the content of the "VendorIdentifier" key under
    // HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0
    // is either "GenuineIntel" or "AuthenticAMD"
    //
    // Read http://download.intel.com/design/Xeon/applnots/24161831.pdf
    // for Model numeric codes.
    // http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/20734.pdf
    // should be used for AMD processors Model numeric codes.
    //
    case PROCESSOR_ARCHITECTURE_INTEL:
        _tcscpy_s(szCPUArch, _countof(szCPUArch), TEXT("Intel"));
        switch (wProcessorLevel)
        {
        case 3:
        case 4:
            StringCchPrintf(szCPULevel, _countof(szCPULevel), TEXT("80%c86"), wProcessorLevel + '0');
            StringCchPrintf(szCPURev, _countof(szCPURev), TEXT("%c%d"),
                            HIBYTE(wProcessorRevision) + TEXT('A'),
                            LOBYTE(wProcessorRevision));
            break;

        case 5:
            _tcscpy_s(szCPULevel, _countof(szCPULevel), TEXT("Pentium"));
            StringCchPrintf(szCPURev, _countof(szCPURev), TEXT("Model %d, Stepping %d"),
                            HIBYTE(wProcessorRevision), LOBYTE(wProcessorRevision));
            break;

        case 6:
            switch (HIBYTE(wProcessorRevision))   // Model
            {
            case 1:
                _tcscpy_s(szCPULevel, _countof(szCPULevel),
                          TEXT("Pentium Pro"));
                break;

            case 3:
            case 5:
                _tcscpy_s(szCPULevel, _countof(szCPULevel),
                          TEXT("Pentium II"));
                break;

            case 6:
                _tcscpy_s(szCPULevel, _countof(szCPULevel),
                          TEXT("Celeron"));
                break;

            case 7:
            case 8:
            case 11:
                _tcscpy_s(szCPULevel, _countof(szCPULevel),
                          TEXT("Pentium III"));
                break;

            case 9:
            case 13:
                _tcscpy_s(szCPULevel, _countof(szCPULevel),
                          TEXT("Pentium M"));
                break;

            case 10:
                _tcscpy_s(szCPULevel, _countof(szCPULevel),
                          TEXT("Pentium Xeon"));
                break;

            case 15:
                _tcscpy_s(szCPULevel, _countof(szCPULevel),
                          TEXT("Core 2 Duo"));
                break;

            default:
                _tcscpy_s(szCPULevel, _countof(szCPULevel),
                          TEXT("Unknown Pentium"));
                break;
            }
            StringCchPrintf(szCPURev, _countof(szCPURev), TEXT("Model %d, Stepping %d"),
                            HIBYTE(wProcessorRevision), LOBYTE(wProcessorRevision));
            break;

        case 15:
            _tcscpy_s(szCPULevel, _countof(szCPULevel), TEXT("Pentium 4"));
            StringCchPrintf(szCPURev, _countof(szCPURev), TEXT("Model %d, Stepping %d"),
                            HIBYTE(wProcessorRevision), LOBYTE(wProcessorRevision));
            break;
        }
        break;

    case PROCESSOR_ARCHITECTURE_IA64:
        _tcscpy_s(szCPUArch, _countof(szCPUArch), TEXT("IA-64"));
        StringCchPrintf(szCPULevel, _countof(szCPULevel), TEXT("%d"), wProcessorLevel);
        StringCchPrintf(szCPURev, _countof(szCPURev), TEXT("Model %c, Pass %d"),
                        HIBYTE(wProcessorRevision) + TEXT('A'),
                        LOBYTE(wProcessorRevision));
        break;

    case PROCESSOR_ARCHITECTURE_AMD64:
        _tcscpy_s(szCPUArch, _countof(szCPUArch), TEXT("AMD64"));
        StringCchPrintf(szCPULevel, _countof(szCPULevel), TEXT("%d"), wProcessorLevel);
        StringCchPrintf(szCPURev, _countof(szCPURev), TEXT("Model %c, Pass %d"),
                        HIBYTE(wProcessorRevision) + TEXT('A'),
                        LOBYTE(wProcessorRevision));
        break;


    case PROCESSOR_ARCHITECTURE_UNKNOWN:
    default:
        _tcscpy_s(szCPUArch, _countof(szCPUArch), TEXT("Unknown"));
        break;
    }
    SetDlgItemText(hWnd, IDC_PROCARCH,  szCPUArch);
    SetDlgItemText(hWnd, IDC_PROCLEVEL, szCPULevel);
    SetDlgItemText(hWnd, IDC_PROCREV,   szCPURev);
}
コード例 #12
0
void CSVNStatusCache::Create()
{
	ATLASSERT(m_pInstance == NULL);
    if (m_pInstance != NULL)
        return;

	m_pInstance = new CSVNStatusCache;

	m_pInstance->watcher.SetFolderCrawler(&m_pInstance->m_folderCrawler);
#define LOADVALUEFROMFILE(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto exit;
#define LOADVALUEFROMFILE2(x) if (fread(&x, sizeof(x), 1, pFile)!=1) goto error;
	unsigned int value = (unsigned int)-1;
	FILE * pFile = NULL;
	// find the location of the cache
	TCHAR path[MAX_PATH];		//MAX_PATH ok here.
	TCHAR path2[MAX_PATH];
	if (SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, path)==S_OK)
	{
		_tcscat_s(path, MAX_PATH, _T("\\TSVNCache"));
		if (!PathIsDirectory(path))
		{
			if (CreateDirectory(path, NULL)==0)
				goto error;
		}
		_tcscat_s(path, MAX_PATH, STATUSCACHEFILENAME);
		// in case the cache file is corrupt, we could crash while
		// reading it! To prevent crashing every time once that happens,
		// we make a copy of the cache file and use that copy to read from.
		// if that copy is corrupt, the original file won't exist anymore
		// and the second time we start up and try to read the file,
		// it's not there anymore and we start from scratch without a crash.
		_tcscpy_s(path2, MAX_PATH, path);
		_tcscat_s(path2, MAX_PATH, _T("2"));
		DeleteFile(path2);
		CopyFile(path, path2, FALSE);
		DeleteFile(path);
		pFile = _tfsopen(path2, _T("rb"), _SH_DENYNO);
		if (pFile)
		{
			try
			{
				LOADVALUEFROMFILE(value);
				if (value != CACHEDISKVERSION)
				{
					goto error;
				}
				int mapsize = 0;
				LOADVALUEFROMFILE(mapsize);
				for (int i=0; i<mapsize; ++i)
				{
					LOADVALUEFROMFILE2(value);	
					if (value > MAX_PATH)
						goto error;
					if (value)
					{
						CString sKey;
						if (fread(sKey.GetBuffer(value+1), sizeof(TCHAR), value, pFile)!=value)
						{
							sKey.ReleaseBuffer(0);
							goto error;
						}
						sKey.ReleaseBuffer(value);
                        std::auto_ptr<CCachedDirectory> cacheddir (new CCachedDirectory());
						if (!cacheddir.get() || !cacheddir->LoadFromDisk(pFile))
						{
                            cacheddir.reset();
							goto error;
						}
						CTSVNPath KeyPath = CTSVNPath(sKey);
						if (m_pInstance->IsPathAllowed(KeyPath))
						{
							// only add the path to the watch list if it is versioned
							if ((cacheddir->GetCurrentFullStatus() != svn_wc_status_unversioned)&&(cacheddir->GetCurrentFullStatus() != svn_wc_status_none))
								m_pInstance->watcher.AddPath(KeyPath, false);

                            m_pInstance->m_directoryCache[KeyPath] = cacheddir.release();

                            // do *not* add the paths for crawling!
							// because crawled paths will trigger a shell
							// notification, which makes the desktop flash constantly
							// until the whole first time crawling is over
							// m_pInstance->AddFolderForCrawling(KeyPath);
						}
					}
				}
			}
			catch (CAtlException)
			{
				goto error;
			}
		}
	}
exit:
	if (pFile)
		fclose(pFile);
	DeleteFile(path2);
	m_pInstance->watcher.ClearInfoMap();
	ATLTRACE("cache loaded from disk successfully!\n");
	return;
error:
	fclose(pFile);
	DeleteFile(path2);
	m_pInstance->watcher.ClearInfoMap();
	if (m_pInstance)
	{
		m_pInstance->Stop();
		Sleep(100);
	}
	delete m_pInstance;
	m_pInstance = new CSVNStatusCache;
	ATLTRACE("cache not loaded from disk\n");
}
コード例 #13
0
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND  - process the application menu
//  WM_PAINT    - Paint the main window
//  WM_DESTROY  - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{\
	switch (message)
	{
	case WM_COMMAND:
	{
		int wmId = LOWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_FILE_OPEN: {
			TCHAR path[MAX_PATH];
			if (OpenFileDialog(hWnd, path, _T("Pri File (*.pri)\0*.pri\0*.*\0*.*\0\0"))) {
				TCHAR* name = _tcsrchr(path, _T('\\')) + 1;
				_tcscpy_s(pAppendTitle, MAX_PATH + szTitle - pAppendTitle, _T(" - "));
				_tcscat_s(pAppendTitle, MAX_PATH + szTitle - pAppendTitle, name);
				SetWindowText(hWnd, szTitle);

				if (pLoader) delete pLoader;
				pLoader = new PriFileLoader(path);

				if (pChanger) delete pChanger;
				pChanger = new PriChanger(pLoader->getPriEntry());

				if (pImage) {
					delete pImage;
					pImage = NULL;
				}

				BYTE* pBuffer = reinterpret_cast<BYTE*>(GlobalLock(hGlobal));
				pLoader->getDataByIndex(pBuffer, MAP_BUFFER_SIZE, 3);
				GlobalUnlock(hGlobal);
				IStream* pStream = NULL;
				if (CreateStreamOnHGlobal(hGlobal, FALSE, &pStream) == S_OK) {
					pImage = Gdiplus::Image::FromStream(pStream);

					HMENU hMenu = GetMenu(hWnd);
					EnableMenuItem(hMenu, IDM_SAVE_AS, MF_ENABLED);
					EnableMenuItem(hMenu, IDM_DUMP_JPGS, MF_ENABLED);
					EnableMenuItem(hMenu, IDM_CHANGE_JPG, MF_ENABLED);
					InvalidateRect(hWnd, NULL, TRUE);
				}
			}
			break;
		}
		case IDM_SAVE_AS: {
			TCHAR path[MAX_PATH];
			if (SaveFileDialog(hWnd, path, _T("Pri File (*.pri)\0*.pri\0\0"))) {
				int length = _tcslen(path);
				if (length <= 4 || !isStringIgnoreCaseEndWith(path, _T(".pri")))
					_tcscat_s(path, _T(".pri"));

				if (pChanger)
					pChanger->saveAs(path);
			}
			break;
		}
		case IDM_DUMP_JPGS: {
			TCHAR path[MAX_PATH];
			BROWSEINFO bInfo = { 0 };
			bInfo.hwndOwner = hWnd;
			bInfo.lpszTitle = szOutputDirectory;
			bInfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_USENEWUI | BIF_UAHINT;
			LPITEMIDLIST lpList = SHBrowseForFolder(&bInfo);
			if (lpList && SHGetPathFromIDList(lpList, path) && pLoader) {
				_tcscat_s(path, _T("\\"));
				pLoader->dumpDataFiles(path, 0xD8FF);
			}
			break;
		}
		case IDM_CHANGE_JPG: {
			TCHAR path[MAX_PATH];
			if (OpenFileDialog(hWnd, path, _T("Jpg File (*.jpg)\0*.jpg\0\0"))) {
				if (pChanger)
					pChanger->changeBackGroundJpg(path);

				if (pImage) {
					delete pImage;
					pImage = NULL;
				}

				BYTE* pBuffer = reinterpret_cast<BYTE*>(GlobalLock(hGlobal));
				pLoader->getDataByIndex(pBuffer, MAP_BUFFER_SIZE, 3);
				GlobalUnlock(hGlobal);
				IStream* pStream = NULL;
				if (CreateStreamOnHGlobal(hGlobal, FALSE, &pStream) == S_OK) {
					pImage = Gdiplus::Image::FromStream(pStream);

					HMENU hMenu = GetMenu(hWnd);
					EnableMenuItem(hMenu, IDM_SAVE_AS, MF_ENABLED);
					EnableMenuItem(hMenu, IDM_CHANGE_JPG, MF_ENABLED);
					InvalidateRect(hWnd, NULL, TRUE);
				}
			}
			break;
		}
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
	}
	break;
	case WM_ERASEBKGND:
		return 1;
	case WM_PAINT:
	{
		RECT rc;
		GetClientRect(hWnd, &rc);
		Gdiplus::Rect rect(rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top);

		PAINTSTRUCT ps;
		HDC hdc = BeginPaint(hWnd, &ps);
		HDC hMemDC = CreateCompatibleDC(hdc);
		HBITMAP hMemBitmap = CreateCompatibleBitmap(hdc, rect.Width, rect.Height);
		SelectObject(hMemDC, hMemBitmap);
		if (pImage) {
			Gdiplus::Graphics graphics(hMemDC);
			graphics.DrawImage(pImage, rect);
			BitBlt(hdc, rect.GetTop(), rect.GetTop(), rect.Width, rect.Height, hMemDC, 0, 0, SRCCOPY);
		}
		DeleteObject(hMemBitmap);
		DeleteDC(hMemDC);
		EndPaint(hWnd, &ps);
	}
	break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
コード例 #14
0
ファイル: NotifyWnd.cpp プロジェクト: zcp0415/CloudDesktop
void ShowNotifyWnd(HWND hWnd, LPCTSTR title, LPCTSTR content, int timeoutMS, int nIcon, int nImg)
{
	//EnterCriticalSection(&g_NotifyInfo.cs);
	//g_NotifyInfo.mode = mode;
	LPNOTIFYWND_DATA pInfo = (LPNOTIFYWND_DATA)GetWindowLongPtr(hWnd, GWLP_USERDATA);
	if(pInfo == NULL) return;

	_tcscpy_s(pInfo->szTitle, _ARRAYSIZE(pInfo->szTitle), title);
	_tcscpy_s(pInfo->szContent, _ARRAYSIZE(pInfo->szContent), content);

	if(nIcon >= 0)
		pInfo->rcTitle.left = pInfo->rcIcon.right + g_NotifyInfo.gap;
	else
		pInfo->rcTitle.left = 3 + g_NotifyInfo.gap;


	if(nImg >= 0)
		pInfo->rcContent.left = pInfo->rcImg.right + g_NotifyInfo.gap;
	else
		pInfo->rcContent.left = pInfo->rcContentOutter.left + g_NotifyInfo.gap;
	pInfo->rcContent.top = pInfo->rcContentOutter.top + g_NotifyInfo.gap;
	pInfo->rcContent.right = pInfo->rcContent.left + pInfo->contentWidth;
	pInfo->rcContentOutter.right = pInfo->rcContent.right + g_NotifyInfo.gap;

	pInfo->wndWidth = pInfo->rcContentOutter.right + 3;
	pInfo->rcTitle.right = pInfo->wndWidth - g_NotifyInfo.gap;

	pInfo->rcContent.bottom = pInfo->rcContent.top + 48;
	pInfo->rcContentOutter.bottom = pInfo->rcContent.bottom + g_NotifyInfo.gap;

	//rcCloseBtn
	pInfo->rcCloseBtn.right = pInfo->wndWidth - 3 - g_NotifyInfo.gap/2;
	pInfo->rcCloseBtn.left = pInfo->rcCloseBtn.right - g_NotifyInfo.closeBtnSize;
	pInfo->rcCloseBtn.top = (pInfo->rcTitle.top + pInfo->rcTitle.bottom - g_NotifyInfo.closeBtnSize)/2;
	pInfo->rcCloseBtn.bottom = pInfo->rcCloseBtn.top + g_NotifyInfo.closeBtnSize;

	SetBkMode(pInfo->hMemDC, TRANSPARENT);
	
	//DT_TOP = 0; (default) 在这里测量矩形
	HGDIOBJ hOldFont = SelectObject(pInfo->hMemDC, g_NotifyInfo.hFontContent);
	DrawText(pInfo->hMemDC, pInfo->szContent, -1,
		&pInfo->rcContent, DT_LEFT | DT_WORDBREAK | DT_CALCRECT);
	
	//复原宽度
	pInfo->rcContent.right = pInfo->rcContent.left + pInfo->contentWidth;

	if(pInfo->mode == MODE_PROGRESS)
	{
		pInfo->bDownloading = TRUE;

		pInfo->rcProgressText.left = pInfo->rcContent.left;
		pInfo->rcProgressText.top = pInfo->rcContent.bottom + g_NotifyInfo.gap;
		pInfo->rcProgressText.right = pInfo->rcContent.right;
		pInfo->rcProgressText.bottom = pInfo->rcProgressText.top + pInfo->titleHeight;

		pInfo->rcProgressBarOutter.left = pInfo->rcContent.left;
		pInfo->rcProgressBarOutter.top = pInfo->rcProgressText.bottom + g_NotifyInfo.gap;
		pInfo->rcProgressBarOutter.right = pInfo->rcContent.right;
		pInfo->rcProgressBarOutter.bottom = pInfo->rcProgressBarOutter.top + g_NotifyInfo.gap * 2 + 4;

		CopyRect(&pInfo->rcProgressBar, &pInfo->rcProgressBarOutter);
		InflateRect(&pInfo->rcProgressBar, -2, - 2);

		pInfo->rcContent.bottom = pInfo->rcProgressBar.bottom + g_NotifyInfo.gap;
	}	

	//更新高度等
	if(nImg >= 0 && pInfo->rcImg.bottom > pInfo->rcContent.bottom)
		pInfo->rcContentOutter.bottom = pInfo->rcImg.bottom + g_NotifyInfo.gap;
	else
		pInfo->rcContentOutter.bottom = pInfo->rcContent.bottom + g_NotifyInfo.gap;

	pInfo->wndHeight = pInfo->rcContentOutter.bottom + 3;

	//FillRgn(hdc, pInfo->hRgnBkGnd, pInfo->hBrush);
	RECT rc = { 0, 0, pInfo->wndWidth, pInfo->wndHeight };
	FillRect(pInfo->hMemDC, &rc, GetSysColorBrush(COLOR_INACTIVECAPTION)); //pInfo->hBrush);
	FrameRect(pInfo->hMemDC, &rc, g_NotifyInfo.hBrushBorder);
	FillRect(pInfo->hMemDC, &pInfo->rcContentOutter, (HBRUSH)GetStockObject(WHITE_BRUSH));

	//绘制标题icon
	if(nIcon >= 0 && !g_NotifyInfo.pIcons->IsNull())
	{
		g_NotifyInfo.pIcons->AlphaBlend(pInfo->hMemDC,
			pInfo->rcIcon.left, pInfo->rcIcon.top,
			g_NotifyInfo.iconSize, g_NotifyInfo.iconSize,
			g_NotifyInfo.iconSize * nIcon, 0,
			g_NotifyInfo.iconSize, g_NotifyInfo.iconSize);
	}
	//绘制左上角Image
	if(nImg >= 0 && !g_NotifyInfo.pImgs->IsNull())
	{
		g_NotifyInfo.pImgs->AlphaBlend(pInfo->hMemDC,
			pInfo->rcImg.left, pInfo->rcImg.top,
			g_NotifyInfo.imgSize, g_NotifyInfo.imgSize,
			g_NotifyInfo.imgSize * nImg, 0,
			g_NotifyInfo.imgSize, g_NotifyInfo.imgSize);
	}

	//绘制标题
	SelectObject(pInfo->hMemDC, g_NotifyInfo.hFontTitle);
	SetTextColor(pInfo->hMemDC, g_NotifyInfo.clrTitle);
	DrawText(pInfo->hMemDC, pInfo->szTitle, -1,
		&pInfo->rcTitle, DT_LEFT | DT_VCENTER | DT_SINGLELINE);

	//绘制文本
	SelectObject(pInfo->hMemDC, g_NotifyInfo.hFontContent);
	SetTextColor(pInfo->hMemDC, g_NotifyInfo.clrContent);
	DrawText(pInfo->hMemDC, pInfo->szContent, -1, 
		&pInfo->rcContent, DT_LEFT | DT_WORDBREAK);
	//复原字体
	SelectObject(pInfo->hMemDC, hOldFont);

	int scrollbar_width = GetSystemMetrics(SM_CXVSCROLL);
	//Width of the screen of the primary display monitor
	int screen_width = GetSystemMetrics(SM_CXSCREEN);

	if(pInfo->mode == MODE_TEXT)
	{
		SetWindowPos(hWnd, NULL,
			screen_width - pInfo->wndWidth - scrollbar_width,
			g_NotifyInfo.rcWorkArea.bottom,
			pInfo->wndWidth, 
			0,
			SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOCOPYBITS | SWP_SHOWWINDOW);

		SetTimer(hWnd, TIMERID_NOTIFY_SHOWING, INTERVAL_NOTIFYWND, NULL);
	}
	else if(pInfo->mode == MODE_PROGRESS)
	{
		//绘制进度条的外边框
		FrameRect(pInfo->hMemDC, &pInfo->rcProgressBarOutter, g_NotifyInfo.hBrushBorder);
		pInfo->szProgressText[0] = 0;
		pInfo->progress = 0;

		//SWP_NOCOPYBITS : 抛弃客户区内容(如果不设置,则系统把窗口的有效区域拷贝到移动后的窗口)
		//因为窗口的内容可能已经发生变更,所以指定这个属性,相当于强制窗口重绘(InvalidateRect)。
		SetWindowPos(hWnd, NULL,
			screen_width - pInfo->wndWidth - scrollbar_width,
			g_NotifyInfo.rcWorkArea.bottom - pInfo->wndHeight,
			pInfo->wndWidth,
			pInfo->wndHeight,
			SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOCOPYBITS | SWP_SHOWWINDOW);

		KillTimer(hWnd, TIMERID_NOTIFY_SHOWING);
	}

	//防止定时器冲突,kill 现有的所有显示定时器
	KillTimer(hWnd, TIMERID_NOTIFY_HIDING);
	KillTimer(hWnd, TIMERID_NOTIFY_HIDE);

	//安装超时定时器, 如果这个参数小于等于0,则表示永远显示!
	if(timeoutMS > 0)
		SetTimer(hWnd, TIMERID_NOTIFY_TIMEOUT, timeoutMS, NULL);
	else
		KillTimer(hWnd, TIMERID_NOTIFY_TIMEOUT);

	//LeaveCriticalSection(&g_NotifyInfo.cs);
}
コード例 #15
0
ファイル: TortoiseMerge.cpp プロジェクト: goodoid/TortoiseGit
// CTortoiseMergeApp initialization
BOOL CTortoiseMergeApp::InitInstance()
{
	SetDllDirectory(L"");

	CMFCVisualManager::SetDefaultManager(RUNTIME_CLASS(CMFCVisualManagerWindows));
	CMFCButton::EnableWindowsTheming();

	{
		DWORD len = GetCurrentDirectory(0, NULL);
		if (len)
		{
			auto_buffer<TCHAR> originalCurrentDirectory(len);
			if (GetCurrentDirectory(len, originalCurrentDirectory))
			{
				sOrigCWD = originalCurrentDirectory;
				sOrigCWD = CPathUtils::GetLongPathname(sOrigCWD);
			}
		}
	}

	//set the resource dll for the required language
	CRegDWORD loc = CRegDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
	long langId = loc;
	CString langDll;
	HINSTANCE hInst = NULL;
	do
	{
		langDll.Format(_T("%sLanguages\\TortoiseMerge%d.dll"), (LPCTSTR)CPathUtils::GetAppParentDirectory(), langId);

		hInst = LoadLibrary(langDll);
		CString sVer = _T(STRPRODUCTVER);
		CString sFileVer = CPathUtils::GetVersionFromFile(langDll);
		if (sFileVer.Compare(sVer)!=0)
		{
			FreeLibrary(hInst);
			hInst = NULL;
		}
		if (hInst != NULL)
			AfxSetResourceHandle(hInst);
		else
		{
			DWORD lid = SUBLANGID(langId);
			lid--;
			if (lid > 0)
			{
				langId = MAKELANGID(PRIMARYLANGID(langId), lid);
			}
			else
				langId = 0;
		}
	} while ((hInst == NULL) && (langId != 0));
	TCHAR buf[6];
	_tcscpy_s(buf, _T("en"));
	langId = loc;
	CString sHelppath;
	sHelppath = this->m_pszHelpFilePath;
	sHelppath = sHelppath.MakeLower();
	sHelppath.Replace(_T(".chm"), _T("_en.chm"));
	free((void*)m_pszHelpFilePath);
	m_pszHelpFilePath=_tcsdup(sHelppath);
	sHelppath = CPathUtils::GetAppParentDirectory() + _T("Languages\\TortoiseMerge_en.chm");
	do
	{
		GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO639LANGNAME, buf, _countof(buf));
		CString sLang = _T("_");
		sLang += buf;
		sHelppath.Replace(_T("_en"), sLang);
		if (PathFileExists(sHelppath))
		{
			free((void*)m_pszHelpFilePath);
			m_pszHelpFilePath=_tcsdup(sHelppath);
			break;
		}
		sHelppath.Replace(sLang, _T("_en"));
		GetLocaleInfo(MAKELCID(langId, SORT_DEFAULT), LOCALE_SISO3166CTRYNAME, buf, _countof(buf));
		sLang += _T("_");
		sLang += buf;
		sHelppath.Replace(_T("_en"), sLang);
		if (PathFileExists(sHelppath))
		{
			free((void*)m_pszHelpFilePath);
			m_pszHelpFilePath=_tcsdup(sHelppath);
			break;
		}
		sHelppath.Replace(sLang, _T("_en"));

		DWORD lid = SUBLANGID(langId);
		lid--;
		if (lid > 0)
		{
			langId = MAKELANGID(PRIMARYLANGID(langId), lid);
		}
		else
			langId = 0;
	} while (langId);
	setlocale(LC_ALL, ""); 
	// We need to explicitly set the thread locale to the system default one to avoid possible problems with saving files in its original codepage
	// The problems occures when the language of OS differs from the regional settings
	// See the details here: http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=100887
	SetThreadLocale(LOCALE_SYSTEM_DEFAULT);

	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	InitCommonControls();

	// Initialize all Managers for usage. They are automatically constructed
	// if not yet present
	InitContextMenuManager();
	InitKeyboardManager();

	CCmdLineParser parser = CCmdLineParser(this->m_lpCmdLine);

	if (parser.HasKey(_T("?")) || parser.HasKey(_T("help")))
	{
		CString sHelpText;
		sHelpText.LoadString(IDS_COMMANDLINEHELP);
		MessageBox(NULL, sHelpText, _T("TortoiseMerge"), MB_ICONINFORMATION);
		return FALSE;
	}

	// Initialize OLE libraries
	if (!AfxOleInit())
	{
		AfxMessageBox(IDP_OLE_INIT_FAILED);
		return FALSE;
	}
	AfxEnableControlContainer();
	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	SetRegistryKey(_T("TortoiseMerge"));

	if (CRegDWORD(_T("Software\\TortoiseMerge\\Debug"), FALSE)==TRUE)
		AfxMessageBox(AfxGetApp()->m_lpCmdLine, MB_OK | MB_ICONINFORMATION);

	// To create the main window, this code creates a new frame window
	// object and then sets it as the application's main window object
	CMainFrame* pFrame = new CMainFrame;
	if (pFrame == NULL)
		return FALSE;
	m_pMainWnd = pFrame;

	// create and load the frame with its resources
	pFrame->LoadFrame(IDR_MAINFRAME,
		WS_OVERLAPPEDWINDOW | FWS_ADDTOTITLE, NULL,
		NULL);

	// Fill in the command line options
	pFrame->m_Data.m_baseFile.SetFileName(parser.GetVal(_T("base")));
	pFrame->m_Data.m_baseFile.SetDescriptiveName(parser.GetVal(_T("basename")));
	pFrame->m_Data.m_theirFile.SetFileName(parser.GetVal(_T("theirs")));
	pFrame->m_Data.m_theirFile.SetDescriptiveName(parser.GetVal(_T("theirsname")));
	pFrame->m_Data.m_yourFile.SetFileName(parser.GetVal(_T("mine")));
	pFrame->m_Data.m_yourFile.SetDescriptiveName(parser.GetVal(_T("minename")));
	pFrame->m_Data.m_mergedFile.SetFileName(parser.GetVal(_T("merged")));
	pFrame->m_Data.m_mergedFile.SetDescriptiveName(parser.GetVal(_T("mergedname")));
	pFrame->m_Data.m_sPatchPath = parser.HasVal(_T("patchpath")) ? parser.GetVal(_T("patchpath")) : _T("");
	pFrame->m_Data.m_sPatchPath.Replace('/', '\\');
	if (parser.HasKey(_T("patchoriginal")))
		pFrame->m_Data.m_sPatchOriginal = parser.GetVal(_T("patchoriginal"));
	if (parser.HasKey(_T("patchpatched")))
		pFrame->m_Data.m_sPatchPatched = parser.GetVal(_T("patchpatched"));
	pFrame->m_Data.m_sDiffFile = parser.GetVal(_T("diff"));
	pFrame->m_Data.m_sDiffFile.Replace('/', '\\');
	if (parser.HasKey(_T("oneway")))
		pFrame->m_bOneWay = TRUE;
	if (parser.HasKey(_T("diff")))
		pFrame->m_bOneWay = FALSE;
	if (parser.HasKey(_T("reversedpatch")))
		pFrame->m_bReversedPatch = TRUE;
	if (pFrame->m_Data.IsBaseFileInUse() && !pFrame->m_Data.IsYourFileInUse() && pFrame->m_Data.IsTheirFileInUse())
	{
		pFrame->m_Data.m_yourFile.TransferDetailsFrom(pFrame->m_Data.m_theirFile);
	}

	if ((!parser.HasKey(_T("patchpath")))&&(parser.HasVal(_T("diff"))))
	{
		// a patchfile was given, but not folder path to apply the patch to
		// If the patchfile is located inside a working copy, then use the parent directory
		// of the patchfile as the target directory, otherwise ask the user for a path.
		if (parser.HasKey(_T("wc")))
			pFrame->m_Data.m_sPatchPath = pFrame->m_Data.m_sDiffFile.Left(pFrame->m_Data.m_sDiffFile.ReverseFind('\\'));
		else
		{
			CBrowseFolder fbrowser;
			fbrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
			if (fbrowser.Show(NULL, pFrame->m_Data.m_sPatchPath)==CBrowseFolder::CANCEL)
				return FALSE;
		}
	}

	if ((parser.HasKey(_T("patchpath")))&&(!parser.HasVal(_T("diff"))))
	{
		// A path was given for applying a patchfile, but
		// the patchfile itself was not.
		// So ask the user for that patchfile

		OPENFILENAME ofn = {0};			// common dialog box structure
		TCHAR szFile[MAX_PATH] = {0};	// buffer for file name
		// Initialize OPENFILENAME
		ofn.lStructSize = sizeof(OPENFILENAME);
		ofn.hwndOwner = pFrame->m_hWnd;
		ofn.lpstrFile = szFile;
		ofn.nMaxFile = _countof(szFile);
		CString temp;
		temp.LoadString(IDS_OPENDIFFFILETITLE);
		if (temp.IsEmpty())
			ofn.lpstrTitle = NULL;
		else
			ofn.lpstrTitle = temp;

		ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
		// check if there's a patchfile in the clipboard
		UINT cFormat = RegisterClipboardFormat(_T("TSVN_UNIFIEDDIFF"));
		if (cFormat)
		{
			if (OpenClipboard(NULL))
			{
				UINT enumFormat = 0;
				do 
				{
					if (enumFormat == cFormat)
					{
						// yes, there's a patchfile in the clipboard
						ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST | OFN_HIDEREADONLY | OFN_ENABLETEMPLATE | OFN_ENABLEHOOK | OFN_EXPLORER;

						ofn.hInstance = AfxGetResourceHandle();
						ofn.lpTemplateName = MAKEINTRESOURCE(IDD_PATCH_FILE_OPEN_CUSTOM);
						ofn.lpfnHook = CreatePatchFileOpenHook;
					}
				} while((enumFormat = EnumClipboardFormats(enumFormat))!=0);
				CloseClipboard();
			}
		}

		CString sFilter;
		sFilter.LoadString(IDS_PATCHFILEFILTER);
		TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
		_tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
		// Replace '|' delimiters with '\0's
		TCHAR *ptr = pszFilters + _tcslen(pszFilters);  //set ptr at the NULL
		while (ptr != pszFilters)
		{
			if (*ptr == '|')
				*ptr = '\0';
			ptr--;
		}
		ofn.lpstrFilter = pszFilters;
		ofn.nFilterIndex = 1;

		// Display the Open dialog box. 
		CString tempfile;
		if (GetOpenFileName(&ofn)==FALSE)
		{
			delete [] pszFilters;
			return FALSE;
		}
		delete [] pszFilters;
		pFrame->m_Data.m_sDiffFile = ofn.lpstrFile;
	}

	if ( pFrame->m_Data.m_baseFile.GetFilename().IsEmpty() && pFrame->m_Data.m_yourFile.GetFilename().IsEmpty() )
	{
		LPWSTR *szArglist;
		int nArgs;

		szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
		if( NULL == szArglist )
		{
			TRACE("CommandLineToArgvW failed\n");
		}
		else
		{
			if ( nArgs==3 || nArgs==4 )
			{
				// Four parameters:
				// [0]: Program name
				// [1]: BASE file
				// [2]: my file
				// [3]: THEIR file (optional)
				// This is the same format CAppUtils::StartExtDiff
				// uses if %base and %mine are not set and most
				// other diff tools use it too.
				if ( PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]) )
				{
					pFrame->m_Data.m_baseFile.SetFileName(szArglist[1]);
					pFrame->m_Data.m_yourFile.SetFileName(szArglist[2]);
					if ( nArgs == 4 && PathFileExists(szArglist[3]) )
					{
						pFrame->m_Data.m_theirFile.SetFileName(szArglist[3]);
					}
				}
			}
		}

		// Free memory allocated for CommandLineToArgvW arguments.
		LocalFree(szArglist);
	}

	pFrame->m_bReadOnly = !!parser.HasKey(_T("readonly"));
	if (GetFileAttributes(pFrame->m_Data.m_yourFile.GetFilename()) & FILE_ATTRIBUTE_READONLY)
		pFrame->m_bReadOnly = true;
	pFrame->m_bBlame = !!parser.HasKey(_T("blame"));
	// diffing a blame means no editing!
	if (pFrame->m_bBlame)
		pFrame->m_bReadOnly = true;

	// try to find a suitable window title
	CString sYour = pFrame->m_Data.m_yourFile.GetDescriptiveName();
	if (sYour.Find(_T(" - "))>=0)
		sYour = sYour.Left(sYour.Find(_T(" - ")));
	if (sYour.Find(_T(" : "))>=0)
		sYour = sYour.Left(sYour.Find(_T(" : ")));
	CString sTheir = pFrame->m_Data.m_theirFile.GetDescriptiveName();
	if (sTheir.Find(_T(" - "))>=0)
		sTheir = sTheir.Left(sTheir.Find(_T(" - ")));
	if (sTheir.Find(_T(" : "))>=0)
		sTheir = sTheir.Left(sTheir.Find(_T(" : ")));

	if (!sYour.IsEmpty() && !sTheir.IsEmpty())
	{
		if (sYour.CompareNoCase(sTheir)==0)
			pFrame->SetWindowText(sYour + _T(" - TortoiseMerge"));
		else if ((sYour.GetLength() < 10) &&
				(sTheir.GetLength() < 10))
			pFrame->SetWindowText(sYour + _T(" - ") + sTheir + _T(" - TortoiseMerge"));
		else
		{
			// we have two very long descriptive texts here, which
			// means we have to find a way to use them as a window 
			// title in a shorter way.
			// for simplicity, we just use the one from "yourfile"
			pFrame->SetWindowText(sYour + _T(" - TortoiseMerge"));
		}
	}
	else if (!sYour.IsEmpty())
		pFrame->SetWindowText(sYour + _T(" - TortoiseMerge"));
	else if (!sTheir.IsEmpty())
		pFrame->SetWindowText(sTheir + _T(" - TortoiseMerge"));

	if (parser.HasKey(_T("createunifieddiff")))
	{
		// user requested to create a unified diff file
		CString origFile = parser.GetVal(_T("origfile"));
		CString modifiedFile = parser.GetVal(_T("modifiedfile"));
		if (!origFile.IsEmpty() && !modifiedFile.IsEmpty())
		{
			CString outfile = parser.GetVal(_T("outfile"));
			if (outfile.IsEmpty())
			{
				OPENFILENAME ofn = {0};			// common dialog box structure
				TCHAR szFile[MAX_PATH] = {0};	// buffer for file name
				ofn.lStructSize = sizeof(OPENFILENAME);
				ofn.lpstrFile = szFile;
				ofn.nMaxFile = _countof(szFile);
				CString temp;
				temp.LoadString(IDS_SAVEASTITLE);
				if (!temp.IsEmpty())
					ofn.lpstrTitle = temp;
				ofn.Flags = OFN_OVERWRITEPROMPT;
				CString sFilter;
				sFilter.LoadString(IDS_COMMONFILEFILTER);
				TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
				_tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
				// Replace '|' delimiters with '\0's
				TCHAR *ptr = pszFilters + _tcslen(pszFilters);  //set ptr at the NULL
				while (ptr != pszFilters)
				{
					if (*ptr == '|')
						*ptr = '\0';
					ptr--;
				}
				ofn.lpstrFilter = pszFilters;
				ofn.nFilterIndex = 1;

				// Display the Save dialog box. 
				CString sFile;
				if (GetSaveFileName(&ofn)==TRUE)
				{
					outfile = CString(ofn.lpstrFile);
				}
				delete [] pszFilters;
			}
			if (!outfile.IsEmpty())
			{
				CAppUtils::CreateUnifiedDiff(origFile, modifiedFile, outfile, false);
				return FALSE;
			}
		}
	}
	// The one and only window has been initialized, so show and update it
	pFrame->ActivateFrame();
	pFrame->ShowWindow(SW_SHOW);
	pFrame->UpdateWindow();
	pFrame->ShowDiffBar(!pFrame->m_bOneWay);
	if (!pFrame->m_Data.IsBaseFileInUse() && pFrame->m_Data.m_sPatchPath.IsEmpty() && pFrame->m_Data.m_sDiffFile.IsEmpty())
	{
		pFrame->OnFileOpen();
		return TRUE;
	}

	return pFrame->LoadViews();
}
コード例 #16
0
int main(int argc, char* argv[])
{
    IADs             *pNS = NULL,
                     *pRoot=NULL,
                     *pAuth=NULL;
    
    IADsOpenDSObject *pDSObj=NULL;

    VARIANT varDSRoot;

    TCHAR   adspath[MAX_PATH],username[255],password[255];

    HRESULT hr;

	hr = CoInitialize(NULL);
	
	//  Get the name of the root container for this domain.  
	//  Read the Root DSE from the default DS,  which will be the DS for 
	//  the local domain.  This will get us the name of the schema container,
	//  which is stored in the "defaultNamingContext" operational attribute.

    hr = ADsGetObject(TEXT("LDAP://RootDSE"),
                      IID_IADs,
                      (void**)&pRoot);

	if ( FAILED(hr) )
	{
		::CoUninitialize();
		_tprintf(TEXT("\nError in ADsGetObject"));
		return 1;
	}


   	hr = pRoot->Get(TEXT("defaultNamingContext"),&varDSRoot);

	if ( FAILED(hr) )
	{
		::CoUninitialize();
		pRoot->Release();
		_tprintf(TEXT("\nError in reading defaultNamingContext"));
		return 1;

	}

	_tprintf(TEXT("\nDomain Name is :%s\n"),varDSRoot.bstrVal);
    pRoot->Release();

    _tcscpy_s(adspath,MAX_PATH, TEXT("LDAP://"));
	// get the remaining buffer size; make sure it copies, avoid buffer overrun
	int rem =  (sizeof(adspath)/sizeof(TCHAR)) - _tcslen(adspath) -1; //-1 is for NULL
	int len = wcslen(varDSRoot.bstrVal);

	if ( rem >= len )
	{
		_tcsncat_s(adspath,MAX_PATH,varDSRoot.bstrVal, len);
	}
	else
	{
		pRoot->Release();
		VariantClear(&varDSRoot);
		return 1;
	}


     

    hr = ADsGetObject(TEXT("LDAP:"),
                      IID_IADs,
                      (void**)&pNS);
	if ( FAILED(hr) )
	{
		::CoUninitialize();
		_tprintf(TEXT("\nError in ADsGetObject"));
		return 1;
	}

    hr = pNS->QueryInterface(IID_IADsOpenDSObject,(void**)&pDSObj);

	if ( FAILED(hr) )
	{
		::CoUninitialize();
		pNS->Release();
		_tprintf(TEXT("\nError in QueryInterface"));
		return 1;
	}
    //
    // Collect the username and password and bind to the Domain using these.
    //

    if SUCCEEDED(hr) 
	{
        pNS->Release();
        _tprintf(TEXT("\nusername:"));
        _fgetts(username,sizeof(username)/sizeof(TCHAR),stdin);
		username[_tcslen(username)-1] = '\0';
        _tprintf(TEXT("\"%s\""), username);
		_tprintf(TEXT("\npassword:"));
        _fgetts(password, sizeof(password)/sizeof(TCHAR), stdin);
		password[_tcslen(password)-1] = '\0';
        hr = pDSObj->OpenDSObject(adspath,username,password,ADS_SECURE_AUTHENTICATION,(IDispatch**)&pAuth);
		// NOTE: Alternatively you can use an ADSI wrapper API: ADsOpenObject
        if FAILED(hr) 
		{
            ReportError(TEXT("Bind Failed"),(DWORD)hr);
        }
		else
		{
			_tprintf(TEXT("Successfully logon!"));

		}
    }
コード例 #17
0
ファイル: TabAES256Dlg.cpp プロジェクト: CoterJiesen/winaes
DWORD WINAPI _CryptoThdFunc(LPVOID _lParam)
{
	TCHAR *_outFilePath = new TCHAR[512];

	//input CDialog pointer
	CTabAES256Dlg *_TabAES256Dlg;
	_TabAES256Dlg = (CTabAES256Dlg *)_lParam;

	//UI
	_TabAES256Dlg->_EnableCtrls(0);

	for(UINT32 _i = 0; _i < _TabAES256Dlg->_inFilePathAllCount; _i++)
	{
		//Set Index Flag
		_TabAES256Dlg->_curEncItem = _i;
		_tcscpy_s(_outFilePath, 512, _TabAES256Dlg->_inFilePath_All[_i]);
		
		//
		if(_TabAES256Dlg->_bCamellia)
		{
			// ********* Encrypt/Decrypt(Camellia) *********
			//Set Flag
			_TabAES256Dlg->_bErasing = 0;
			if(_TabAES256Dlg->_bDecrypt)
			{
				//Decrypt Mode
				if(_tcslen(_outFilePath) >= 8){
					if(!_tcscmp(&_outFilePath[_tcslen(_outFilePath) - 7], _T(".cam256")))
					{	//cut extension ".cam256"
						_outFilePath[_tcslen(_outFilePath) - 7] = 0;
					}else{
						_tcscat_s(_outFilePath, 512, _T(".decrypted"));
					}
				}
				if(_File_Camellia_Decrypt_CBC(_TabAES256Dlg->_inFilePath_All[_i], _outFilePath, _TabAES256Dlg->_CryptoCipherKey, &_UpdateOpProcess, _lParam)){
					_TabAES256Dlg->_SetItemStatusInList(_i, _T("Decrypted"));
				}else{
					_TabAES256Dlg->_SetItemStatusInList(_i, _T("Decryption Failed"));
					//No need to erase
					_TabAES256Dlg->_bErase = 0;
				}

			}else{
				//Encrypt Mode
				_tcscat_s(_outFilePath, 512, _T(".cam256"));
				if(_File_Camellia_Encrypt_CBC(_TabAES256Dlg->_inFilePath_All[_i], _outFilePath, _TabAES256Dlg->_CryptoCipherKey, &_UpdateOpProcess, _lParam)){
					_TabAES256Dlg->_SetItemStatusInList(_i, _T("Encrypted"));
				}else{
					_TabAES256Dlg->_SetItemStatusInList(_i, _T("Encryption Failed"));
					//No need to erase
					_TabAES256Dlg->_bErase = 0;
				}
			}//if
		}else{
			// ********* Encrypt/Decrypt(AES) *********
			//Set Flag
			_TabAES256Dlg->_bErasing = 0;
			if(_TabAES256Dlg->_bDecrypt)
			{
				//Decrypt Mode
				if(_tcslen(_outFilePath) >= 8){
					if(!_tcscmp(&_outFilePath[_tcslen(_outFilePath) - 7], _T(".aes256")))
					{	//cut extension ".aes256"
						_outFilePath[_tcslen(_outFilePath) - 7] = 0;
					}else{
						_tcscat_s(_outFilePath, 512, _T(".decrypted"));
					}
				}
				if(_File_AES_Decrypt_CBC(_TabAES256Dlg->_inFilePath_All[_i], _outFilePath, _TabAES256Dlg->_CryptoCipherKey, &_UpdateOpProcess, _lParam)){
					_TabAES256Dlg->_SetItemStatusInList(_i, _T("Decrypted"));
				}else{
					_TabAES256Dlg->_SetItemStatusInList(_i, _T("Decryption Failed"));
					//No need to erase
					_TabAES256Dlg->_bErase = 0;
				}

			}else{
				//Encrypt Mode
				_tcscat_s(_outFilePath, 512, _T(".aes256"));
				if(_File_AES_Encrypt_CBC(_TabAES256Dlg->_inFilePath_All[_i], _outFilePath, _TabAES256Dlg->_CryptoCipherKey, &_UpdateOpProcess, _lParam)){
					_TabAES256Dlg->_SetItemStatusInList(_i, _T("Encrypted"));
				}else{
					_TabAES256Dlg->_SetItemStatusInList(_i, _T("Encryption Failed"));
					//No need to erase
					_TabAES256Dlg->_bErase = 0;
				}
			}//if
		}//if(Camellia)

		//Erase Original File
		if(_TabAES256Dlg->_bErase)
		{
			//Set Flag
			_TabAES256Dlg->_bErasing = 1;
			if(File_Secure_Erase(_TabAES256Dlg->_inFilePath_All[_i], 1, &_UpdateOpProcess, _lParam)){
				_TabAES256Dlg->_SetItemStatusInList(_i, _T("Done and erased"));
			}else{
				_TabAES256Dlg->_SetItemStatusInList(_i, _T("Erasing failed"));
			}
		}
	}//for

	_TabAES256Dlg->_EnableCtrls(1);

	free(_outFilePath);

	return 0;
}
コード例 #18
0
ファイル: TrayNotifyIcon.cpp プロジェクト: uvbs/SupportCenter
BOOL CTrayNotifyIcon::Create(CWindow* pNotifyWnd, UINT uID, LPCTSTR pszTooltipText, HICON hIcon, UINT nNotifyMessage, UINT uMenuID)
#endif
{
    //Validate our parameters
    ATLASSERT(pNotifyWnd && ::IsWindow(pNotifyWnd->operator HWND()));
#ifdef _DEBUG
    if (GetShellVersion() >= 5) //If on Shell v5 or higher, then use the larger size tooltip
    {
        NOTIFYICONDATA_2 dummy;
        ATLASSERT(_tcslen(pszTooltipText) < sizeof(dummy.szTip)/sizeof(TCHAR));
        DBG_UNREFERENCED_LOCAL_VARIABLE(dummy);
    }
    else
    {
        NOTIFYICONDATA_1 dummy;
        ATLASSERT(_tcslen(pszTooltipText) < sizeof(dummy.szTip)/sizeof(TCHAR));
        DBG_UNREFERENCED_LOCAL_VARIABLE(dummy);
    }
#endif
    ATLASSERT(hIcon);
    ATLASSERT(nNotifyMessage >= WM_USER); //Make sure we avoid conflict with other messages

    //Load up the menu resource which is to be used as the context menu
    if (!m_Menu.LoadMenu(uMenuID == 0 ? uID : uMenuID))
    {
        ATLASSERT(FALSE);
        return FALSE;
    }
#ifdef _AFX
    CMenu* pSubMenu = m_Menu.GetSubMenu(0);
    if (!pSubMenu)
    {
        ATLASSERT(FALSE); //Your menu resource has been designed incorrectly
        return FALSE;
    }
    //Make the specified menu item the default (bold font)
    pSubMenu->SetDefaultItem(m_nDefaultMenuItem, m_bDefaultMenuItemByPos);
#else
    CMenuHandle subMenu = m_Menu.GetSubMenu(0);
    if (!subMenu.IsMenu())
    {
        ATLASSERT(FALSE); //Your menu resource has been designed incorrectly
        return FALSE;
    }
    subMenu.SetMenuDefaultItem(m_nDefaultMenuItem, m_bDefaultMenuItemByPos);
#endif

    //Install the hook
    if (!m_HookWnd.Init(this, pNotifyWnd))
        return FALSE;

    //Call the Shell_NotifyIcon function
    m_pNotificationWnd = pNotifyWnd;
    m_NotifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
    m_NotifyIconData.hWnd = pNotifyWnd->operator HWND();
    m_NotifyIconData.uID = uID;
    m_NotifyIconData.uCallbackMessage = nNotifyMessage;
    m_NotifyIconData.hIcon = hIcon;
#if (_MSC_VER >= 1400)
    _tcscpy_s(m_NotifyIconData.szTip, sizeof(m_NotifyIconData.szTip)/sizeof(TCHAR), pszTooltipText);
#else
    _tcscpy(m_NotifyIconData.szTip, pszTooltipText);
#endif
    m_bCreated = Shell_NotifyIcon(NIM_ADD, reinterpret_cast<PNOTIFYICONDATA>(&m_NotifyIconData));

    //Turn on Shell v5 style behaviour if supported
    if (GetShellVersion() >= 5)
        SetVersion(NOTIFYICON_VERSION);

    return m_bCreated;
}
コード例 #19
0
ファイル: TabAES256Dlg.cpp プロジェクト: CoterJiesen/winaes
BOOL CTabAES256Dlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	//Add Columns
	LPLVCOLUMN _tmpColumn = new LVCOLUMN;
	if (!this->_ctl_lst_files.GetColumnWidth(0))
	{
		//Set ListBox Style
		_ctl_lst_files.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_BORDERSELECT | LVS_EX_GRIDLINES | LVS_EX_DOUBLEBUFFER);
		//Set Mask
		_tmpColumn->mask = LVCF_SUBITEM | LVCF_TEXT;
		//Insert Columns
		_tmpColumn->iSubItem = 0;	//SubItemIndex
		_tmpColumn->pszText = _T("File Path");	//Caption
		this->_ctl_lst_files.InsertColumn(0, _tmpColumn);	//Insert

		_tmpColumn->iSubItem = 1;
		_tmpColumn->pszText=_T("Size");
		this->_ctl_lst_files.InsertColumn(1, _tmpColumn);

		_tmpColumn->iSubItem = 2;
		_tmpColumn->pszText = _T("Status");
		this->_ctl_lst_files.InsertColumn(2, _tmpColumn);

		//Set Width
		this->_ctl_lst_files.SetColumnWidth(0,410);
		this->_ctl_lst_files.SetColumnWidth(1,110);
		this->_ctl_lst_files.SetColumnWidth(2,120);
	}

	//Set Default Radio(Check) Buttons
	this->_ctl_rad_aes = (CButton *)GetDlgItem(_RAD_AES);
	this->_ctl_rad_cam = (CButton *)GetDlgItem(_RAD_CAM);
	this->_ctl_rad_aes->SetCheck(TRUE);
	
	//Set Controls
	this->_ctl_edit_pass.SetLimitText(32);
	_EnableCtrls(1);

	//Initiate Variables 
	this->_iFileIndex = 0;

	if(_tcslen(theApp.m_lpCmdLine))
	{
		TCHAR _curFilePath[512];
		TCHAR _curFileLenStr[512];
		UINT64 _curFileLen;
		_curFilePath[0] = 0;

		//Copy Path
		_tcscpy_s(_curFilePath, 512, theApp.m_lpCmdLine + 1);

		//Remove "
		_curFilePath[_tcslen(_curFilePath) - 1] = 0;

		//Get Length
		if(this->_GetFileLen(_curFilePath, &_curFileLen)){
			_stprintf_s(_curFileLenStr, 128, _T("%lld KB"), (_curFileLen / 1024));
		}else{
			_stprintf_s(_curFileLenStr, 128, _T("Open Failed"));
		}
		//add to list
		this->_AddToList(0, _curFilePath, _curFileLenStr, _T("Ready"));
	}
	return TRUE;
}
コード例 #20
0
ファイル: TrayNotifyIcon.cpp プロジェクト: uvbs/SupportCenter
BOOL CTrayNotifyIcon::Create(CWindow* pNotifyWnd, UINT uID, LPCTSTR pszTooltipText, LPCTSTR pszBalloonText, LPCTSTR pszBalloonCaption, UINT nTimeout, BalloonStyle style, HICON hIcon, UINT nNotifyMessage, UINT uMenuID, BOOL bNoSound)
#endif
{
    //Validate our parameters
    ATLASSERT(pNotifyWnd && ::IsWindow(pNotifyWnd->operator HWND()));
    ATLASSERT(GetShellVersion() >= 5); //Only supported on Shell v5 or later
#ifdef _DEBUG
    NOTIFYICONDATA_2 dummy;
    DBG_UNREFERENCED_LOCAL_VARIABLE(dummy);
    ATLASSERT(_tcslen(pszTooltipText) < sizeof(dummy.szTip)/sizeof(TCHAR));
    ATLASSERT(_tcslen(pszBalloonText) < sizeof(dummy.szInfo)/sizeof(TCHAR));
    ATLASSERT(_tcslen(pszBalloonCaption) < sizeof(dummy.szInfoTitle)/sizeof(TCHAR));
    ATLASSERT(hIcon);
    ATLASSERT(nNotifyMessage >= WM_USER); //Make sure we avoid conflict with other messages
#endif

    //Load up the menu resource which is to be used as the context menu
    if (!m_Menu.LoadMenu(uMenuID == 0 ? uID : uMenuID))
    {
        ATLASSERT(FALSE);
        return FALSE;
    }
#ifdef _AFX
    CMenu* pSubMenu = m_Menu.GetSubMenu(0);
    if (!pSubMenu)
    {
        ATLASSERT(FALSE); //Your menu resource has been designed incorrectly
        return FALSE;
    }
    //Make the specified menu item the default (bold font)
    pSubMenu->SetDefaultItem(m_nDefaultMenuItem, m_bDefaultMenuItemByPos);
#else
    CMenuHandle subMenu = m_Menu.GetSubMenu(0);
    if (!subMenu.IsMenu())
    {
        ATLASSERT(FALSE); //Your menu resource has been designed incorrectly
        return FALSE;
    }
    //Make the specified menu item the default (bold font)
    subMenu.SetMenuDefaultItem(m_nDefaultMenuItem, m_bDefaultMenuItemByPos);
#endif

    //Install the hook
    if (!m_HookWnd.Init(this, pNotifyWnd))
        return FALSE;

    //Call the Shell_NotifyIcon function
    m_pNotificationWnd = pNotifyWnd;
    m_NotifyIconData.hWnd = pNotifyWnd->operator HWND();
    m_NotifyIconData.uID = uID;
    m_NotifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP | NIF_INFO;
    m_NotifyIconData.uCallbackMessage = nNotifyMessage;
    m_NotifyIconData.hIcon = hIcon;
#if (_MSC_VER >= 1400)
    _tcscpy_s(m_NotifyIconData.szTip, sizeof(m_NotifyIconData.szTip)/sizeof(TCHAR), pszTooltipText);
    _tcscpy_s(m_NotifyIconData.szInfo, sizeof(m_NotifyIconData.szInfo)/sizeof(TCHAR), pszBalloonText);
    _tcscpy_s(m_NotifyIconData.szInfoTitle, sizeof(m_NotifyIconData.szInfoTitle)/sizeof(TCHAR), pszBalloonCaption);
#else
    _tcscpy(m_NotifyIconData.szTip, pszTooltipText);
    _tcscpy(m_NotifyIconData.szInfo, pszBalloonText);
    _tcscpy(m_NotifyIconData.szInfoTitle, pszBalloonCaption);
#endif
    m_NotifyIconData.uTimeout = nTimeout;
    switch (style)
    {
    case Warning:
    {
        m_NotifyIconData.dwInfoFlags = NIIF_WARNING;
        break;
    }
    case Error:
    {
        m_NotifyIconData.dwInfoFlags = NIIF_ERROR;
        break;
    }
    case Info:
    {
        m_NotifyIconData.dwInfoFlags = NIIF_INFO;
        break;
    }
    case None:
    {
        m_NotifyIconData.dwInfoFlags = NIIF_NONE;
        break;
    }
    case User:
    {
        ATLASSERT(hIcon != NULL); //You forget to provide a user icon
        m_NotifyIconData.dwInfoFlags = NIIF_USER;
        break;
    }
    default:
    {
        ATLASSERT(FALSE);
        break;
    }
    }
    if (bNoSound)
        m_NotifyIconData.dwInfoFlags |= NIIF_NOSOUND;

    m_bCreated = Shell_NotifyIcon(NIM_ADD, reinterpret_cast<PNOTIFYICONDATA>(&m_NotifyIconData));

    //Turn on Shell v5 tray icon behaviour
    SetVersion(NOTIFYICON_VERSION);

    return m_bCreated;
}
コード例 #21
0
ファイル: awt_FileDialog.cpp プロジェクト: lmsf/jdk9-dev
void
AwtFileDialog::Show(void *p)
{
    JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
    jobject peer;
    LPTSTR fileBuffer = NULL;
    LPTSTR currentDirectory = NULL;
    jint mode = 0;
    BOOL result = FALSE;
    DWORD dlgerr;
    jstring directory = NULL;
    jstring title = NULL;
    jstring file = NULL;
    jobject fileFilter = NULL;
    jobject target = NULL;
    jobject parent = NULL;
    AwtComponent* awtParent = NULL;
    jboolean multipleMode = JNI_FALSE;

    OPENFILENAME ofn;
    memset(&ofn, 0, sizeof(ofn));

    /*
     * There's a situation (see bug 4906972) when InvokeFunction (by which this method is called)
     * returnes earlier than this method returnes. Probably it's caused due to ReplyMessage system call.
     * So for the avoidance of this mistiming we need to make new global reference here
     * (not local as it's used by the hook) and then manage it independently of the calling thread.
     */
    peer = env->NewGlobalRef((jobject)p);

    try {
        DASSERT(peer);
        target = env->GetObjectField(peer, AwtObject::targetID);
        parent = env->GetObjectField(peer, AwtFileDialog::parentID);
        if (parent != NULL) {
            awtParent = (AwtComponent *)JNI_GET_PDATA(parent);
        }
//      DASSERT(awtParent);
        title = (jstring)(env)->GetObjectField(target, AwtDialog::titleID);
        HWND hwndOwner = awtParent ? awtParent->GetHWnd() : NULL;

        if (title == NULL || env->GetStringLength(title)==0) {
            title = JNU_NewStringPlatform(env, L" ");
            if (title == NULL) {
                throw std::bad_alloc();
            }
        }

        JavaStringBuffer titleBuffer(env, title);
        directory =
            (jstring)env->GetObjectField(target, AwtFileDialog::dirID);
        JavaStringBuffer directoryBuffer(env, directory);

        multipleMode = env->CallBooleanMethod(peer, AwtFileDialog::isMultipleModeMID);

        UINT bufferLimit;
        if (multipleMode == JNI_TRUE) {
            bufferLimit = MULTIPLE_MODE_BUFFER_LIMIT;
        } else {
            bufferLimit = SINGLE_MODE_BUFFER_LIMIT;
        }
        LPTSTR fileBuffer = new TCHAR[bufferLimit];
        memset(fileBuffer, 0, bufferLimit * sizeof(TCHAR));

        file = (jstring)env->GetObjectField(target, AwtFileDialog::fileID);
        if (file != NULL) {
            LPCTSTR tmp = JNU_GetStringPlatformChars(env, file, NULL);
            _tcsncpy(fileBuffer, tmp, bufferLimit - 2); // the fileBuffer is double null terminated string
            JNU_ReleaseStringPlatformChars(env, file, tmp);
        } else {
            fileBuffer[0] = _T('\0');
        }

        ofn.lStructSize = sizeof(ofn);
        ofn.lpstrFilter = s_fileFilterString;
        ofn.nFilterIndex = 1;
        /*
          Fix for 6488834.
          To disable Win32 native parent modality we have to set
          hwndOwner field to either NULL or some hidden window. For
          parentless dialogs we use NULL to show them in the taskbar,
          and for all other dialogs AwtToolkit's HWND is used.
        */
        if (awtParent != NULL)
        {
            ofn.hwndOwner = AwtToolkit::GetInstance().GetHWnd();
        }
        else
        {
            ofn.hwndOwner = NULL;
        }
        ofn.lpstrFile = fileBuffer;
        ofn.nMaxFile = bufferLimit;
        ofn.lpstrTitle = titleBuffer;
        ofn.lpstrInitialDir = directoryBuffer;
        ofn.Flags = OFN_LONGNAMES | OFN_OVERWRITEPROMPT | OFN_HIDEREADONLY |
                    OFN_ENABLEHOOK | OFN_EXPLORER | OFN_ENABLESIZING;
        fileFilter = env->GetObjectField(peer,
        AwtFileDialog::fileFilterID);
        if (!JNU_IsNull(env,fileFilter)) {
            ofn.Flags |= OFN_ENABLEINCLUDENOTIFY;
        }
        ofn.lCustData = (LPARAM)peer;
        ofn.lpfnHook = (LPOFNHOOKPROC)FileDialogHookProc;

        if (multipleMode == JNI_TRUE) {
            ofn.Flags |= OFN_ALLOWMULTISELECT;
        }

        // Save current directory, so we can reset if it changes.
        currentDirectory = new TCHAR[MAX_PATH+1];

        VERIFY(::GetCurrentDirectory(MAX_PATH, currentDirectory) > 0);

        mode = env->GetIntField(target, AwtFileDialog::modeID);

        AwtDialog::CheckInstallModalHook();

        // show the Win32 file dialog
        if (mode == java_awt_FileDialog_LOAD) {
            result = ::GetOpenFileName(&ofn);
        } else {
            result = ::GetSaveFileName(&ofn);
        }
        // Fix for 4181310: FileDialog does not show up.
        // If the dialog is not shown because of invalid file name
        // replace the file name by empty string.
        if (!result) {
            dlgerr = ::CommDlgExtendedError();
            if (dlgerr == FNERR_INVALIDFILENAME) {
                _tcscpy_s(fileBuffer, bufferLimit, TEXT(""));
                if (mode == java_awt_FileDialog_LOAD) {
                    result = ::GetOpenFileName(&ofn);
                } else {
                    result = ::GetSaveFileName(&ofn);
                }
            }
        }

        AwtDialog::CheckUninstallModalHook();

        DASSERT(env->GetLongField(peer, AwtComponent::hwndID) == 0L);

        AwtDialog::ModalActivateNextWindow(NULL, target, peer);

        VERIFY(::SetCurrentDirectory(currentDirectory));

        // Report result to peer.
        if (result) {
            jint length = multipleMode
                    ? (jint)GetBufferLength(ofn.lpstrFile, ofn.nMaxFile)
                    : (jint)_tcslen(ofn.lpstrFile);
            jcharArray jnames = env->NewCharArray(length);
            if (jnames == NULL) {
                throw std::bad_alloc();
            }
            env->SetCharArrayRegion(jnames, 0, length, (jchar*)ofn.lpstrFile);

            env->CallVoidMethod(peer, AwtFileDialog::handleSelectedMID, jnames);
            env->DeleteLocalRef(jnames);
        } else {
            env->CallVoidMethod(peer, AwtFileDialog::handleCancelMID);
        }
        DASSERT(!safe_ExceptionOccurred(env));
    } catch (...) {

        env->DeleteLocalRef(target);
        env->DeleteLocalRef(parent);
        env->DeleteLocalRef(title);
        env->DeleteLocalRef(directory);
        env->DeleteLocalRef(file);
        env->DeleteLocalRef(fileFilter);
        env->DeleteGlobalRef(peer);

        delete[] currentDirectory;
        if (ofn.lpstrFile)
            delete[] ofn.lpstrFile;
        throw;
    }

    env->DeleteLocalRef(target);
    env->DeleteLocalRef(parent);
    env->DeleteLocalRef(title);
    env->DeleteLocalRef(directory);
    env->DeleteLocalRef(file);
    env->DeleteLocalRef(fileFilter);
    env->DeleteGlobalRef(peer);

    delete[] currentDirectory;
    if (ofn.lpstrFile)
        delete[] ofn.lpstrFile;
}
コード例 #22
0
ファイル: TrayNotifyIcon.cpp プロジェクト: uvbs/SupportCenter
BOOL CTrayNotifyIcon::SetBalloonDetails(LPCTSTR pszBalloonText, LPCTSTR pszBalloonCaption, BalloonStyle style, UINT nTimeout, HICON hUserIcon, BOOL bNoSound)
{
    if (!m_bCreated)
        return FALSE;

    //Validate our parameters
    ATLASSERT(GetShellVersion() >= 5); //Only supported on Shell v5 or later
#ifdef _DEBUG
    NOTIFYICONDATA_2 dummy;
    DBG_UNREFERENCED_LOCAL_VARIABLE(dummy);
    ATLASSERT(_tcslen(pszBalloonText) < sizeof(dummy.szInfo)/sizeof(TCHAR));
    ATLASSERT(_tcslen(pszBalloonCaption) < sizeof(dummy.szInfoTitle)/sizeof(TCHAR));
#endif

    //Call the Shell_NotifyIcon function
    m_NotifyIconData.uFlags = NIF_INFO;
#if (_MSC_VER >= 1400)
    _tcscpy_s(m_NotifyIconData.szInfo, sizeof(m_NotifyIconData.szInfo)/sizeof(TCHAR), pszBalloonText);
    _tcscpy_s(m_NotifyIconData.szInfoTitle, sizeof(m_NotifyIconData.szInfoTitle)/sizeof(TCHAR), pszBalloonCaption);
#else
    _tcscpy(m_NotifyIconData.szInfo, pszBalloonText);
    _tcscpy(m_NotifyIconData.szInfoTitle, pszBalloonCaption);
#endif
    m_NotifyIconData.uTimeout = nTimeout;
    switch (style)
    {
    case Warning:
    {
        m_NotifyIconData.dwInfoFlags = NIIF_WARNING;
        break;
    }
    case Error:
    {
        m_NotifyIconData.dwInfoFlags = NIIF_ERROR;
        break;
    }
    case Info:
    {
        m_NotifyIconData.dwInfoFlags = NIIF_INFO;
        break;
    }
    case None:
    {
        m_NotifyIconData.dwInfoFlags = NIIF_NONE;
        break;
    }
    case User:
    {
        ATLASSERT(hUserIcon != NULL); //You forget to provide a user icon
        m_NotifyIconData.dwInfoFlags = NIIF_USER;
        m_NotifyIconData.hIcon = hUserIcon;
        break;
    }
    default:
    {
        ATLASSERT(FALSE);
        break;
    }
    }
    if (bNoSound)
        m_NotifyIconData.dwInfoFlags |= NIIF_NOSOUND;

    return Shell_NotifyIcon(NIM_MODIFY, reinterpret_cast<PNOTIFYICONDATA>(&m_NotifyIconData));
}
コード例 #23
0
BOOL CNTEventLogSource::SetStringArrayIntoRegistry(ATL::CRegKey& key, LPCTSTR lpszEntry, const CNTServiceStringArray& array, DWORD* pLastError)
{   
  //Validate our input parameters
  ATLASSERT(lpszEntry != NULL);

  //Work out the size of the buffer we will need
#ifdef CNTSERVICE_MFC_EXTENSIONS
  int nSize = 0;
  INT_PTR nStrings = array.GetSize();
  for (INT_PTR i=0; i<nStrings; i++)
    nSize += array.GetAt(i).GetLength() + 1; //1 extra for each NULL terminator
#else
  CNTServiceStringArray::size_type nSize = 0;
  CNTServiceStringArray::size_type nStrings = array.size();
  for (CNTServiceStringArray::size_type i=0; i<nStrings; i++)
    nSize += array[i].length() + 1; //1 extra for each NULL terminator
#endif

  //Need one second NULL for the double NULL at the end
  nSize++;

  //Allocate some memory for the API
  ATL::CHeapPtr<TCHAR> lpBuffer;
  if (!lpBuffer.Allocate(nSize))
  {
    SetLastError(ERROR_OUTOFMEMORY);
    if (pLastError)
      *pLastError = ERROR_OUTOFMEMORY;
    return FALSE;
  }

  //Now copy the strings into the buffer
  LPTSTR lpszString = lpBuffer.m_pData;
#ifdef CNTSERVICE_MFC_EXTENSIONS
  int nCurOffset = 0;
  for (INT_PTR i=0; i<nStrings; i++)
#else
  CNTServiceStringArray::size_type nCurOffset = 0;
  for (CNTServiceStringArray::size_type i=0; i<nStrings; i++)
#endif
  {
    const CNTServiceString& sText = array[i];
  #ifdef CNTSERVICE_MFC_EXTENSIONS
    int nCurrentStringLength = sText.GetLength();
    _tcscpy_s(&lpszString[nCurOffset], nCurrentStringLength+1, sText);
  #else
    CNTServiceString::size_type nCurrentStringLength = sText.length();
    _tcscpy_s(&lpszString[nCurOffset], nCurrentStringLength+1, sText.c_str());
  #endif
    nCurOffset += (nCurrentStringLength + 1);
  }
  //Don't forgot to doubly NULL terminate
  lpszString[nCurOffset] = _T('\0');

  //Finally write it into the registry
  LONG lResult = key.SetMultiStringValue(lpszEntry, lpBuffer);
  BOOL bSuccess = (lResult == ERROR_SUCCESS);
  if (!bSuccess && pLastError)
    *pLastError = lResult;

  return bSuccess;
}
コード例 #24
0
ファイル: gkSceneBuilder.cpp プロジェクト: CheryJazz/gkEngine
//-----------------------------------------------------------------------
void gkSceneBuilder::exportChildInfo(IGameObject* child, CObjectNode* parentAuthor, IRapidXmlAuthor* author, uint32& counter)
{
	// name
	parentAuthor->AddAttribute(_T("Name"), child->getName().c_str());

	// meshname
	switch(child->getGameObjectSuperClass())
	{
		case eGOClass_GROUP:
			{
				parentAuthor->AddAttribute(_T("SuperClass"), _T("Group"));
			}
			break;
		case eGOClass_STATICMESH:
			{
				parentAuthor->AddAttribute(_T("SuperClass"), _T("Mesh"));

				// Mesh name to fullpath [12/30/2011 Kaiming]
				IGameObjectRenderLayer* pRenderLayer = child->getRenderLayer();
				if (pRenderLayer)
				{
					gkStdString relPath = gkGetGameRelativePath( pRenderLayer->getMesh()->getName());
					parentAuthor->AddAttribute(_T("MeshName"), relPath.c_str());
					relPath = pRenderLayer->getMaterialName();
					if (relPath.size() > 4)
					{
						TCHAR extension[10];
						_tcscpy_s(extension, 10, &(relPath.c_str()[relPath.size()-4]));
						if (_tcsicmp(extension, _T(".MTL")))
						{
							relPath += _T(".mtl");
						}
						relPath = gkGetGameRelativePath( relPath );
					}

					parentAuthor->AddAttribute(_T("MaterialName"), relPath.c_str());
				}


				IGameObjectPhysicLayer* pPhysicLayer = child->getPhysicLayer();
				if (pPhysicLayer)
				{
					parentAuthor->AddAttribute(_T("Physical"), "true");
				}
			}
			break;
		case eGOClass_LIGHT:
			{
				parentAuthor->AddAttribute(_T("SuperClass"), _T("Light"));

				IGameObjectLightLayer* pLightLayer = static_cast<IGameObjectLightLayer*>(child->getGameObjectLayer(eGL_LightLayer));

				parentAuthor->AddAttribute(_T("Color"), pLightLayer->getDiffuseColor());
				parentAuthor->AddAttribute(_T("Radius"), pLightLayer->getRadius());
				parentAuthor->AddAttribute(_T("FakeShadow"), pLightLayer->getFakeShadow());
				parentAuthor->AddAttribute(_T("GloabalShadow"), pLightLayer->getGlobalShadow());
			}
			break;

	}

	// matrix
	parentAuthor->SetTranslation(child->getPosition().x, child->getPosition().y, child->getPosition().z);
	parentAuthor->SetRotation(child->getOrientation().v.x, child->getOrientation().v.y, child->getOrientation().v.z, child->getOrientation().w);
	parentAuthor->SetScale(child->getScale().x, child->getScale().y, child->getScale().z);

	counter++;
	// child situation
	uint32 childcount = child->getChildCount();
	for(uint32 i=0; i < childcount; ++i)
	{
		if (child->getChild(i) && child->getChild(i)->getGameObjectSuperClass() != eGOClass_SYSTEM)
		{
			// write author nodes [12/4/2011 Kaiming]
			CObjectNode* authorNode = author->createObjectNode( parentAuthor );
			exportChildInfo(child->getChild(i), authorNode, author, counter);
		}
	}


}
コード例 #25
0
ファイル: Profile.cpp プロジェクト: YaoXuanZhi/win32-netmon
BOOL NetmonProfile::GetAdapter(TCHAR *szAdapter, int cchLen)
{
    _tcscpy_s(szAdapter, cchLen, _szAdapter);
    return TRUE;
}
コード例 #26
0
ファイル: gkSceneBuilder.cpp プロジェクト: CheryJazz/gkEngine
//-----------------------------------------------------------------------
void gkSceneBuilder::saveSceneToFile( const TCHAR* filename )
{
	float estTime = gEnv->pTimer->GetAsyncCurTime();

	IRapidXmlAuthor author;
	// initialize the doc [12/4/2011 Kaiming]
	author.initializeSceneWrite();

	CRapidXmlAuthorNode* head = author.createRapidXmlNode(_T("GameKnifeScene"));
	head->AddAttribute(_T("author"), _T("gkENGINE RapidXml Author"));
	head->AddAttribute(_T("version"), _T("1.0.0"));
	head->AddAttribute(_T("level"), filename);

	//////////////////////////////////////////////////////////////////////////
	// 导出地形
	ITerrianSystem* terrian = gEnv->p3DEngine->getTerrian();
	if (terrian)
	{
		CRapidXmlAuthorNode* terrianNode = author.createRapidXmlNode(_T("Terrian"));
		
		terrian->Save( terrianNode );
	}

	CRapidXmlAuthorNode* root = author.createRapidXmlNode(_T("SceneObjects"));
	
	uint32 count = gEnv->pGameObjSystem->getGameObjectCount();
	uint32 realcount = 0;
	uint32 fullcount = 0;
	for( uint32 i=0; i < count; ++i)
	{
		IGameObject* go = gEnv->pGameObjSystem->GetGameObjectById(i);
		if (go && go->getParent() == NULL && go->getGameObjectSuperClass() != eGOClass_SYSTEM)
		{
			CObjectNode* authorNode = author.createObjectNode(root);
			exportChildInfo(go, authorNode, &author, fullcount);
			realcount++;
			fullcount++;
		}
	}
	root->AddAttribute(_T("TopLevelCount"), (int)realcount);
	root->AddAttribute(_T("AllCount"), (int)fullcount);


	author.writeToFile(filename);

	// write the same name tod file [1/8/2012 Kaiming]
	gkStdString relScenePath = gkGetGameRelativePath(filename);

	TCHAR todfilename[MAX_PATH];
	_tcscpy_s(todfilename, relScenePath.c_str());
	todfilename[_tcslen(todfilename) - 4] = 0;
	_tcscat_s(todfilename, _T(".tod"));

	gEnv->p3DEngine->getTimeOfDay()->saveTODSequence(todfilename);

	estTime = gEnv->pTimer->GetAsyncCurTime() - estTime;
// 	gkLogMessage(_T("Scene [ %s ] saved successfully. Use %.4f seconds."), filename, estTime);
// 	gkLogMessage(_T("TOD [ %s ] saved successfully. Use %.4f seconds."), todfilename, estTime);


}
コード例 #27
0
ファイル: Profile.cpp プロジェクト: YaoXuanZhi/win32-netmon
void Profile::Init(const TCHAR *szFileName, const TCHAR *szSectionName)
{
    _tcscpy_s(_szFileName, MAX_PATH, szFileName);
    _tcscpy_s(_szSectionName, MAX_PATH, szSectionName);
}
コード例 #28
0
ファイル: gkSceneBuilder.cpp プロジェクト: CheryJazz/gkEngine
//-----------------------------------------------------------------------
void gkSceneBuilder::buildSceneFromFile( gkStdString filename,bool syncMode, bool bPak , Vec3 position, uint8 uRenderLayer, bool builtIn)
{
	HRESULT hr = S_OK;

	m_bBuiltInPak = builtIn;
	m_uRenderLayer = uRenderLayer;

	if (!builtIn)
	{
		// 		gkStdString relScenePath = gkGetGameRelativePath(wszPath);
		// 
		TCHAR todfilename[MAX_PATH];
		_tcscpy_s(todfilename, filename.c_str());
		todfilename[_tcslen(todfilename) - 4] = 0;
		_tcscat_s(todfilename, _T(".tod"));

		IRapidXmlParser todParser;
		todParser.initializeReading(todfilename);
		if (!todParser.getRootXmlNode())
		{
			return;
		}
		gEnv->p3DEngine->getTimeOfDay()->loadTODSequence(todParser.getRootXmlNode(), true);
		todParser.finishReading();


		// 


		//		gkLogMessage( _T("gkSceneBuilder::TodFile Loaded. [%s]"), filename.c_str() );
	}

	ms_nAllNodeCount = 0;
	ms_nLoadedNodeCount = 0;

	// if not syncMode, we should clear the cache
	if (!syncMode)
	{
		m_currEntityList.clear();
		m_lastEntityList.clear();
	}

	// first drim to a pure filename [8/20/2011 Kaiming-Desktop]
// 	uint8 index = filename.find_last_of('\\') + 1;
// 	uint8 count = filename.length() - index;
// 	filename = filename.substr(index, count);
// 
// 	// 先在目录内查找名字 [9/18/2010 Kaiming-Desktop]
// 	TCHAR wszPath[MAX_PATH] = _T("");
// 	hr = gkFindFileRelativeGame(wszPath, MAX_PATH, filename.c_str());
// 	assert( hr == S_OK );

	// if not builtIn, load tod file [1/8/2012 Kaiming]



	gkLogMessage( _T("gkSceneBuilder::Creating: [%s] ..."), filename.c_str() );
	float nStartTime = gEnv->pTimer->GetAsyncCurTime();

	IRapidXmlParser sceneParser;
	sceneParser.initializeReading(filename.c_str());

	// 建立地形 [4/4/2013 Kaiming]
	CRapidXmlParseNode* terrianNode = sceneParser.getRootXmlNode(_T("Terrian"));
	if (terrianNode)
	{
		ITerrianSystem* terrian = gEnv->p3DEngine->createTerrian();
		terrian->Create( terrianNode );
	}

	CRapidXmlParseNode* rootNode = sceneParser.getRootXmlNode(_T("SceneObjects"));

	rootNode->GetAttribute(_T("AllCount"), ms_nAllNodeCount);

	CRapidXmlParseNode* firstObject = rootNode->getChildNode(_T("gkObject"));

	if (firstObject)
	{
		// parsing one by one
		parseSceneObject(firstObject);	
	}
	sceneParser.finishReading();

	gEnv->pSystem->updateProgress( 100 );

	removeEntitiesDeleted();

	float nTimeLoadFile = gEnv->pTimer->GetAsyncCurTime() - nStartTime;

	gkLogWarning( _T("gkSceneBuilder::Loaded: [%s], use %0.2f seconds. \n"), filename.c_str() , nTimeLoadFile );
}
コード例 #29
0
ファイル: Profile.cpp プロジェクト: YaoXuanZhi/win32-netmon
BOOL NetmonProfile::Load(const TCHAR *szDefaultAdapter)
{
    TCHAR szCurrentExe[MAX_PATH]={ 0 };
    TCHAR szCurrentDir[MAX_PATH]={ 0 };
    TCHAR szProfile[MAX_PATH]={ 0 };
    TCHAR *pFilePart;
    TCHAR szHiddenProcesses[1000];

    // Get full path name of Netmon.exe
    GetModuleFileName(0, szCurrentExe, MAX_PATH);

    // Get base directory
    GetFullPathName(szCurrentExe, MAX_PATH, szCurrentDir, &pFilePart);
    *pFilePart = TEXT('\0');

    // Get full path name of Netmon.ini
    _tcscpy_s(szProfile, MAX_PATH, szCurrentDir);
    _tcscat_s(szProfile, MAX_PATH, _T("Netmon.ini"));

    // Init
    _pf.Init(szProfile, _T("Netmon Profile v1"));

    // Load preferences
    // If the key doesn't exist, a default value is written to the ini file
    if( _pf.GetString(_T("Adapter"), _szAdapter, 256) == FALSE )
    {
        SetAdapter(szDefaultAdapter);
    }

    if( _pf.GetString(_T("AutoStart"), _szAutoStart, MAX_PATH) == FALSE )
    {
        SetAutoStart(_T(""));
    }

    if( _pf.GetInt(_T("AutoCapture"), &_bAutoCapture) == FALSE )
    {
        SetAutoCapture(FALSE);
    }

    if( _pf.GetInt(_T("DtViewEnable"), &_bDtViewEnable) == FALSE )
    {
        SetDtViewEnable(FALSE);
    }

    if( _pf.GetInt(_T("DtViewMaxSpace"), &_iDtViewMaxSpace) == FALSE )
    {
        SetDtViewMaxSpace(0); // No limit
    }

    if( _pf.GetString(_T("HiddenProcess"), szHiddenProcesses, 1000) == FALSE)
    {
        SetHiddenProcesses(std::vector<int>());
    }
    else
    {
        int puid;
        int offset = 0;
        while (_stscanf_s(szHiddenProcesses + offset, _T("%d"), &puid) == 1)
        {
            _hiddenProcesses.push_back(puid);

            // Offset
            TCHAR buf[16];
            _stprintf_s(buf, 16, _T("%d"), puid);
            offset += _tcslen(buf) + 1;
        }
    }

    if( _pf.GetString(_T("Language"), _szLanguage, 64) == FALSE )
    {
        SetLanguage(_T("English"));
    }

    if( _pf.GetInt(_T("ShowHidden"), &_bShowHidden) == FALSE )
    {
        SetShowHidden(TRUE);
    }

    return TRUE;
}
コード例 #30
0
STDMETHODIMP HttpRequest::put_Url(BSTR newVal)
{
	ATLASSERT(newVal);
	if(IsValidURL(NULL,newVal,0)!=S_OK){
		ErrorMsgBox(0,_T("请求地址不合法!"));
		return S_OK;
	}

	DWORD dwSize=STRLEN_4K;
	if (!InternetCanonicalizeUrl(newVal,m_szUrl,&dwSize,ICU_BROWSER_MODE)){
		ErrorMsgBox(GetLastError(),_T("请求地址不合法或者长度太大:%s"));
		ZeroMemory(m_szUrl,sizeof(m_szUrl));
		return S_OK;
	}
	ZeroMemory(m_szUrl,sizeof(m_szUrl));
	_tcsncpy_s(m_szUrl,newVal,_tcslen(newVal));
	
	ZeroMemory(m_szUrlProtocol,sizeof(m_szUrlProtocol));
	ZeroMemory(m_szUrlHost,sizeof(m_szUrlHost));
	ZeroMemory(m_szUrlFile,sizeof(m_szUrlFile));
	m_usUrlPort=DEFAULT_HTTP_PORT;
	m_blUrlIsSSL=VARIANT_FALSE;

	if (!m_szUrl || _tcslen(m_szUrl)==0) return S_OK;

	//»ñÈ¡urlЭÒ鲿·Ö
	for(size_t i=0;i<sizeof(m_szUrl);i++){
		if (m_szUrl[i]==_T(':') || i>=sizeof(m_szUrlProtocol)) break;
		m_szUrlProtocol[i]=m_szUrl[i];
	}
	
	//ÊÇ·ñsslºÍsslĬÈ϶˿Ú
	if (_tcsicmp(m_szUrlProtocol,_T("https"))==0) {
		m_blUrlIsSSL=VARIANT_TRUE;
		if (m_usUrlPort==DEFAULT_HTTP_PORT) m_usUrlPort=DEFAULT_HTTPS_PORT;
	}

	//»ñÈ¡url¶Ë¿Ú²¿·Ö
	TCHAR* szPos1=_tcschr(m_szUrl+_tcslen(m_szUrlProtocol)+1,_T(':'));
	TCHAR* szPos2=_tcschr(m_szUrl+_tcslen(m_szUrlProtocol)+3,_T('/'));
	if (szPos1 && szPos2){
		TCHAR szPort[STRLEN_SMALL]={0};
		_tcsncpy_s(szPort,szPos1+1,szPos2-szPos1-1);
		
		TCHAR *stop;
		m_usUrlPort=(USHORT)_tcstoul(szPort,&stop,0);
	}
	
	//»ñÈ¡urlÖ÷»ú²¿·Ö
	int idx=0;
	for(size_t i=_tcslen(m_szUrlProtocol)+3;i<sizeof(m_szUrl);i++){
		if (m_szUrl[i]==_T(':') || m_szUrl[i]==_T('/')) break;
		m_szUrlHost[idx++]=m_szUrl[i];
	}
	
	//»ñÈ¡urlÎļþ²¿·Ö
	TCHAR* szPos3=_tcschr(m_szUrl+_tcslen(m_szUrlProtocol)+3,_T('/'));
	if(szPos3) _tcscpy_s(this->m_szUrlFile,szPos3);
	else this->m_szUrlFile[0]=_T('/');
	
	return S_OK;
}