예제 #1
0
파일: OS.cpp 프로젝트: penbor/jwebtop
			// 创建一个新进程,返回的数据为进程中主线程的id
			DWORD createSubProcess(LPTSTR subProcess, LPTSTR szCmdLine){
				std::wstring cmd;
				if (subProcess[0] == L'"'){// 如果url中已以双引号开头,那么这里就不再添加双引号
					cmd.append(subProcess);
				}
				else{// 把子进程用双引号包含起来,避免恶意程序问题
					cmd.append(L"\"");
					cmd.append(subProcess);
					cmd.append(L"\"");
				}
				cmd += L" "; cmd += szCmdLine;// 追加一个空格在命令行参数的前面,否则新进程的szCmdLine会取不到参数

				STARTUPINFO sui;
				ZeroMemory(&sui, sizeof(STARTUPINFO)); // 对一个内存区清零,最好用ZeroMemory, 它的速度要快于memset
				sui.cb = sizeof(STARTUPINFO);

				PROCESS_INFORMATION pi; // 保存了所创建子进程的信息
				//DWORD dwCreationFlags = DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
				DWORD dwCreationFlags = CREATE_NEW_PROCESS_GROUP;
				if (CreateProcess(NULL, LPTSTR(cmd.c_str()), // 第一个参数置空,可执行文件和命令行放到一起避免恶意程序问题
					NULL, NULL, FALSE,//句柄不继承 
					dwCreationFlags, //使用正常优先级 
					NULL, //使用父进程的环境变量 
					NULL, //指定工作目录 
					&sui, &pi))
				{
					CloseHandle(pi.hProcess); // 子进程的进程句柄
					CloseHandle(pi.hThread);  // 子进程的线程句柄,windows中进程就是一个线程的容器,每个进程至少有一个线程在执行
					return pi.dwThreadId;
				}
				//else{// else的处理主要是为了方便在VS环境下调试程序,因为VS下启动的程序默认的工作目录是$(ProjectDir),如果改为$(SolutionDir)$(Configuration)\则不需要else的处理
				//	TCHAR   szPath[1000];
				//	GetModuleFileName(NULL, szPath, MAX_PATH);
				//	std::wstring path(szPath);
				//	path = path.substr(0, path.find_last_of('\\') + 1);
				//	path += subProcess;
				//	if (CreateProcess(path.c_str(), LPTSTR(cmd.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &sui, &pi))
				//	{
				//		CloseHandle(pi.hProcess); // 子进程的进程句柄
				//		CloseHandle(pi.hThread);  // 子进程的线程句柄,windows中进程就是一个线程的容器,每个进程至少有一个线程在执行
				//		return pi.dwThreadId;
				//	}
				//}
				return 0;
			}
예제 #2
0
GLuint TextureMan::Get(string id)
{
	if (textures.find(id) == textures.end() && toLoad.find(id) != toLoad.end()) {
		string tex = MODELSPATH + toLoad[id] + TEXEXT;
		cout << "\t" << tex << "...";
		GLuint texId;

		bool success = NeHeLoadBitmap(LPTSTR(tex.c_str()), texId);
		if(!success)
		{
			cout << "Unsuccessful." << endl;
			return -1;
		}
		TextureMan::GetInstance()->Add(id, texId);
		cout << "DONE." << endl;
	}
	return textures[id];
}
//--------------------------------------------------------------------------------
BOOL CNTService::StartDispatcher()
	{
	AFX_MANAGE_STATE_IF_DLL

	// Default implementation creates a single threaded service.
	// Override this method and provide more table entries for
	// a multithreaded service (one entry for each thread).
	SERVICE_TABLE_ENTRY dispatchTable[] =
		{
			{ LPTSTR(GetServiceName()), (LPSERVICE_MAIN_FUNCTION)ServiceMain },
			{ 0, 0 }
		};

	if(! StartServiceCtrlDispatcher(dispatchTable))
		return false;

	return true;
	}
예제 #4
0
bool CSoundManager::add(LPTSTR filename, int *id)  //char *
{
	// Create a sound file
	CSound* newSound=NULL;

	HRESULT hr;

	// Load the wave file into a DirectSound buffer
	//if( FAILED( hr = Create( &newSound, filename, 0, GUID_NULL ) ) )
		//return FALSE;
	hr = Create( &newSound, LPTSTR(filename), 0, GUID_NULL );
	// Succeeded so add to our vector and fill id for return
	m_soundVector.push_back(newSound);

	*id=(int)m_soundVector.size()-1;

	return TRUE;
}
예제 #5
0
void COXTreeCal::FinishEdit(BOOL bOK)
{
	CString str;
	m_wndEdit.GetWindowText(str);
	// Send Notification to parent 
	LV_DISPINFO di;
	di.hdr.hwndFrom = GetParent()->m_hWnd;
	di.hdr.idFrom = GetDlgCtrlID();
	di.hdr.code = LVN_ENDLABELEDIT;
	di.item.mask = LVIF_TEXT;
	di.item.iItem = bOK ? m_iItem : -1;
	di.item.iSubItem = m_iSubItem;
	di.item.pszText = LPTSTR((LPCTSTR)str);
	di.item.cchTextMax = str.GetLength();
	GetParent()->GetParent()->SendMessage( WM_NOTIFY, GetParent()->GetDlgCtrlID(), 
		(LPARAM)&di );
	// and close window too
	DestroyWindow();
}
//
// AddThingToTree
// given a parent item and a thing pointer
// add the thing to three
HTREEITEM CThingTreeCtrl::AddThingToTree(HTREEITEM hParentItem, IThing *pThing	)
{
	CComBSTR bstrName;
	CString strName;
	long lID, lIcon;
	HTREEITEM hReturn = NULL;
	TV_INSERTSTRUCT tvInsert;
	TV_ITEM tvItem;
	HRESULT hr = S_OK;

	if (!pThing)
		return NULL;

	if (FAILED(hr = pThing->get_ID(&lID)))
		goto exit;

	if (FAILED(hr = pThing->get_Name(&bstrName.m_str)))
		goto exit;

//#ifdef _DEBUG
//	{
//		TRACE("CThingTreeCtrl::AddThingToTree %s \n", CString(bstrName));
//	}
//#endif

	lIcon = AssignIcon(pThing);

	tvItem.mask = TVIF_PARAM | TVIF_TEXT | TVIF_IMAGE | TVIF_SELECTEDIMAGE;
	strName = bstrName;
	tvItem.pszText = LPTSTR(LPCTSTR(strName));
	tvItem.lParam = lID;
	tvItem.iImage = tvItem.iSelectedImage = lIcon;

	tvInsert.hParent = hParentItem;
	tvInsert.hInsertAfter = TVI_LAST;
	tvInsert.item = tvItem;

	hReturn = m_treeCtrl.InsertItem(&tvInsert);

exit:

	return hReturn;
}
예제 #7
0
ThtiPage* TffdshowPageBase::addTI(TVINSERTSTRUCT *tvis, const TconfPages &pages, int *Iid)
{
    ThtiPage *htiPage = new ThtiPage(Iid, pages);
    htiPages.push_back(htiPage);
    HTREEITEM hti;
    if (tvis) {
        tvis->item.lParam = (LPARAM)htiPage;
        tvis->item.pszText = LPTSTR(pages[0]->dialogName());
        tvis->item.iImage = tvis->item.iSelectedImage = 0;
        hti = TreeView_InsertItem(htv, tvis);
    } else {
        hti = NULL;
    }
    for (TconfPages::iterator i = htiPage->begin(); i != htiPage->end(); i++) {
        (*i)->hti = hti;
    }
    htiPage->hti = hti;
    return htiPage;
}
예제 #8
0
void CListEditCtrl::OnKillFocus(CWnd* pNewWnd)
{	
	CEdit::OnKillFocus(pNewWnd);

	CString str;	GetWindowText(str);

	// Send Notification to parent of ListView ctrl	
	LV_DISPINFO lvDispInfo;
	lvDispInfo.hdr.hwndFrom = GetParent()->m_hWnd;
	lvDispInfo.hdr.idFrom = GetDlgCtrlID();	
	lvDispInfo.hdr.code = LVN_ENDLABELEDIT;
	lvDispInfo.item.mask = LVIF_TEXT;	
	lvDispInfo.item.iItem = m_iItem;
	lvDispInfo.item.iSubItem = m_iSubItem;
	lvDispInfo.item.pszText = m_bVK_ESCAPE ? NULL : LPTSTR((LPCTSTR)str);
	lvDispInfo.item.cchTextMax = str.GetLength();
	GetParent()->GetParent()->SendMessage( WM_NOTIFY, GetParent()->GetDlgCtrlID(),(LPARAM)&lvDispInfo);
	DestroyWindow();
}
예제 #9
0
void gxEditCell::SetListText()
{
    CString Text;
    GetWindowText (Text);

    // Send Notification to parent of ListView ctrl
    LV_DISPINFO dispinfo;
    dispinfo.hdr.hwndFrom = GetParent()->m_hWnd;
    dispinfo.hdr.idFrom = GetDlgCtrlID();
    dispinfo.hdr.code = LVN_ENDLABELEDIT;

    dispinfo.item.mask = LVIF_TEXT;
    dispinfo.item.iItem = Item;
    dispinfo.item.iSubItem = SubItem;
    dispinfo.item.pszText = bEscape ? NULL : LPTSTR ((LPCTSTR) Text);
    dispinfo.item.cchTextMax = Text.GetLength();

    GetParent()->GetParent()->SendMessage (WM_NOTIFY, GetParent()->GetDlgCtrlID(), (LPARAM) &dispinfo);
}
예제 #10
0
void CGrid::SendRemoveCharacterMsg(CObject* pLeavedObject)
{
	m_CharacterHashTable.SetPositionHead();
	CObject* pObject;
	while( (pObject = (CObject*)m_CharacterHashTable.GetData()) != NULL)
	{
		if(pLeavedObject->GetID() == pObject->GetID())
			continue;

		MSGBASE* message = 0;
		const DWORD messageLength = pObject->SetRemoveMsg(
			pLeavedObject->GetID(),
			message);
		g_Network.Send2Server(
			pLeavedObject->GetAgentNum(),
			LPTSTR(message),
			messageLength);
	}	
}
HRESULT CThingTreeCtrl::HandleOnModuleChanged(BSTR bstrName, long lHint, VARIANT varHintData)
{
	TV_INSERTSTRUCT tvInsert;
	TV_ITEM			tvItem;
	CString			strModuleName;
	HTREEITEM		hItem;

	strModuleName = bstrName;

	// the module has changed, find out which one
	if (lHint == moCreate)
	{
		// create a new module
		tvItem.mask = TVIF_PARAM | TVIF_TEXT;
		tvItem.pszText = LPTSTR(LPCTSTR(strModuleName));
		tvItem.lParam = -2;

		tvInsert.hParent = m_hModules;
		tvInsert.hInsertAfter = TVI_LAST;
		tvInsert.item = tvItem;

		hItem = m_treeCtrl.InsertItem(&tvInsert);

		// check to see if the module node is expanded
		// if not, expand it
		m_treeCtrl.Expand(m_hModules, TVE_EXPAND);
		m_treeCtrl.SortChildren(m_hModules);

		// select the module (as per bug #5044)
		m_treeCtrl.SelectItem(hItem);
	}
	if (lHint == moRemove)
	{
		// remove an existing module
		// find the module in the tree
		hItem = FindModuleByName(strModuleName);
		if (hItem)
			m_treeCtrl.DeleteItem(hItem);
	}
	
	return S_OK;
}
예제 #12
0
void CMSInfoDlg::InitData()
{
	// combobox
	m_cbServerSet.ResetContent();
	m_cbServerSet.AddString( L"All Server" );
	CServerSet* pServerSet = NULL;
	for( int i = 0; i < SERVERSETMNG->GetMaxServerSet(); ++i )
	{
		pServerSet = SERVERSETMNG->GetServerSet( i );
		if( pServerSet->m_bInit )
		{
			m_cbServerSet.AddString( pServerSet->m_sServerSetName );
		}
	}
	m_cbServerSet.SetCurSel( 0 );

	LPCTSTR tcolumn[7] = { L"State", L"ServerSet", L"ServerName", L"IP", L"Port", L"AutoPatch", L"PatchVersion" };
	int tcolumnsize[7] = { 90, 80, 80, 100, 50, 80, 120 };
	
	// listctrl column 설정
	LV_COLUMN lvcolumn;
	lvcolumn.mask = LVCF_FMT | LVCF_SUBITEM | LVCF_TEXT | LVCF_WIDTH;
	lvcolumn.fmt = LVCFMT_CENTER;
	for( i = 0; i < 7; ++i )
	{
		lvcolumn.iSubItem = i;
		lvcolumn.cx = tcolumnsize[i];
		lvcolumn.pszText = LPTSTR( tcolumn[i] );
		m_lcMSInfo.InsertColumn( i, &lvcolumn );
	}
	// style
	m_lcMSInfo.SetExtendedStyle( LVS_EX_FULLROWSELECT );
	// state image
	m_lcMSInfo.SetImageList( &m_StateImageList, LVSIL_STATE );

	UpdateListCtrl();

	SERVERSETMNG->DoMSStateAll( L"All Server" );
	SERVERSETMNG->DoQueryAutoPatchVersion( L"All Server" );	

	m_bInit = TRUE;
}
예제 #13
0
void CGrid::SendCurrentCharacterMsg(CObject* pNewObject)
{
	m_CharacterHashTable.SetPositionHead();
	
	while(CObject* const pObject = m_CharacterHashTable.GetData())
	{
		if(pNewObject->GetID() == pObject->GetID())
			continue;

		MSGBASE* message = 0;
		const DWORD messageLength = pObject->SetAddMsg(
			pNewObject->GetID(),
			FALSE,
			message);
		g_Network.Send2Server(
			pNewObject->GetAgentNum(),
			LPTSTR(message),
			messageLength);
	}	
}
예제 #14
0
void CInPlaceWinHotkey::OnKillFocus(CWnd* pNewWnd)
{
    CWinHotkeyCtrl::OnKillFocus(pNewWnd);

    CString str;
    GetWindowText(str);

    LV_DISPINFO dispinfo;
    dispinfo.hdr.hwndFrom = GetParent()->m_hWnd;
    dispinfo.hdr.idFrom = GetDlgCtrlID();
    dispinfo.hdr.code = LVN_ENDLABELEDIT;
    dispinfo.item.mask = LVIF_TEXT;
    dispinfo.item.iItem = m_iItem;
    dispinfo.item.iSubItem = m_iSubItem;
    dispinfo.item.pszText = m_bESC ? nullptr : LPTSTR((LPCTSTR)str);
    dispinfo.item.cchTextMax = str.GetLength();
    GetParent()->GetParent()->SendMessage(WM_NOTIFY, GetParent()->GetDlgCtrlID(), (LPARAM)&dispinfo);

    DestroyWindow();
}
예제 #15
0
STDMETHODIMP CExRichEditWindowless::QueryAcceptData(LPDATAOBJECT lpdataobj, CLIPFORMAT FAR *lpcfFormat,DWORD reco, BOOL fReally, HGLOBAL hMetaPict)
{
	if ( NULL == lpdataobj )
		return E_INVALIDARG;	

	HRESULT hr;
	FORMATETC formatEtc;
	STGMEDIUM stgMedium;

	UINT uFormat = m_uOwnOleClipboardFormat;
	if (0 == uFormat)
	{
		return E_FAIL;
	}
	SecureZeroMemory(&formatEtc, sizeof(FORMATETC));
	formatEtc.cfFormat = uFormat;
	formatEtc.dwAspect = DVASPECT_CONTENT;
	formatEtc.lindex = -1;
	formatEtc.ptd = NULL;
	formatEtc.tymed = TYMED_HGLOBAL;

	hr = lpdataobj->GetData(&formatEtc, &stgMedium);
	if (S_OK == hr)
	{
		LPTSTR pDest = LPTSTR(::GlobalLock(stgMedium.hGlobal));
		if (pDest != NULL)
		{
			ReplaceSel(CString(pDest),true);
			::GlobalUnlock(stgMedium.hGlobal);
			::ReleaseStgMedium( &stgMedium );
			return S_OK;
		}
		else
		{
			::ReleaseStgMedium( &stgMedium );
			return E_FAIL;
		}
	}
	return S_OK;  

}
예제 #16
0
void TffdshowPageBase::translate(void)
{
    Twindow::translate();
    for (ThtiPages::const_iterator hp = htiPages.begin(); hp != htiPages.end(); hp++)
        for (TconfPages::const_iterator i = (*hp)->begin(); i != (*hp)->end(); i++) {
            if ((*i)->m_hwnd) {
                (*i)->translate();
            }
            TVITEM ti;
            ti.hItem = (*i)->hti;
            ti.mask = TVIF_TEXT;
            ti.pszText = LPTSTR((*i)->dialogName());
            TreeView_SetItem(htv, &ti);
            if ((*i)->m_hwnd) {
                (*i)->cfg2dlg();
            }
        }
    if (comptrQ<IPropertyPageSiteFF> siteFF = pageSite) {
        siteFF->onTranslate();
    }
}
예제 #17
0
파일: ObjectMan.cpp 프로젝트: tygill/Racer
void ObjectMan::LoadTexture(string id, string name)
{
	string tex = MODELSPATH + name + TEXEXT;
	cout << "\t" << tex << "...";
	GLuint texId;

	if (TextureMan::GetInstance()->Get(id) != 0)
	{
		cout << "Previously loaded." << endl;
		return;
	}

	bool success = NeHeLoadBitmap(LPTSTR(tex.c_str()), texId);
	if(!success)
	{
		cout << "Unsuccessful." << endl;
		return;
	}
	TextureMan::GetInstance()->Add(id, texId);
	cout << "DONE." << endl;
}
예제 #18
0
void CInPlaceListBox::OnKillFocus(CWnd* pNewWnd) 
{
	CListBox::OnKillFocus(pNewWnd);
	
	CString str;
	GetWindowText(str);

	LV_DISPINFO dispinfo;
	dispinfo.hdr.hwndFrom = GetParent()->m_hWnd;
	dispinfo.hdr.idFrom = GetDlgCtrlID();
	dispinfo.hdr.code = LVN_ENDLABELEDIT;
	dispinfo.item.mask = LVIF_TEXT|LVIF_PARAM;
	dispinfo.item.iItem = m_iItem;
	dispinfo.item.iSubItem = m_iSubItem;
	dispinfo.item.pszText = m_bESC ? NULL : LPTSTR((LPCTSTR)str);
	dispinfo.item.cchTextMax = str.GetLength();
	dispinfo.item.lParam = GetCurSel();
	GetParent()->GetParent()->SendMessage(WM_NOTIFY, GetParent()->GetDlgCtrlID(), (LPARAM)&dispinfo);

	PostMessage(WM_CLOSE);
}
예제 #19
0
LRESULT CInPlaceSelect::OnChildLoseFocus(WPARAM wParam, LPARAM lParam)
{
	
	CString str;
	GetWindowText(str);
	
	// Send Notification to parent of ListView ctrl
	LV_DISPINFO dispinfo;
	dispinfo.hdr.hwndFrom = GetParent()->m_hWnd;
	dispinfo.hdr.idFrom = GetDlgCtrlID();
	dispinfo.hdr.code = LVN_ENDLABELEDIT;

	dispinfo.item.mask = LVIF_TEXT;
	dispinfo.item.iItem = m_iItem;
	dispinfo.item.iSubItem = m_iSubItem;
	dispinfo.item.pszText = m_bESC ? NULL : LPTSTR((LPCTSTR)str);
	dispinfo.item.cchTextMax = str.GetLength();

	GetParent()->GetParent()->SendMessage( WM_NOTIFY, GetParent()->GetDlgCtrlID(), (LPARAM)&dispinfo );
	PostMessage( WM_CLOSE );
	return(TRUE);
}
예제 #20
0
void TgenericPage::cfg2dlg(void)
{
    flags.clear();
    if (sup_gray(codecId)) {
        flags.push_back(std::make_tuple(_(IDC_LV_GENERIC,_l("Greyscale")),IDFF_enc_gray,1,false));
    }

    nostate=true;
    int iig=lvGetSelItem(IDC_LV_GENERIC);
    ListView_DeleteAllItems(hlv);
    for (Tflags::const_iterator f=flags.begin(); f!=flags.end(); f++) {
        LVITEM lvi;
        memset(&lvi,0,sizeof(lvi));
        lvi.mask=LVIF_TEXT|LVIF_PARAM;
        lvi.pszText=LPTSTR(std::get<NAME-1>(*f));
        lvi.lParam=LPARAM(&*f);
        lvi.iItem=100;
        int ii=ListView_InsertItem(hlv,&lvi);
        ListView_SetCheckState(hlv,ii,cfgGet(std::get<IDFF-1>(*f))&std::get<VAL-1>(*f));
    }
    lvSetSelItem(IDC_LV_GENERIC,iig);
    nostate=false;
}
예제 #21
0
void CComboInListView::OnKillFocus(CWnd* pNewWnd) 
{	
	int nIndex = GetCurSel();

	CComboBox::OnKillFocus(pNewWnd);

	CString str;	
	GetWindowText(str);
	// Send Notification to parent of ListView ctrl	
	LV_DISPINFO lvDispinfo;
	lvDispinfo.hdr.hwndFrom = GetParent()->m_hWnd;
	lvDispinfo.hdr.idFrom = GetDlgCtrlID();//that's us
	lvDispinfo.hdr.code = LVN_ENDLABELEDIT;
	lvDispinfo.item.mask = LVIF_TEXT | LVIF_PARAM;	
	lvDispinfo.item.iItem = m_iItem;
	lvDispinfo.item.iSubItem = m_iSubItem;
	lvDispinfo.item.pszText = m_bVK_ESCAPE ? NULL : LPTSTR((LPCTSTR)str);
	lvDispinfo.item.cchTextMax = str.GetLength();
	lvDispinfo.item.lParam = GetItemData(GetCurSel());
	if(nIndex!=CB_ERR)
		GetParent()->GetParent()->SendMessage(WM_NOTIFY, GetParent()->GetDlgCtrlID(), (LPARAM)&lvDispinfo);
	PostMessage(WM_CLOSE);
	
}
예제 #22
0
void CServiceControl::DeregisterApplicationLog( LPCTSTR ServiceName )
{
	TCHAR szKey[256];
	_tcscpy_s(szKey, _countof(szKey), gszAppRegKey);
	_tcscat_s(szKey, _countof(szKey), ServiceName);
	HKEY hKey = 0;
	LONG lRet = ERROR_SUCCESS;

	lRet = ::RegDeleteKey(HKEY_LOCAL_MACHINE, szKey);

	// now we have to delete the application from the "Sources" value too.
	lRet =	::RegOpenKeyEx(
		HKEY_LOCAL_MACHINE,	// handle of open key
		gszAppRegKey,		// address of name of subkey to open
		0,					// reserved
		KEY_ALL_ACCESS,		// security access mask
		&hKey				// address of handle of open key
		);

	if( lRet == ERROR_SUCCESS )
	{
		DWORD dwSize;

		// retrieve the size of the needed value
		lRet =	::RegQueryValueEx(
			hKey,			// handle of key to query
			TEXT("Sources"),// address of name of value to query
			0,				// reserved
			0,				// address of buffer for value type
			0,				// address of data buffer
			&dwSize			// address of data buffer size
			);

		if( lRet == ERROR_SUCCESS ) {
			DWORD dwType;

			DWORD dwAllocSize = dwSize + 2 * sizeof(TCHAR); // need to ensure that value is NULL-terminated
			LPBYTE Buffer = LPBYTE(::GlobalAlloc(GPTR, dwAllocSize));
			LPBYTE NewBuffer = LPBYTE(::GlobalAlloc(GPTR, dwAllocSize));

			lRet =	::RegQueryValueEx(
				hKey,			// handle of key to query
				TEXT("Sources"),// address of name of value to query
				0,				// reserved
				&dwType,		// address of buffer for value type
				Buffer,			// address of data buffer
				&dwSize			// address of data buffer size
				);
			if( lRet == ERROR_SUCCESS ) {

				// check whether this service is already a known source
				register LPTSTR p = LPTSTR(Buffer);
				register LPTSTR pNew = LPTSTR(NewBuffer);

				// check that value is terminated with 2 zeroes.
				int tchar_count = dwSize / sizeof(TCHAR);
				if (tchar_count < 2 || p[tchar_count - 1] != 0 || p[tchar_count - 2] != 0)
					dwSize += 2 * sizeof(TCHAR);

				BOOL bNeedSave = FALSE;	// assume the value is already correct
				for(; *p; p += _tcslen(p)+1) {
					// except ourself: copy the source string into the destination
					if( _tcscmp(p, ServiceName) != 0 ) {
						_tcsncpy(pNew, p, dwSize/sizeof(TCHAR) - (pNew - LPTSTR(NewBuffer)));
						pNew += _tcslen(pNew)+1;
					} else {
						bNeedSave = TRUE;		// *this* application found
						dwSize -= sizeof(TCHAR)*(_tcslen(p)+1);	// new size of value
					}
				}
				if( bNeedSave ) {
					// OK - now store the modified value back into the
					// registry.
					lRet =	::RegSetValueEx(
						hKey,			// handle of key to set value for
						TEXT("Sources"),// address of value to set
						0,				// reserved
						dwType,			// flag for value type
						NewBuffer,		// address of value data
						dwSize			// size of value data
						);
				}
			}

			::GlobalFree(HGLOBAL(Buffer));
			::GlobalFree(HGLOBAL(NewBuffer));
		}

		::RegCloseKey(hKey);
	}
}
예제 #23
0
void CServiceControl::RegisterApplicationLog( LPCTSTR ServiceName, LPCTSTR lpszFileName )
{
	DWORD dwTypes = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE;
	TCHAR szKey[256];
	_tcscpy_s(szKey, _countof(szKey), gszAppRegKey);
	_tcscat_s(szKey, _countof(szKey), ServiceName);

	HKEY hKey = 0;
	LONG lRet = ERROR_SUCCESS;

	// Create a key for that application and insert values for
	// "EventMessageFile" and "TypesSupported"
	if( ::RegCreateKey(HKEY_LOCAL_MACHINE, szKey, &hKey) == ERROR_SUCCESS ) {
		lRet =	::RegSetValueEx(
			hKey,						// handle of key to set value for
			TEXT("EventMessageFile"),	// address of value to set
			0,							// reserved
			REG_EXPAND_SZ,				// flag for value type
			(CONST BYTE*)lpszFileName,	// address of value data
			sizeof(TCHAR)*(_tcslen(lpszFileName) + 1)	// size of value data
			);

		// Set the supported types flags.
		lRet =	::RegSetValueEx(
			hKey,					// handle of key to set value for
			TEXT("TypesSupported"),	// address of value to set
			0,						// reserved
			REG_DWORD,				// flag for value type
			(CONST BYTE*)&dwTypes,	// address of value data
			sizeof(DWORD)			// size of value data
			);
		::RegCloseKey(hKey);
	}

	// Add the service to the "Sources" value

	lRet =	::RegOpenKeyEx(
		HKEY_LOCAL_MACHINE,	// handle of open key
		gszAppRegKey,		// address of name of subkey to open
		0,					// reserved
		KEY_ALL_ACCESS,		// security access mask
		&hKey				// address of handle of open key
		);
	if( lRet == ERROR_SUCCESS ) {
		DWORD dwSize;

		// retrieve the size of the needed value
		lRet =	::RegQueryValueEx(
			hKey,			// handle of key to query
			TEXT("Sources"),// address of name of value to query
			0,				// reserved
			0,				// address of buffer for value type
			0,				// address of data buffer
			&dwSize			// address of data buffer size
			);

		if( lRet == ERROR_SUCCESS ) {
			DWORD dwType;

			DWORD  dwAllocSize = dwSize + sizeof(TCHAR)*(_tcslen(ServiceName)+1)
						+ 2*sizeof(TCHAR); // RegQueryValueEx may return non null-terminated string

			LPBYTE Buffer = LPBYTE(::GlobalAlloc(GPTR, dwAllocSize)); // note: allocated mem is zeroed

			lRet =	::RegQueryValueEx(
				hKey,			// handle of key to query
				TEXT("Sources"),// address of name of value to query
				0,				// reserved
				&dwType,		// address of buffer for value type
				Buffer,			// address of data buffer
				&dwSize			// address of data buffer size
				);
			if( lRet == ERROR_SUCCESS ) {

				register LPTSTR p = LPTSTR(Buffer);

				// check that value is terminated with 2 zeroes. Also need prevent growth of key-size.
				// note: allocated buf was zeroed
				int tchar_count = dwSize / sizeof(TCHAR);
				DWORD dwNewSize = dwSize + sizeof(TCHAR)*(_tcslen(ServiceName)+1);
				if (tchar_count < 2 || p[tchar_count - 1] != 0 || p[tchar_count - 2] != 0)
					dwNewSize += 2 * sizeof(TCHAR);

				// check whether this service is already a known source
				for(; *p; p += _tcslen(p)+1 ) {
					if( _tcscmp(p, ServiceName) == 0 )
						break;
				}
				if( ! * p ) {
					// We're standing at the end of the stringarray
					// and the service does still not exist in the "Sources".
					// Now insert it at this point.
					// Note that we have already enough memory allocated
					// (see GlobalAlloc() above). We also don't need to append
					// an additional '\0'. This is done in GlobalAlloc() above
					// too.
					_tcsncpy(p, ServiceName, dwNewSize/sizeof(TCHAR) - (p - (LPTSTR)Buffer));

					// OK - now store the modified value back into the
					// registry.
					lRet =	::RegSetValueEx(
						hKey,			// handle of key to set value for
						TEXT("Sources"),// address of value to set
						0,				// reserved
						dwType,			// flag for value type
						Buffer,			// address of value data
						dwNewSize		// size of value data
						);
				}
			}

			::GlobalFree(HGLOBAL(Buffer));
		}

		::RegCloseKey(hKey);
	}
}
예제 #24
0
void
CNdasDeviceMenu::AppendUnitDeviceMenuItem(
	ndas::UnitDevicePtr pUnitDevice,
	HMENU hMenu,
	PBYTE pPartStatus)
{
	CMenuHandle menu = hMenu;
	CMenuItemInfo mii;
	CString strText;
	BOOL fSuccess = FALSE;

	CMenuItemInfo sep;
	sep.fMask = MIIM_TYPE;
	sep.fType = MFT_SEPARATOR;

	mii.fMask = MIIM_ID | MIIM_STRING | MIIM_DATA | MIIM_STATE;
	mii.fState = MFS_ENABLED;
	mii.dwItemData = 
		((WORD) pUnitDevice->GetSlotNo()) |
		(((WORD) pUnitDevice->GetUnitNo()) << 16);

	NDAS_LOGICALDEVICE_ID logDeviceId = pUnitDevice->GetLogicalDeviceId();
	ndas::LogicalDevicePtr pLogDevice;
	if (!ndas::FindLogicalDevice(pLogDevice, logDeviceId)) 
	{
		pSetDeviceStatusMenuItem(menu, IDS_DEVMST_ERROR);
		if (pUnitDevice->GetStatus() == NDAS_UNITDEVICE_STATUS_ERROR)
		{
			*pPartStatus = NDSI_PART_ERROR;
		}
		return;
	}

	pLogDevice->UpdateStatus();
	pLogDevice->UpdateInfo();

	mii.dwItemData = pLogDevice->GetLogicalDeviceId();

	NDAS_LOGICALDEVICE_STATUS lstatus = pLogDevice->GetStatus();

	if (NDAS_LOGICALDEVICE_STATUS_MOUNTED == lstatus ||
		NDAS_LOGICALDEVICE_STATUS_UNMOUNT_PENDING == lstatus) 
	{

		if (pLogDevice->GetMountedAccess() & GENERIC_WRITE) 
		{
			*pPartStatus = NDSI_PART_MOUNTED_RW;
			pSetDeviceStatusMenuItem(menu, IDS_DEVMST_MOUNTED_RW);
		}
		else 
		{
			*pPartStatus = NDSI_PART_MOUNTED_RO;
			pSetDeviceStatusMenuItem(menu, IDS_DEVMST_MOUNTED_RO);
		}
		if (pLogDevice->IsContentEncrypted())
		{
			*pPartStatus |= NDSI_PART_CONTENT_IS_ENCRYPTED;
		}

		ATLVERIFY(strText.LoadString(IDR_NDD_UNMOUNT));

		mii.wID = IDR_NDD_UNMOUNT;
		mii.dwTypeData = LPTSTR(LPCTSTR(strText));

		if (NDAS_LOGICALDEVICE_STATUS_UNMOUNT_PENDING == lstatus) 
		{
			mii.fState = MFS_DISABLED;
		}

		ATLVERIFY(menu.InsertMenuItem(0xFFFF, TRUE, &mii));
		ATLVERIFY(menu.InsertMenuItem(0xFFFF, TRUE, &sep));

	}
	else if (NDAS_LOGICALDEVICE_STATUS_UNMOUNTED == lstatus ||
		NDAS_LOGICALDEVICE_STATUS_MOUNT_PENDING == lstatus) 
	{
		*pPartStatus = NDSI_PART_UNMOUNTED;
		if (pLogDevice->IsContentEncrypted())
		{
			*pPartStatus |= NDSI_PART_CONTENT_IS_ENCRYPTED;
		}

		pSetDeviceStatusMenuItem(menu, IDS_DEVMST_CONNECTED);

		// push the status
		UINT fSavedState = mii.fState;

		ATLVERIFY(strText.LoadString(IDR_NDD_MOUNT_RO));

		mii.wID = IDR_NDD_MOUNT_RO;
		mii.dwTypeData = LPTSTR(LPCTSTR(strText));
		mii.fState = (pLogDevice->GetGrantedAccess() & GENERIC_READ) ?
			MFS_ENABLED : MFS_DISABLED;

		if (NDAS_LOGICALDEVICE_STATUS_MOUNT_PENDING == lstatus) 
		{
			mii.fState = MFS_DISABLED;
		}

		ATLVERIFY(menu.InsertMenuItem(0xFFFF, TRUE, &mii));

		ATLVERIFY(strText.LoadString(IDR_NDD_MOUNT_RW));

		mii.wID = IDR_NDD_MOUNT_RW;
		mii.dwTypeData = LPTSTR(LPCTSTR(strText));
		mii.fState = (pLogDevice->GetGrantedAccess() & GENERIC_WRITE) ?
			MFS_ENABLED : MFS_DISABLED;

		if (NDAS_LOGICALDEVICE_STATUS_MOUNT_PENDING == lstatus) 
		{
			mii.fState = MFS_DISABLED;
		}

		ATLVERIFY(menu.InsertMenuItem(0xFFFF, TRUE, &mii));

		// pop the status;
		mii.fState = fSavedState;

		ATLVERIFY(menu.InsertMenuItem(0xFFFF, TRUE, &sep));

	} 
	else if (NDAS_LOGICALDEVICE_STATUS_NOT_INITIALIZED == lstatus) 
	{
		// not used
		*pPartStatus = NDSI_PART_UNMOUNTED;
	}
	else if (NDAS_LOGICALDEVICE_STATUS_UNKNOWN == lstatus) 
	{
		// not used
		*pPartStatus = NDSI_PART_UNMOUNTED;
	}
	else 
	{
		ATLASSERT(FALSE);
	}
}
예제 #25
0
void CView::OnFilePrint()
{
	// get default print info
	CPrintInfo printInfo;
	ASSERT(printInfo.m_pPD != NULL);    // must be set

	if (LOWORD(GetCurrentMessage()->wParam) == ID_FILE_PRINT_DIRECT)
	{
		CCommandLineInfo* pCmdInfo = AfxGetApp()->m_pCmdInfo;

		if (pCmdInfo != NULL)
		{
			if (pCmdInfo->m_nShellCommand == CCommandLineInfo::FilePrintTo)
			{
				printInfo.m_pPD->m_pd.hDC = ::CreateDC(pCmdInfo->m_strDriverName,
					pCmdInfo->m_strPrinterName, pCmdInfo->m_strPortName, NULL);
				if (printInfo.m_pPD->m_pd.hDC == NULL)
				{
					AfxMessageBox(AFX_IDP_FAILED_TO_START_PRINT);
					return;
				}
			}
		}

		printInfo.m_bDirect = TRUE;
	}

	if (OnPreparePrinting(&printInfo))
	{
		// hDC must be set (did you remember to call DoPreparePrinting?)
		ASSERT(printInfo.m_pPD->m_pd.hDC != NULL);

		// gather file to print to if print-to-file selected
		CString strOutput;
		if (printInfo.m_pPD->m_pd.Flags & PD_PRINTTOFILE && !printInfo.m_bDocObject)
		{
			// construct CFileDialog for browsing
			CString strDef(MAKEINTRESOURCE(AFX_IDS_PRINTDEFAULTEXT));
			CString strPrintDef(MAKEINTRESOURCE(AFX_IDS_PRINTDEFAULT));
			CString strFilter(MAKEINTRESOURCE(AFX_IDS_PRINTFILTER));
			CString strCaption(MAKEINTRESOURCE(AFX_IDS_PRINTCAPTION));
			CFileDialog dlg(FALSE, strDef, strPrintDef,
				OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT, strFilter, NULL, 0);
			dlg.m_ofn.lpstrTitle = strCaption;

			if (dlg.DoModal() != IDOK)
				return;

			// set output device to resulting path name
			strOutput = dlg.GetPathName();
		}

		// set up document info and start the document printing process
		CString strTitle;
		CDocument* pDoc = GetDocument();
		if (pDoc != NULL)
			strTitle = pDoc->GetTitle();
		else
			EnsureParentFrame()->GetWindowText(strTitle);
		DOCINFO docInfo;
		memset(&docInfo, 0, sizeof(DOCINFO));
		docInfo.cbSize = sizeof(DOCINFO);
		docInfo.lpszDocName = strTitle;
		CString strPortName;
		if (strOutput.IsEmpty())
		{
			docInfo.lpszOutput = NULL;
			strPortName = printInfo.m_pPD->GetPortName();
		}
		else
		{
			docInfo.lpszOutput = strOutput;
			AfxGetFileTitle(strOutput,
				strPortName.GetBuffer(_MAX_PATH), _MAX_PATH);
		}

		// setup the printing DC
		CDC dcPrint;
		if (!printInfo.m_bDocObject)
		{
			dcPrint.Attach(printInfo.m_pPD->m_pd.hDC);  // attach printer dc
			dcPrint.m_bPrinting = TRUE;
		}
		OnBeginPrinting(&dcPrint, &printInfo);

		if (!printInfo.m_bDocObject)
			dcPrint.SetAbortProc(_AfxAbortProc);

		// disable main window while printing & init printing status dialog
		// Store the Handle of the Window in a temp so that it can be enabled 
		// once the printing is finished
		CWnd * hwndTemp = AfxGetMainWnd();
		hwndTemp->EnableWindow(FALSE);
		CPrintingDialog dlgPrintStatus(this);

		CString strTemp;
		dlgPrintStatus.SetDlgItemText(AFX_IDC_PRINT_DOCNAME, strTitle);
		dlgPrintStatus.SetDlgItemText(AFX_IDC_PRINT_PRINTERNAME,
			printInfo.m_pPD->GetDeviceName());
		dlgPrintStatus.SetDlgItemText(AFX_IDC_PRINT_PORTNAME, strPortName);
		dlgPrintStatus.ShowWindow(SW_SHOW);
		dlgPrintStatus.UpdateWindow();

		// start document printing process
		if (!printInfo.m_bDocObject)
		{
			printInfo.m_nJobNumber = dcPrint.StartDoc(&docInfo);
			if (printInfo.m_nJobNumber == SP_ERROR)
			{
				// enable main window before proceeding
				hwndTemp->EnableWindow(TRUE);

				// cleanup and show error message
				OnEndPrinting(&dcPrint, &printInfo);
				dlgPrintStatus.DestroyWindow();
				dcPrint.Detach();   // will be cleaned up by CPrintInfo destructor
				AfxMessageBox(AFX_IDP_FAILED_TO_START_PRINT);
				return;
			}
		}

		// Guarantee values are in the valid range
		UINT nEndPage = printInfo.GetToPage();
		UINT nStartPage = printInfo.GetFromPage();

		if (nEndPage < printInfo.GetMinPage())
			nEndPage = printInfo.GetMinPage();
		if (nEndPage > printInfo.GetMaxPage())
			nEndPage = printInfo.GetMaxPage();

		if (nStartPage < printInfo.GetMinPage())
			nStartPage = printInfo.GetMinPage();
		if (nStartPage > printInfo.GetMaxPage())
			nStartPage = printInfo.GetMaxPage();

		int nStep = (nEndPage >= nStartPage) ? 1 : -1;
		nEndPage = (nEndPage == 0xffff) ? 0xffff : nEndPage + nStep;

		VERIFY(strTemp.LoadString(AFX_IDS_PRINTPAGENUM));

		// If it's a doc object, we don't loop page-by-page
		// because doc objects don't support that kind of levity.

		BOOL bError = FALSE;
		if (printInfo.m_bDocObject)
		{
			OnPrepareDC(&dcPrint, &printInfo);
			OnPrint(&dcPrint, &printInfo);
		}
		else
		{
			// begin page printing loop
			for (printInfo.m_nCurPage = nStartPage;
				printInfo.m_nCurPage != nEndPage; printInfo.m_nCurPage += nStep)
			{
				OnPrepareDC(&dcPrint, &printInfo);

				// check for end of print
				if (!printInfo.m_bContinuePrinting)
					break;

				// write current page
				TCHAR szBuf[80];
				ATL_CRT_ERRORCHECK_SPRINTF(_sntprintf_s(szBuf, _countof(szBuf), _countof(szBuf) - 1, strTemp, printInfo.m_nCurPage));
				
				dlgPrintStatus.SetDlgItemText(AFX_IDC_PRINT_PAGENUM, szBuf);

				// set up drawing rect to entire page (in logical coordinates)
				printInfo.m_rectDraw.SetRect(0, 0,
					dcPrint.GetDeviceCaps(HORZRES),
					dcPrint.GetDeviceCaps(VERTRES));
				dcPrint.DPtoLP(&printInfo.m_rectDraw);

				// attempt to start the current page
				if (dcPrint.StartPage() < 0)
				{
					bError = TRUE;
					break;
				}

				// must call OnPrepareDC on newer versions of Windows because
				// StartPage now resets the device attributes.
				OnPrepareDC(&dcPrint, &printInfo);

				ASSERT(printInfo.m_bContinuePrinting);

				// page successfully started, so now render the page
				OnPrint(&dcPrint, &printInfo);

				// If the user restarts the job when it's spooling, all 
				// subsequent calls to EndPage returns < 0. The first time
				// GetLastError returns ERROR_PRINT_CANCELLED
				if (dcPrint.EndPage() < 0 && (GetLastError()!= ERROR_SUCCESS))
				{
					HANDLE hPrinter;
					if (!OpenPrinter(LPTSTR(printInfo.m_pPD->GetDeviceName().GetBuffer()), &hPrinter, NULL))
					{
						bError = TRUE;
						break;
					}

					DWORD cBytesNeeded;
					if(!GetJob(hPrinter,printInfo.m_nJobNumber,1,NULL,0,&cBytesNeeded))
					{
						if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
						{
						   bError = TRUE;
						   break;
						}
					}

					JOB_INFO_1 *pJobInfo; 					
					if((pJobInfo = (JOB_INFO_1 *)malloc(cBytesNeeded))== NULL)
					{
						bError = TRUE;
						break;
					}

					DWORD cBytesUsed;

					BOOL bRet = GetJob(hPrinter,printInfo.m_nJobNumber,1,LPBYTE(pJobInfo),cBytesNeeded,&cBytesUsed);

					DWORD dwJobStatus = pJobInfo->Status;

					free(pJobInfo);
					pJobInfo = NULL;

					// if job status is restart, just continue
					if(!bRet || !(dwJobStatus & JOB_STATUS_RESTART) )
					{
						bError = TRUE;
						break;
					}
				}

				if(!_AfxAbortProc(dcPrint.m_hDC, 0))
				{		
					bError = TRUE;
					break;
				}
			}
		}

		// cleanup document printing process
		if (!printInfo.m_bDocObject)
		{
			if (!bError)
				dcPrint.EndDoc();
			else
				dcPrint.AbortDoc();
		}

		hwndTemp->EnableWindow();    // enable main window

		OnEndPrinting(&dcPrint, &printInfo);    // clean up after printing
		dlgPrintStatus.DestroyWindow();

		dcPrint.Detach();   // will be cleaned up by CPrintInfo destructor
	}
}
예제 #26
0
/*******************************************************************************
 Function Name  : vShowControl
 Inputs         : nRow      - Index of the Row
                  nColumn   - Index of the Column
 Output         :   -
 Description    : This function will show the UI control to change the list item
                  text. This will get the type information from the Cmap and
                  will call approp. function to create and show that control.
 Member of      : CFlexListCtrl
 Author(s)      : Raja N
 Date Created   : 22.07.2004
 Modifications  : Raja N on 30.07.2004, Code review comments implemented
*******************************************************************************/
void CFlexListCtrl::vShowControl(int nItem, int nSubItem)
{
    // Proceed only for a valid entry
    if( nItem >= 0 && nSubItem >= 0)
    {
        SLISTINFO sInfo;
        SNUMERICINFO    sNumInfo;
        SUSERPROGINFO   sProgInfo;
        CString omStr = STR_EMPTY;

        // Got the entry type from the CMap
        if( m_omListItemType.Lookup(
                    lGetMapID(nItem, nSubItem) , sInfo) == TRUE )
        {
            // Begining of Controls creation
            m_bCreating = TRUE;

            switch( sInfo.m_eType)
            {
                    // Numeric Edit box with or with out Spin Control
                case eNumber:
                case eBuddy:

                    // Get the numeric control parameters
                    if( m_omNumDetails.Lookup( lGetMapID(nItem, nSubItem),
                                               sNumInfo ) == TRUE )
                    {
                        pomNumItem(nItem, nSubItem, sNumInfo);
                    }
                    else
                    {
                        // Numeric info is not set
                        ASSERT( FALSE );
                        // Call with default value
                        pomNumItem(nItem, nSubItem, sNumInfo);
                    }

                    break;

                    // General Edit control
                case eText:
                    pomEditItem(nItem, nSubItem);
                    break;

                    // Editalble Combo Box
                case eComboList:
                    pomComboList(nItem, nSubItem, sInfo.m_omEntries);
                    break;

                    // Non - Editable combo box
                case eComboItem:
                    pomComboItem(nItem, nSubItem, sInfo.m_omEntries);
                    break;

                    // User function will be executed
                case eUser:

                    // Get the user program pointer and parameter details
                    if( m_omUserProg.Lookup( lGetMapID(nItem, nSubItem),
                                             sProgInfo ) == TRUE )
                    {
                        sProgInfo.m_pfHandler( this,
                                               nItem,
                                               nSubItem,
                                               sProgInfo.m_pUserParam);
                    }
                    else
                    {
                        // User program information is not set
                        ASSERT( FALSE );
                    }

                    break;

                    // Toggling type control
                case eBool:
                    // Get the current text
                    omStr = GetItemText(nItem, nSubItem);

                    // Compare with the first item
                    if( sInfo.m_omEntries.GetAt(0).Compare(omStr) == 0 )
                    {
                        // Toggle the first with the second item text.
                        omStr = sInfo.m_omEntries.GetAt(1);
                    }
                    // Compare with the Second item
                    else if( sInfo.m_omEntries.GetAt(1).Compare(omStr) == 0 )
                    {
                        // Replace with the first item
                        omStr = sInfo.m_omEntries.GetAt(0);
                    }

                    // If it is not matching with these two items nothing will
                    // happen. This could be used to disable the control
                    // For boolean type this is the end of Controls creation
                    m_bCreating = FALSE;
                    // For boolean send the EndLAbleEdit message here itself
                    LV_DISPINFO lvDispInfo;
                    lvDispInfo.hdr.hwndFrom = m_hWnd;
                    lvDispInfo.hdr.idFrom = GetDlgCtrlID();
                    lvDispInfo.hdr.code = LVN_ENDLABELEDIT;
                    lvDispInfo.item.mask = LVIF_TEXT;
                    lvDispInfo.item.iItem = nItem;
                    lvDispInfo.item.iSubItem = nSubItem;
                    lvDispInfo.item.pszText = LPTSTR((LPCTSTR)omStr);
                    lvDispInfo.item.cchTextMax = omStr.GetLength();
                    SendMessage( WM_NOTIFY, GetDlgCtrlID(),(LPARAM)&lvDispInfo);
                    break;

                default:
                    // Unknown control type
                    ASSERT( FALSE );
            }

            // End of Controls
            m_bCreating = FALSE;
        }
    }
}
예제 #27
0
void CRedirect::Run()
{
	HANDLE					PipeReadHandle;
	HANDLE					PipeWriteHandle;
	PROCESS_INFORMATION		ProcessInfo;
	SECURITY_ATTRIBUTES		SecurityAttributes;
	STARTUPINFO				StartupInfo;
	BOOL					Success;

	//--------------------------------------------------------------------------
	//	Zero the structures.
	//--------------------------------------------------------------------------
	ZeroMemory( &StartupInfo,			sizeof( StartupInfo ));
	ZeroMemory( &ProcessInfo,			sizeof( ProcessInfo ));
	ZeroMemory( &SecurityAttributes,	sizeof( SecurityAttributes ));

	//--------------------------------------------------------------------------
	//	Create a pipe for the child's STDOUT.
	//--------------------------------------------------------------------------
	SecurityAttributes.nLength              = sizeof(SECURITY_ATTRIBUTES);
	SecurityAttributes.bInheritHandle       = TRUE;
	SecurityAttributes.lpSecurityDescriptor = NULL;

	Success = CreatePipe
	(
		&PipeReadHandle,		// address of variable for read handle
		&PipeWriteHandle,		// address of variable for write handle
		&SecurityAttributes,	// pointer to security attributes
		0						// number of bytes reserved for pipe (use default size)
	);

	if ( !Success )
	{
		ShowLastError(_T("Error creating pipe"));
		return;
	}	

	//--------------------------------------------------------------------------
	//	Set up members of STARTUPINFO structure.
	//--------------------------------------------------------------------------
	StartupInfo.cb           = sizeof(STARTUPINFO);
	StartupInfo.dwFlags      = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
	StartupInfo.wShowWindow  = SW_HIDE;//SW_SHOW;//
	StartupInfo.hStdOutput   = PipeWriteHandle;
	StartupInfo.hStdError    = PipeWriteHandle;

	//----------------------------------------------------------------------------
	//	Create the child process.
	//----------------------------------------------------------------------------
	Success = CreateProcess
	( 
		NULL,					// pointer to name of executable module
		LPTSTR(m_szCommand),	// command line 
		NULL,					// pointer to process security attributes 
		NULL,					// pointer to thread security attributes (use primary thread security attributes)
		TRUE,					// inherit handles
		0,						// creation flags
		NULL,					// pointer to new environment block (use parent's)
		m_szCurrentDirectory,	// pointer to current directory name
		&StartupInfo,			// pointer to STARTUPINFO
		&ProcessInfo			// pointer to PROCESS_INFORMATION
	);                 

	if ( !Success )
	{
		ShowLastError(_T("Error creating process"));
		return;
	}

	DWORD	BytesLeftThisMessage = 0;
	DWORD	NumBytesRead;
	TCHAR	PipeData[BUF_SIZE]; 
	DWORD	TotalBytesAvailable = 0;

	for ( ; ; )
	{ 
		NumBytesRead = 0;

		Success = PeekNamedPipe
		( 
			PipeReadHandle,				// handle to pipe to copy from 
			PipeData,					// pointer to data buffer 
			1,							// size, in bytes, of data buffer 
			&NumBytesRead,				// pointer to number of bytes read 
			&TotalBytesAvailable,		// pointer to total number of bytes available
			&BytesLeftThisMessage		// pointer to unread bytes in this message 
		);

		if ( !Success )
		{
			ShowLastError(_T("PeekNamedPipe fialed"));
			break;
		}

		if ( NumBytesRead )
		{
			Success = ReadFile
			(
				PipeReadHandle,		// handle to pipe to copy from 
				PipeData,			// address of buffer that receives data
				BUF_SIZE - 1,		// number of bytes to read
				&NumBytesRead,		// address of number of bytes read
				NULL				// address of structure for data for overlapped I/O
			);

			if ( !Success )
			{
				ShowLastError(_T("ReadFile fialed"));
				break;
			}

			//------------------------------------------------------------------
			//	Zero-terminate the data.
			//------------------------------------------------------------------
			PipeData[NumBytesRead] = '\0';

			//------------------------------------------------------------------
			//	Replace backspaces with spaces.
			//------------------------------------------------------------------
			for ( DWORD ii = 0; ii < NumBytesRead; ii++ )
			{
				if ( PipeData[ii] == _T('\b') )
				{
					PipeData[ii] = ' ';
				}
			}
			
			//------------------------------------------------------------------
			//	If we're running a batch file that contains a pause command, 
			//	assume it is the last output from the batch file and remove it.
			//------------------------------------------------------------------
			TCHAR  *ptr = _tcsstr(PipeData, _T("Press any key to continue . . ."));
			if ( ptr )
			{
				*ptr = '\0';
			}

            OutputDebugStringA((char*)PipeData);

			//------------------------------------------------------------------
			//	Append the output to the CEdit control.
			//------------------------------------------------------------------
			AppendText(PipeData);

			//------------------------------------------------------------------
			//	Peek and pump messages.
			//------------------------------------------------------------------
			PeekAndPump();
		}
		else
		{
			//------------------------------------------------------------------
			//	If the child process has completed, break out.
			//------------------------------------------------------------------
			if ( WaitForSingleObject(ProcessInfo.hProcess, 0) == WAIT_OBJECT_0 )	//lint !e1924 (warning about C-style cast)
			{
				break;
			}

			//------------------------------------------------------------------
			//	Peek and pump messages.
			//------------------------------------------------------------------
			PeekAndPump();

			//------------------------------------------------------------------
			//	If the user cancelled the operation, terminate the process.
			//------------------------------------------------------------------
			if ( m_bStopped )
			{
				Success = TerminateProcess
				(
					ProcessInfo.hProcess,
					0
				);

				if ( Success )
				{
					AppendText(_T("\r\nCancelled.\r\n\r\nProcess terminated successfully.\r\n"));
				}
				else
				{
					ShowLastError(_T("Error terminating process."));
				}

				break;
			}

			//------------------------------------------------------------------
			//	Sleep.
			//------------------------------------------------------------------
			Sleep(m_dwSleepMilliseconds);
		}
		
	}

	//--------------------------------------------------------------------------
	//	Close handles.
	//--------------------------------------------------------------------------
	Success = CloseHandle(ProcessInfo.hThread);
	if ( !Success )
	{
		ShowLastError(_T("Error closing thread handle."));
	}

	Success = CloseHandle(ProcessInfo.hProcess);
	if ( !Success )
	{
		ShowLastError(_T("Error closing process handle."));
	}

	Success = CloseHandle(PipeReadHandle);
	if ( !Success )
	{
		ShowLastError(_T("Error closing pipe read handle."));
	}

	Success = CloseHandle(PipeWriteHandle);
	if ( !Success )
	{
		ShowLastError(_T("Error closing pipe write handle."));
	}

}
예제 #28
0
static void watch_directory(folder_watcher* pfw)
{
	DWORD dwWaitStatus;
	HANDLE dwChangeHandles[2];
	TCHAR lpDrive[4];
	TCHAR lpFile[_MAX_FNAME];
	TCHAR lpExt[_MAX_EXT];

	_tsplitpath_s(LPTSTR(pfw->get_directory().data()), lpDrive, 4, NULL, 0, lpFile, _MAX_FNAME, lpExt, _MAX_EXT);

	lpDrive[2] = (TCHAR)'\\';
	lpDrive[3] = (TCHAR)'\0';

	// Watch the directory for file creation and deletion. 

	dwChangeHandles[0] = FindFirstChangeNotification(
		LPTSTR(pfw->get_directory().data()), // directory to watch 
		TRUE,                         // do not watch subtree 
		pfw->get_filter()); // watch file name changes 

	if (dwChangeHandles[0] == INVALID_HANDLE_VALUE)
	{
		printf("\n ERROR: FindFirstChangeNotification function failed.\n");
		ExitProcess(GetLastError());
	}

	// Watch the subtree for directory creation and deletion. 
	
	dwChangeHandles[1] = FindFirstChangeNotification(
		lpDrive,                       // directory to watch 
		TRUE,                          // watch the subtree 
		FILE_NOTIFY_CHANGE_DIR_NAME);  // watch dir name changes 

	if (dwChangeHandles[1] == INVALID_HANDLE_VALUE)
	{
		printf("\n ERROR: FindFirstChangeNotification function failed.\n");
		ExitProcess(GetLastError());
	}


	// Make a final validation check on our handles.

	if ((dwChangeHandles[0] == NULL) || (dwChangeHandles[1] == NULL))
	{
		printf("\n ERROR: Unexpected NULL from FindFirstChangeNotification.\n");
		ExitProcess(GetLastError());
	}

	// Change notification is set. Now wait on both notification 
	// handles and refresh accordingly. 

	while (true)
	{
		// Wait for notification.

		//printf("\nWaiting for notification...\n");

		dwWaitStatus = WaitForMultipleObjects(2, dwChangeHandles, FALSE, WAIT_TIME);

		if (!pfw->is_running())
		{
			break;
		}

		switch (dwWaitStatus)
		{
		case WAIT_OBJECT_0:

			// A file was created, renamed, or deleted in the directory.
			// Refresh this directory and restart the notification.
			//printf("fileupdate\n");
			pfw->call_callback();
			if (FindNextChangeNotification(dwChangeHandles[0]) == FALSE)
			{
				printf("\n ERROR: FindNextChangeNotification function failed.\n");
				ExitProcess(GetLastError());
			}
			
			break;

		case WAIT_OBJECT_0 + 1:

			// A directory was created, renamed, or deleted.
			// Refresh the tree and restart the notification.
			//printf("folderupdate\n");
			pfw->call_callback();
			if (FindNextChangeNotification(dwChangeHandles[1]) == FALSE)
			{
				printf("\n ERROR: FindNextChangeNotification function failed.\n");
				ExitProcess(GetLastError());
			}
			break;

		case WAIT_TIMEOUT:

			// A timeout occurred, this would happen if some value other 
			// than INFINITE is used in the Wait call and no changes occur.
			// In a single-threaded environment you might not want an
			// INFINITE wait.

			//printf("\nNo changes in the timeout period.\n");
			break;

		default:
			printf("\n ERROR: Unhandled dwWaitStatus.\n");
			ExitProcess(GetLastError());
			break;
		}
	}
}
예제 #29
-1
ThtiPage* TffdshowPageBase::addTI(TVINSERTSTRUCT *tvis, TconfPageBase *page)
{
    ThtiPage *htiPage = new ThtiPage(NULL, page);
    htiPages.push_back(htiPage);
    if (tvis) {
        tvis->item.lParam = (LPARAM)htiPage;
        tvis->item.pszText = LPTSTR(page->dialogName());
        HTREEITEM hti = TreeView_InsertItem(htv, tvis);
        page->hti = hti;
        htiPage->hti = hti;
    } else {
        page->hti = NULL;
        htiPage->hti = NULL;
    }
    return htiPage;
}
예제 #30
-2
void TffdshowPageDec::showShowHide(int previd, int prevVisId)
{
    if (previd == 0 && page) {
        previd = page->uniqueID();
    }
    if (prevVisId == 0) {
        prevVisId = hti2page(TreeView_GetFirstVisible(htv))->uniqueID();
    }
    for (ThtiPages::reverse_iterator rp = filterPages.rbegin(); rp != filterPages.rend(); rp++)
        if ((*rp)->hti) {
            TreeView_DeleteItem(htv, (*rp)->hti);
            (*rp)->hti = NULL;
            for (TconfPages::iterator i = (*rp)->begin(); i != (*rp)->end(); i++) {
                (*i)->hti = NULL;
            }
        }
    TVINSERTSTRUCT tvis;
    tvis.hParent = htiPresets;
    tvis.hInsertAfter = htiBeforeShowHide;
    tvis.item.mask = TVIF_PARAM | TVIF_TEXT;
    HTREEITEM htiLast0 = NULL;
    for (ThtiPages::const_iterator p = filterPages.begin(); p != filterPages.end(); p++)
        if ((*p)->getPage()->getShow()) {
            tvis.item.lParam = (LPARAM) * p;
            tvis.item.pszText = LPTSTR((*p)->front()->dialogName());
            tvis.item.iImage = tvis.item.iSelectedImage = 0;
            tvis.hParent = ((*p)->getPage()->filterPageID > 1) ? htiLast0 : htiPresets;
            HTREEITEM hti = TreeView_InsertItem(htv, &tvis);
            (*p)->hti = hti;
            for (TconfPages::iterator i = (*p)->begin(); i != (*p)->end(); i++) {
                (*i)->hti = hti;
            }
            if ((*p)->getPage()->filterPageID <= 1) {
                if (htiLast0) {
                    TreeView_Expand(htv, htiLast0, TVE_EXPAND);
                }
                htiLast0 = hti;
            }
        }
    if (htiLast0) {
        TreeView_Expand(htv, htiLast0, TVE_EXPAND);
    }
    sortOrder();
    if (previd) {
        treeSelectItem(previd, prevVisId);
    }
}