void CWordBinaryMetadataDiscoveryWorker::GetMacros() 
{
	if (NULL == m_pStorage)
		throw Workshare::Exception(_T("Encountered NULL pointer (m_pStorage)"));

	if (NULL == m_pStrategy)
		throw Workshare::Exception(_T("Encountered NULL pointer (m_pStrategy)"));

	__raise m_pStrategy->OnMacrosBegin();
	IStorage *pStorageMacros;
	
	if(OpenSubStorage(m_pStorage, MACROS_ELEMENT_NAME, &pStorageMacros))
	{
		USES_CONVERSION;
		IStorage *pVBAStorage;
		try
		{
			if(OpenSubStorage(pStorageMacros, _T("VBA"), &pVBAStorage))
			{
				// Enumerate components
				IEnumSTATSTG *pEnumVBA;
				HRESULT hr = pVBAStorage->EnumElements(0, NULL, 0, &pEnumVBA);
				if(SUCCEEDED(hr))
				{
					STATSTG statstg;
					ZeroMemory(&statstg, sizeof(STATSTG));
					CStdString sStream;
					while(S_OK == pEnumVBA->Next(1, &statstg, 0))
					{
						sStream = W2A(statstg.pwcsName);
						//ignore dir and _VBA_PROJECT as these are of no interest
						if(0 != sStream.CompareNoCase(_T("dir")) && 0 != sStream.CompareNoCase(_T("_VBA_PROJECT")))
						{
							__raise m_pStrategy->OnMacro(_bstr_t(sStream.c_str()));
						}
						CoTaskMemFree(statstg.pwcsName);
						statstg.pwcsName = NULL;
					}
					pEnumVBA->Release();
				}
				pVBAStorage->Release();
			}
		}
		catch (std::exception&)
		{
			pStorageMacros->Release();
			throw;
		}

		pStorageMacros->Release();
	}
	__raise m_pStrategy->OnMacrosEnd();

}
// @pymethod |pythoncom|WriteClassStg|Writes a CLSID to a storage object
PyObject *pythoncom_WriteClassStg(PyObject *self, PyObject *args)
{
	PyObject *obStg;
	PyObject *obCLSID;
	if (!PyArg_ParseTuple(args, "OO:WriteClassStg",
					   &obStg, // @pyparm <o PyIStorage>|storage||Storage object into which CLSID will be written.
					   &obCLSID)) // @pyparm <o PyIID>|iid||The IID to write
		return NULL;

	CLSID clsid;
	if (!PyWinObject_AsIID(obCLSID, &clsid))
		return NULL;

	IStorage *pStorage;
	if (!PyCom_InterfaceFromPyObject(obStg, IID_IStorage, (void **)&pStorage, FALSE))
		return NULL;

	PY_INTERFACE_PRECALL;
	HRESULT hr = WriteClassStg(pStorage, clsid);
	pStorage->Release();
	PY_INTERFACE_POSTCALL;
	if (FAILED(hr)) return PyCom_BuildPyException(hr);
	Py_INCREF(Py_None);
	return Py_None;
}
Beispiel #3
0
HRESULT CDShowCtrl::LoadGraphFile(IGraphBuilder *pGraph, const WCHAR* wszName)
{
    IStorage *pStorage = 0;
    if (S_OK != StgIsStorageFile(wszName))
    {
        return E_FAIL;
    }
    HRESULT hr = StgOpenStorage(wszName, 0, 
        STGM_TRANSACTED | STGM_READ | STGM_SHARE_DENY_WRITE, 
        0, 0, &pStorage);
    if (FAILED(hr))
    {
        return hr;
    }
    IPersistStream *pPersistStream = 0;
    hr = pGraph->QueryInterface(IID_IPersistStream,
             reinterpret_cast<void**>(&pPersistStream));
    if (SUCCEEDED(hr))
    {
        IStream *pStream = 0;
        hr = pStorage->OpenStream(L"ActiveMovieGraph", 0, 
            STGM_READ | STGM_SHARE_EXCLUSIVE, 0, &pStream);
        if(SUCCEEDED(hr))
        {
            hr = pPersistStream->Load(pStream);
            pStream->Release();
        }
        pPersistStream->Release();
    }
    pStorage->Release();
    return hr;
}
static PyObject *pyBindIFilterFromStorage(PyObject *self, PyObject *args)
{
	HRESULT hr;
	IUnknown *pOb = NULL;
	PyObject *obStg;
	
	PyObject *ret;
	long lres = 0;
	if (!PyArg_ParseTuple(args, "O:BindIFilterFromStorage", &obStg)) 
		return NULL;

	IStorage *pstgDest;
	BOOL bPythonIsHappy = TRUE;
	if (!PyCom_InterfaceFromPyObject(obStg, IID_IStorage, (void **)&pstgDest, FALSE /* bNoneOK */))
	    bPythonIsHappy = FALSE;

	if (!bPythonIsHappy)
		return NULL;

	Py_BEGIN_ALLOW_THREADS;
    hr = BindIFilterFromStorage( pstgDest , NULL , (void**)&pOb ); 
	pstgDest->Release();
	Py_END_ALLOW_THREADS;
	if (FAILED(hr))
		ret = OleSetOleError(hr);

	else
		ret = PyCom_PyObjectFromIUnknown(pOb, IID_IFilter, FALSE);

	return ret;
}
// @pymethod |PyIStorage|MoveElementTo|Copies or moves a substorage or stream from this storage object to another storage object.
PyObject *PyIStorage::MoveElementTo(PyObject *self, PyObject *args)
{
	IStorage *pIS = GetI(self);
	if ( pIS == NULL )
		return NULL;
	// @pyparm string|name||A string that contains the name of the element in this storage object to be moved or copied.
	// @pyparm <o PyIStorage>|stgDest||<o PyIStorage> for the destination storage object.
	// @pyparm string|newName||A string that contains the new name for the element in its new storage object.
	// @pyparm int|grfFlags||Specifies whether the operation should be a move (STGMOVE_MOVE) or a copy (STGMOVE_COPY). See the STGMOVE enumeration.
	PyObject *obName, *obNewName;
	PyObject *obpstgDest;
	DWORD grfFlags;
	if ( !PyArg_ParseTuple(args, "OOOi:MoveElementTo", &obName, &obpstgDest, &obNewName, &grfFlags) )
		return NULL;
	IStorage *pstgDest;
	BOOL bPythonIsHappy = TRUE;
	BSTR bstrName, bstrNewName;
	bPythonIsHappy = PyWinObject_AsBstr(obName, &bstrName);
	if (!PyWinObject_AsBstr(obNewName, &bstrNewName))
		bPythonIsHappy = FALSE;
	if (!PyCom_InterfaceFromPyObject(obpstgDest, IID_IStorage, (void **)&pstgDest, FALSE /* bNoneOK */))
		 bPythonIsHappy = FALSE;
	if (!bPythonIsHappy) return NULL;
	PY_INTERFACE_PRECALL;
	HRESULT hr = pIS->MoveElementTo( bstrName, pstgDest, bstrNewName, grfFlags );
	pstgDest->Release();
	PY_INTERFACE_POSTCALL;
	PyWinObject_FreeBstr(bstrName);
	PyWinObject_FreeBstr(bstrNewName);
	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pIS, IID_IStorage);
	Py_INCREF(Py_None);
	return Py_None;

}
// @pymethod |PyIStorage|CopyTo|Copies the entire contents of an open storage object to another storage object.
PyObject *PyIStorage::CopyTo(PyObject *self, PyObject *args)
{
	IStorage *pIS = GetI(self);
	if ( pIS == NULL )
		return NULL;
	// @pyparm [<o PyIID>,]|rgiidExclude||List of IID's to be excluded.
	// @pyparm <o SNB>|snbExclude||Reserved for later - Must be None
	// @pyparm <o PyIStorage>|stgDest||The open storage object into which this storage object is to be copied. 
	// The destination storage object can be a different implementation of the <o PyIStorage> interface from the source storage object. 
	// Thus, <om IStorage::CopyTo> can only use publicly available methods of the destination storage object. 
	// If stgDest is open in transacted mode, it can be reverted by calling its <om PyIStorage::Revert> method. 
	DWORD ciidExclude = 0;
	PyObject *obSeqExclude;
	PyObject *obpstgDest;
	char *temp;
	if ( !PyArg_ParseTuple(args, "OzO:CopyTo", &obSeqExclude, &temp, &obpstgDest) )
		return NULL;
	IID *pExclude;
	if (obSeqExclude==Py_None)
		pExclude = NULL;
	else {
		if (!PySequence_Check(obSeqExclude)) {
			PyErr_SetString(PyExc_TypeError, "Argument 1 must be a sequence of IID's, or None");
			return NULL;
		}
		ciidExclude = PySequence_Length(obSeqExclude);
		pExclude = new IID[ciidExclude];
		if (pExclude==NULL) {
			PyErr_SetString(PyExc_MemoryError, "Allocating array of IID's");
			return NULL;
		}
		for (DWORD i=0;i<ciidExclude;i++) {
			PyObject *ob = PySequence_GetItem(obSeqExclude, (int)i);
			BOOL ok = PyWinObject_AsIID(ob, pExclude+i);
			Py_XDECREF(ob);
			if (!ok) {
				delete [] pExclude;
				return NULL;
			}
		}
	}
	IStorage *pstgDest;
	BOOL bPythonIsHappy = TRUE;
	if (!PyCom_InterfaceFromPyObject(obpstgDest, IID_IStorage, (void **)&pstgDest, FALSE /* bNoneOK */))
		 bPythonIsHappy = FALSE;
	if (!bPythonIsHappy) {
		return NULL;
		delete [] pExclude;
	}
	PY_INTERFACE_PRECALL;
	HRESULT hr = pIS->CopyTo( ciidExclude, pExclude, NULL, pstgDest );
	delete [] pExclude;
	pstgDest->Release();
	PY_INTERFACE_POSTCALL;

	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pIS, IID_IStorage);
	Py_INCREF(Py_None);
	return Py_None;
}
Beispiel #7
0
long __stdcall FastIStorage::CopyTo(unsigned long,const struct _GUID *,WCHAR ** ,struct IStorage *pstgNew)
	{
	HRESULT hr;
	IStorage *pstgT;
	IStream *pstmT;

	for (int i=0;i<m_vstg.Size();i++)
		{
		FastIStorage *pstgCur = m_vstg.ElementAt(i);
		if(SUCCEEDED(hr = pstgNew->CreateStorage(pstgCur->m_wzName, STGM_DIRECT | STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE, 0, 0, &pstgT)))
			{
			pstgCur->CopyTo(0,NULL,NULL,pstgT);
			pstgT->Release();
			}
		}

	for (int i=0;i<m_vstm.Size();i++)
		{
		FastIStream *pstmCur = m_vstm.ElementAt(i);
		if(SUCCEEDED(hr = pstgNew->CreateStream(pstmCur->m_wzName, STGM_DIRECT | STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE, 0, 0, &pstmT)))
			{
			ULONG writ;
			//pstmCur->CopyTo(0,NULL,NULL,pstmT);
			pstmT->Write(pstmCur->m_rg, pstmCur->m_cSize, &writ);
			pstmT->Release();
			}
		}

	return S_OK;
	}
// @pymethod <o PyIStorage>|pythoncom|StgOpenStorage|Opens an existing root storage object in the file system.
PyObject *pythoncom_StgOpenStorage(PyObject *self, PyObject *args)
{
	PyObject *temp = NULL;
	DWORD reserved = 0;
	PyObject *obName;
	DWORD mode;
	IStorage *pResult;
	PyObject *obOther;

	if (!PyArg_ParseTuple(args, "OOi|Oi:StgOpenStorage",
		               &obName, // @pyparm string|name||Name of the stream, or possibly None if storageOther is non None.
					   &obOther, // @pyparm <o PyIStorage>|other||Usually None, or another parent storage.
					   &mode, // @pyparm int|mode||Specifies the access mode used to open the storage.  A combination of the storagecon.STGM_* constants.
					   &temp, // @pyparm object|snbExclude|None|Not yet supported - must be None
					   &reserved)) // @pyparm int|reserved|0|A reserved value
		return NULL;
	PyWin_AutoFreeBstr bstrName;
	if ( !PyWinObject_AsAutoFreeBstr(obName, &bstrName, TRUE) )
		return NULL;
	IStorage *pOther;
	if (!PyCom_InterfaceFromPyObject(obOther, IID_IStorage, (void **)&pOther, TRUE))
		return NULL;
	PY_INTERFACE_PRECALL;
	HRESULT hr = StgOpenStorage(bstrName, pOther, mode, NULL, reserved, &pResult);
	if (pOther) pOther->Release();
	PY_INTERFACE_POSTCALL;
	if (FAILED(hr)) return PyCom_BuildPyException(hr);
	return PyCom_PyObjectFromIUnknown(pResult, IID_IStorage, FALSE);
}
    ~Pimpl()
    {
        if (control != 0)
        {
            control->Close (OLECLOSE_NOSAVE);
            control->Release();
        }

        clientSite->Release();
        storage->Release();
    }
Beispiel #10
0
// This code was also brazenly stolen from the DX9 SDK
// Pass it a file name in wszPath, and it will save the filter graph to that file.
HRESULT SaveGraphFile(IGraphBuilder *pGraph, WCHAR *wszPath) 
{
    const WCHAR wszStreamName[] = L"ActiveMovieGraph"; 
    HRESULT hr;
    IStorage *pStorage = NULL;

	// First, create a document file which will hold the GRF file
	hr = StgCreateDocfile(
        wszPath,
        STGM_CREATE | STGM_TRANSACTED | STGM_READWRITE | STGM_SHARE_EXCLUSIVE,
        0, &pStorage);
    if(FAILED(hr)) 
    {
        return hr;
    }

	// Next, create a stream to store.
    IStream *pStream;
    hr = pStorage->CreateStream(
		wszStreamName,
        STGM_WRITE | STGM_CREATE | STGM_SHARE_EXCLUSIVE,
        0, 0, &pStream);
    if (FAILED(hr)) 
    {
        pStorage->Release();    
        return hr;
    }

	// The IPersistStream converts a stream into a persistent object.
    IPersistStream *pPersist = NULL;
    pGraph->QueryInterface(IID_IPersistStream, reinterpret_cast<void**>(&pPersist));
    hr = pPersist->Save(pStream, TRUE);
    pStream->Release();
    pPersist->Release();
    if (SUCCEEDED(hr)) 
    {
        hr = pStorage->Commit(STGC_DEFAULT);
    }
    pStorage->Release();
    return hr;
}
HRESULT SaveGraphFile(IGraphBuilder *pGraph, WCHAR *wszPath) 
{
	const WCHAR wszStreamName[] = L"ActiveMovieGraph"; 
	HRESULT hr;
	
	IStorage *pStorage = NULL;
	hr = StgCreateDocfile(
	wszPath,
	STGM_CREATE | STGM_TRANSACTED | STGM_READWRITE | STGM_SHARE_EXCLUSIVE,
	0, &pStorage);
	if(FAILED(hr)) 
	{
		return hr;
	}

	IStream *pStream;
	hr = pStorage->CreateStream(
	wszStreamName,
	STGM_WRITE | STGM_CREATE | STGM_SHARE_EXCLUSIVE,
	0, 0, &pStream);
	if (FAILED(hr)) 
	{
		pStorage->Release(); 
		return hr;
	}
	
	IPersistStream *pPersist = NULL;
	pGraph->QueryInterface(IID_IPersistStream, (void**)&pPersist);
	hr = pPersist->Save(pStream, TRUE);
	pStream->Release();
	pPersist->Release();
	if (SUCCEEDED(hr)) 
	{
		hr = pStorage->Commit(STGC_DEFAULT);
	}
	pStorage->Release();
	return hr;
}
HRESULT CDropHandler::CopyShellIDListData(IDataObject *pDataObject,
	list<PastedFile_t> *pPastedFileList)
{
	STGMEDIUM stg;
	HRESULT hr;

	hr = pDataObject->GetData(&m_ftcShellIDList,&stg);

	if(hr == S_OK)
	{
		CIDA *pcida = (CIDA *)GlobalLock(stg.hGlobal);

		if(pcida != NULL)
		{
			IShellFolder *pShellFolder = NULL;
			HRESULT hr;

			LPCITEMIDLIST pidlDirectory = HIDA_GetPIDLFolder(pcida);

			hr = BindToShellFolder(pidlDirectory,&pShellFolder);

			if(SUCCEEDED(hr))
			{
				LPCITEMIDLIST pidlItem = NULL;
				IStorage *pStorage = NULL;

				for(unsigned int i = 0;i < pcida->cidl;i++)
				{
					pidlItem = HIDA_GetPIDLItem(pcida,i);

					hr = pShellFolder->BindToStorage(pidlItem,NULL,IID_IStorage,(LPVOID *)&pStorage);

					if(SUCCEEDED(hr))
					{
						/* TODO: Copy the files. */
						pStorage->Release();
					}
				}

				pShellFolder->Release();
			}

			GlobalUnlock(stg.hGlobal);
		}

		ReleaseStgMedium(&stg);
	}

	return hr;
}
// @pymethod <o PyIID>|pythoncom|ReadClassStg|Reads a CLSID from a storage object.
PyObject *pythoncom_ReadClassStg(PyObject *self, PyObject *args)
{
	PyObject *obStg;
	if (!PyArg_ParseTuple(args, "O:ReadClassStg",
					   &obStg)) // @pyparm <o PyIStorage>|storage||The storage to read the CLSID from.
		return NULL;
	IStorage *pStorage;
	if (!PyCom_InterfaceFromPyObject(obStg, IID_IStorage, (void **)&pStorage, FALSE))
		return NULL;
	CLSID clsidRet;
	PY_INTERFACE_PRECALL;
	HRESULT hr = ReadClassStg(pStorage, &clsidRet);
	pStorage->Release();
	PY_INTERFACE_POSTCALL;
	if (FAILED(hr)) return PyCom_BuildPyException(hr);
	return PyWinObject_FromIID(clsidRet);
}
Beispiel #14
0
void CompleteAutoSave(HANDLE hEvent, LPARAM lParam)
	{
	AutoSavePackage *pasp = (AutoSavePackage *)lParam;

	FastIStorage *pstgroot = pasp->pstg;

	IStorage *pstgDisk;

	WCHAR *wzSaveName = L"AutoSave";
	WCHAR *wzSaveExtension = L".vpx";
	WCHAR wzSuffix[32];
	_itow_s(pasp->tableindex, wzSuffix, sizeof(wzSuffix)/sizeof(WCHAR), 10);

	WCHAR * const wzT = new WCHAR[MAX_PATH + 32 + lstrlenW(wzSaveName) + lstrlenW(wzSaveExtension)+ 1];

	WideStrCopy(g_pvp->m_wzMyPath, wzT);
	WideStrCat(wzSaveName, wzT);
	WideStrCat(wzSuffix, wzT);
	WideStrCat(wzSaveExtension, wzT);
	
	//MAKE_WIDEPTR_FROMANSI(wszCodeFile, m_szFileName);

	STGOPTIONS stg;
	stg.usVersion = 1;
	stg.reserved = 0;
	stg.ulSectorSize = 4096;

	HRESULT hr;
	if(SUCCEEDED(hr = StgCreateStorageEx(wzT, STGM_TRANSACTED | STGM_READWRITE | STGM_SHARE_EXCLUSIVE | STGM_CREATE,
		STGFMT_DOCFILE, 0, &stg, 0, IID_IStorage, (void**)&pstgDisk)))
		{
		pstgroot->CopyTo(0, NULL, NULL, pstgDisk);
		hr = pstgDisk->Commit(STGC_DEFAULT);
		pstgDisk->Release();
		}

	pstgroot->Release();

	SetEvent(hEvent);

	PostMessage(pasp->HwndTable, DONE_AUTOSAVE, (WPARAM)hEvent, hr);

	delete [] wzT;
	delete pasp;
	}
// @pymethod <o PyIStorage>|PyIStorage|OpenStorage|Opens an existing storage object with the specified name in the specified access mode.
PyObject *PyIStorage::OpenStorage(PyObject *self, PyObject *args)
{
	IStorage *pIS = GetI(self);
	if ( pIS == NULL )
		return NULL;
	// @pyparm string|pwcsName||Name of the storage, or None.
	// @pyparm <o PyIStorage>|pstgPriority||If the pstgPriority parameter is not None, it is a <o PyIStorage> object to a previous opening of an element of the storage object, 
	// usually one that was opened in priority mode. The storage object should be closed and re-opened 
	// according to grfMode. When the <om PyIStorage.OpenStorage> method returns, pstgPriority is no longer valid - use the result value. 
	// If the pstgPriority parameter is None, it is ignored.
	// @pyparm int|grfMode||Specifies the access mode to use when opening the storage object. See the STGM enumeration values for descriptions of the possible values. Whatever other modes you may choose, you must at least specify STGM_SHARE_EXCLUSIVE when calling this method. 
	// @pyparm <o SNB>|snbExclude||Reserved for later - Must be None
	// @pyparm int|reserved|0|Reserved integer param.
	PyObject *obName;
	PyObject *obpstgPriority;
	DWORD grfMode;
	DWORD reserved = 0;
	char *temp = NULL;
	if ( !PyArg_ParseTuple(args, "OOi|zi:OpenStorage", &obName, &obpstgPriority, &grfMode, &temp, &reserved) )
		return NULL;
	IStorage *pstgPriority;
	IStorage *ppstg;
	BOOL bPythonIsHappy = TRUE;
	BSTR bstrName;
	bPythonIsHappy = PyWinObject_AsBstr(obName, &bstrName, TRUE);
	if (!PyCom_InterfaceFromPyObject(obpstgPriority, IID_IStorage, (void **)&pstgPriority, TRUE /* bNoneOK */))
		 bPythonIsHappy = FALSE;
	if (!bPythonIsHappy) return NULL;
	PY_INTERFACE_PRECALL;
	HRESULT hr = pIS->OpenStorage( bstrName, pstgPriority, grfMode, NULL, reserved, &ppstg );
	if ( pstgPriority != NULL )
		pstgPriority->Release();
	PyWinObject_FreeBstr(bstrName);
	PY_INTERFACE_POSTCALL;
	if ( FAILED(hr) )
		return PyCom_BuildPyException(hr, pIS, IID_IStorage);

	return PyCom_PyObjectFromIUnknown(ppstg, IID_IStorage, FALSE);
}
Beispiel #16
0
void SaveMsg2File(){
	ULONG cbStrSize = 0L;
	LPWSTR lpWideCharStr = NULL;
	wchar_t szPath[_MAX_PATH];
	// get temp file directory
	GetTempPath(_MAX_PATH, szPath);
#ifdef MAPI32_W
	wcscat_s(szPath, L"Correct.msg");
#else 
	wcscat_s(szPath, L"Garbage.msg");
#endif
	IStorage *pStorage = NULL;
	LPMSGSESS pMsgSession = NULL;
	LPMESSAGE pMessage = NULL;
	HRESULT hr = S_OK;

	//LPWSTR subject = L"テスト日本の";// L"ceshi测试12";
	//LPWSTR body = L"テスト日本のテスト日本の"; // L"lhy测试12";
	//LPWSTR receipt = L"*****@*****.**";

	LPWSTR subject = L"Η πολιτική αβεβαιότητα ανησυχεί τις αγορές";// L"ceshi测试12";
	LPWSTR body = L"Η πολιτική αβεβαιότητα ανησυχεί τις αγορές"; // L"lhy测试12";
	LPWSTR receipt = L"*****@*****.**";

	LPSTR subjectA = ConvertUnicode2Ansi(subject);
	LPSTR bodyA = ConvertUnicode2Ansi(body);
	LPSTR receiptA = ConvertUnicode2Ansi(receipt);
	//LPSTR subjectA = "ceshi测试12";
	//LPSTR bodyA = "lhy测试12";
	//LPSTR receiptA = "*****@*****.**";

	do{
		MAPIINIT_0 mapiInit = { 0, MAPI_MULTITHREAD_NOTIFICATIONS };
		hr = MAPIInitialize(&mapiInit);
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		LPMALLOC pMalloc = MAPIGetDefaultMalloc();

		hr = StgCreateDocfile(szPath, STGM_READWRITE | STGM_TRANSACTED | STGM_CREATE, 0, &pStorage);
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		
		hr = OpenIMsgSession(pMalloc, 0, &pMsgSession);
		DEFINE_IF_HR_NT_OK_BREAK(hr);
#ifdef MAPI32_W
		// lhy comment:if load exmapi32.dll, this function will failed with error code 0x80040106.
		hr = OpenIMsgOnIStg(pMsgSession, MAPIAllocateBuffer, MAPIAllocateMore, MAPIFreeBuffer, pMalloc, NULL, pStorage, NULL, 0, MAPI_UNICODE, &pMessage); 
#else
		hr = OpenIMsgOnIStg(pMsgSession, MAPIAllocateBuffer, MAPIAllocateMore, MAPIFreeBuffer, pMalloc, NULL, pStorage, NULL, 0, 0, &pMessage);
#endif
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		hr = WriteClassStg(pStorage, CLSID_MailMessage);
		DEFINE_IF_HR_NT_OK_BREAK(hr);
#ifdef MAPI32_W
		hr = SetPropsW(pMessage, subject, body, receipt, false, false, false, false, FORCE_SAVE);
#else 
		
		hr = SetPropsA(pMessage, subjectA, bodyA, receiptA, false, false, false, false, FORCE_SAVE);
#endif
		DEFINE_IF_HR_NT_OK_BREAK(hr);

		hr = pStorage->Commit(STGC_DEFAULT);
		DEFINE_IF_HR_NT_OK_BREAK(hr);

	} while (0);
	
	delete subjectA;
	delete bodyA;
	delete receiptA;
	if (pMessage){
		pMessage->Release();
		pMessage = NULL;
	}
	if (pStorage){
		pStorage->Release();
		pStorage = NULL;
	}
	if (pMsgSession){
		CloseIMsgSession(pMsgSession);
		pMsgSession = NULL;
	}
	MAPIUninitialize();
}
Beispiel #17
0
BOOL RichEdit_InsertSkin(CDuiRichEdit *pRicheditCtrl, CDuiSkinBase *pSkin)
{
	IRichEditOle *pRichEditOle=NULL;
	LRESULT lRes=pRicheditCtrl->DuiSendMessage(EM_GETOLEINTERFACE,0,(LPARAM)&pRichEditOle);
	if(!pRichEditOle) return FALSE;

	SCODE sc;
	IOleClientSite *pOleClientSite = NULL;
	pRichEditOle->GetClientSite(&pOleClientSite);
	if (NULL == pOleClientSite)
		return FALSE;

	IStorage *pStorage = NULL;

	LPLOCKBYTES lpLockBytes = NULL;
	sc = ::CreateILockBytesOnHGlobal(NULL, TRUE, &lpLockBytes);
	if (sc != S_OK)
		return FALSE;

	sc = ::StgCreateDocfileOnILockBytes(lpLockBytes,
		STGM_SHARE_EXCLUSIVE|STGM_CREATE|STGM_READWRITE, 0, &pStorage);
	if (sc != S_OK)
	{
		lpLockBytes->Release();
		lpLockBytes = NULL;
		return FALSE;
	}


	CImageOle *pImageOle = new CImageOle(pRicheditCtrl);
	if (NULL == pImageOle)
		return FALSE;

	pImageOle->SetDuiSkinObj(pSkin);

	IOleObject *pOleObject = NULL;
	pImageOle->QueryInterface(IID_IOleObject, (void **)&pOleObject);
	if (NULL == pOleObject)
	{
		delete pImageOle;
		return FALSE;
	}

	pImageOle->SetClientSite(pOleClientSite);

	HRESULT hr = ::OleSetContainedObject(pOleObject, TRUE);

	REOBJECT reobject = {0};
	reobject.cbStruct = sizeof(REOBJECT);
	reobject.clsid    = CLSID_NULL;
	reobject.cp       = REO_CP_SELECTION;
	reobject.dvaspect = DVASPECT_CONTENT;
	reobject.poleobj  = pOleObject;
	reobject.polesite = pOleClientSite;
	reobject.pstg     = pStorage;
	reobject.dwUser   = 0;

	pRichEditOle->InsertObject(&reobject);

	pOleObject->Release();
	pOleClientSite->Release();
	pStorage->Release();
	pRichEditOle->Release();

	return TRUE;
}
Beispiel #18
0
	void CImageDataObject::InsertBitmap(IRichEditOle* pRichEditOle, HBITMAP hBitmap)
	{
		SCODE sc;

		// Get the image data object
		//
		CImageDataObject *pods = new CImageDataObject;
		LPDATAOBJECT lpDataObject;
		pods->QueryInterface(IID_IDataObject, (void **)&lpDataObject);

		pods->SetBitmap(hBitmap);

		// Get the RichEdit container site
		//
		IOleClientSite *pOleClientSite;	
		pRichEditOle->GetClientSite(&pOleClientSite);

		// Initialize a Storage Object
		//
		IStorage *pStorage;	

		LPLOCKBYTES lpLockBytes = NULL;
		sc = ::CreateILockBytesOnHGlobal(NULL, TRUE, &lpLockBytes);
		if (sc != S_OK)
			AfxThrowOleException(sc);
		ASSERT(lpLockBytes != NULL);
		
		sc = ::StgCreateDocfileOnILockBytes(lpLockBytes,
			STGM_SHARE_EXCLUSIVE|STGM_CREATE|STGM_READWRITE, 0, &pStorage);
		if (sc != S_OK)
		{
			VERIFY(lpLockBytes->Release() == 0);
			lpLockBytes = NULL;
			AfxThrowOleException(sc);
		}
		ASSERT(pStorage != NULL);

		// The final ole object which will be inserted in the richedit control
		//
		IOleObject *pOleObject; 
		pOleObject = pods->GetOleObject(pOleClientSite, pStorage);
		if(!pOleObject)
			AfxThrowOleException(sc);

		// all items are "contained" -- this makes our reference to this object
		//  weak -- which is needed for links to embedding silent update.
		OleSetContainedObject(pOleObject, TRUE);

		// Now Add the object to the RichEdit 
		//
		REOBJECT reobject;
		ZeroMemory(&reobject, sizeof(REOBJECT));
		reobject.cbStruct = sizeof(REOBJECT);
		
		CLSID clsid;
		sc = pOleObject->GetUserClassID(&clsid);
		if (sc != S_OK)
			AfxThrowOleException(sc);

		reobject.clsid = clsid;
		reobject.cp = REO_CP_SELECTION;
		reobject.dvaspect = DVASPECT_CONTENT;
		reobject.poleobj = pOleObject;
		reobject.polesite = pOleClientSite;
		reobject.pstg = pStorage;

		// Insert the bitmap at the current location in the richedit control
		//
		pRichEditOle->InsertObject(&reobject);

		// Release all unnecessary interfaces
		//
		pOleObject->Release();
		pOleClientSite->Release();
		pStorage->Release();
		lpDataObject->Release();
	}
// returns true on success, false on failure
//bool InsertBitmap(IRichEditOle* pRichEditOle, HBITMAP hBitmap, HGLOBAL hGlobal)
bool InsertBitmap(IRichEditOle* pRichEditOle, HENHMETAFILE hEmf)
{
	SCODE sc;

	// Get the image data object
	//
	static const FORMATETC lc_format[] =
	{
		{ CF_ENHMETAFILE, 0, DVASPECT_CONTENT, -1, TYMED_ENHMF }//,
		//		{ CF_BITMAP, 0, DVASPECT_CONTENT, -1, TYMED_GDI },
		//		{ CF_TEXT,   0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL } 
	};

	STGMEDIUM lc_stgmed[] =
	{
		{ TYMED_ENHMF, { (HBITMAP)hEmf }, 0 }//,
		//		{ TYMED_GDI, { hBitmap }, 0 },
		//		{ TYMED_HGLOBAL, { (HBITMAP)hGlobal }, 0 }
	};

	IDataObject *pods;
	CreateDataObject(lc_format, lc_stgmed, 1, &pods);

	// Get the RichEdit container site
	//
	IOleClientSite *pOleClientSite;
	pRichEditOle->GetClientSite(&pOleClientSite);

	// Initialize a Storage Object
	//
	LPLOCKBYTES lpLockBytes = NULL;
	sc = CreateILockBytesOnHGlobal(NULL, TRUE, &lpLockBytes);
	if (sc != S_OK)
	{
		pOleClientSite->Release();
		return false;
	}

	IStorage *pStorage;
	sc = StgCreateDocfileOnILockBytes(lpLockBytes,
		STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, &pStorage);
	if (sc != S_OK)
	{
		lpLockBytes->Release();
		pOleClientSite->Release();
		return false;
	}

	// The final ole object which will be inserted in the richedit control
	//
	IOleObject *pOleObject;
	sc = OleCreateStaticFromData(pods, IID_IOleObject, OLERENDER_FORMAT,
		(LPFORMATETC)lc_format, pOleClientSite, pStorage, (void **)&pOleObject);
	if (sc != S_OK)
	{
		pStorage->Release();
		lpLockBytes->Release();
		pOleClientSite->Release();
		return false;
	}

	// all items are "contained" -- this makes our reference to this object
	//  weak -- which is needed for links to embedding silent update.
	OleSetContainedObject(pOleObject, TRUE);

	// Now Add the object to the RichEdit 
	//
	REOBJECT reobject = { 0 };

	reobject.cbStruct = sizeof(REOBJECT);
	reobject.cp = REO_CP_SELECTION;
	reobject.dvaspect = DVASPECT_CONTENT;
	reobject.poleobj = pOleObject;
	reobject.polesite = pOleClientSite;
	reobject.pstg = pStorage;
	reobject.dwFlags = REO_BELOWBASELINE;

	sc = pOleObject->GetUserClassID(&reobject.clsid);
	if (sc != S_OK)
	{
		pOleObject->Release();
		pStorage->Release();
		lpLockBytes->Release();
		pOleClientSite->Release();
		return false;
	}

	// Insert the bitmap at the current location in the richedit control
	//
	sc = pRichEditOle->InsertObject(&reobject);

	// Release all unnecessary interfaces
	//
	pOleObject->Release();
	pStorage->Release();
	lpLockBytes->Release();
	pOleClientSite->Release();
	pods->Release();

	return sc == S_OK;
}
BOOL CChildFrame::OpenCompositeDocument(LPCTSTR lpszFileName) 
{ 
    USES_CONVERSION; 

    CWaitCursor wait; 

    HRESULT hResult = E_FAIL; 
    IStorage * ptrRootStg = NULL; // root storage 
    HWND hWnd = (HWND)m_hWnd; 

    hResult = ::StgIsStorageFile( T2COLE(m_szFileName) ); 
    if( S_OK != hResult ) 
    { 
        TCHAR szFmt[MAX_PATH] = { 0 }; 
        AtlLoadString(IDS_OPEN_ARCHIVE_ERROR, szFmt, _countof(szFmt)); 

        TCHAR szOut[MAX_PATH*2] = { 0 }; 
        wnsprintf(szOut, _countof(szOut), szFmt, lpszFileName); 

        AtlMessageBox(m_hWnd, szOut, IDS_ERROR, MB_OK|MB_ICONSTOP); 
        return FALSE; 
    }

    // open the Compound document 
    hResult = ::StgOpenStorage( T2COLE(m_szFileName), NULL, 
        STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 
        0, 0, &ptrRootStg ); 
    if( FAILED(hResult) )
    { 
        TCHAR szFmt[MAX_PATH] = { 0 }; 
        AtlLoadString(IDS_OPEN_FILE_ERROR, szFmt, _countof(szFmt)); 

        TCHAR szError[MAX_PATH] = { 0 }; 

        TCHAR szOut[MAX_PATH*2] = { 0 }; 
        wnsprintf(szOut, _countof(szOut), szFmt, 
            lpszFileName, GetErrorString(S_OK, szError, _countof(szError))); 

        AtlMessageBox(m_hWnd, szOut, IDS_ERROR, MB_OK|MB_ICONSTOP); 
        return FALSE;
    } 

    TREE_ITEM_DATA * pRootData = new TREE_ITEM_DATA(ptrRootStg, STGTY_STORAGE); 

    HTREEITEM hRoot = m_wndCatalog.InsertItem ( 
        TVIF_IMAGE|TVIF_TEXT|TVIF_PARAM|TVIF_SELECTEDIMAGE, 
        PathFindFileName(m_szFileName), 
        0, 1, TVIS_EXPANDED, 0, 
        reinterpret_cast<LPARAM>(pRootData), 
        NULL, NULL); 


    std::stack < StgInfo > FolderStack; 
    HTREEITEM htiParent = hRoot; 
    IEnumSTATSTG * ptrEnum = NULL; 

    hResult = ptrRootStg->EnumElements( 0, NULL, 0, &ptrEnum ); 
    if( FAILED(hResult) ) { 
        ptrRootStg->Release(); 
        return 0; 
    } 

    TCHAR szSwap[MAX_PATH] = { 0 }; 

	LARGE_INTEGER nStorageLength;
	nStorageLength.QuadPart = 0;
    STATSTG StatStg = { 0 }; 
    while( S_OK == hResult ) 
    { 
        hResult = ptrEnum->Next( 1, &StatStg, NULL ); 
        if( S_FALSE == hResult ) 
        { 
            ptrRootStg->Release(); 
            ptrEnum->Release(); 

            // m_wndCatalog.Expand(strFolder); 

            if( !FolderStack.empty() ) 
            { 
				TCHAR szCurText[MAX_PATH] = {0};
				m_wndCatalog.GetItemText(htiParent, szCurText, _countof(szCurText));
				CString strTotal;
				strTotal.Format(TEXT("%s(%ld)"), szCurText, nStorageLength);
				m_wndCatalog.SetItemText(htiParent, strTotal);

				ptrRootStg  = FolderStack.top().pStg; 
                ptrEnum     = FolderStack.top().pEnum; 
                htiParent   = FolderStack.top().hParent; 
                FolderStack.pop(); 

                hResult = S_OK; 
            } 

            continue; 
        } 

        switch(StatStg.type) 
        { 
        case STGTY_STORAGE: // 是存储对象, "文件夹" 
            { 
				//先清零
				nStorageLength.QuadPart = 0;
                IStorage * ptrChildStg = NULL;

                HRESULT hr = ptrRootStg->OpenStorage( StatStg.pwcsName, NULL, 
                    STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 
                    0, 0, &ptrChildStg ); 
                if( SUCCEEDED(hr) ) 
                { 
                    TREE_ITEM_DATA * pData = new TREE_ITEM_DATA(ptrChildStg, StatStg.type); 

                    HTREEITEM hFolder = m_wndCatalog.InsertItem ( 
                        TVIF_IMAGE|TVIF_TEXT|TVIF_PARAM|TVIF_SELECTEDIMAGE, 
                        WCHAR2TCHAR(StatStg.pwcsName, szSwap, _countof(szSwap)), 
                        0, 1, TVIS_EXPANDED, 0, 
                        reinterpret_cast<LPARAM>(pData), 
                        htiParent, NULL); 

                    // 父存储入栈 
                    FolderStack.push( StgInfo(ptrRootStg, ptrEnum, htiParent) );

                    // 子存储替代父存储 
                    ptrRootStg = ptrChildStg; 
                    htiParent = hFolder; 
                    hr = ptrChildStg->EnumElements( 0, NULL, 0, &ptrEnum ); 
                } 
            } 
            break; 
        case STGTY_STREAM:  // 是流, "文件" 
            { 
                CComPtr<IStream> spStream; 
                HRESULT hr = ptrRootStg->OpenStream(StatStg.pwcsName, NULL, 
                    STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &spStream); 
                ATLASSERT(SUCCEEDED(hr)); 
				
				LARGE_INTEGER nSeekPos;
				nSeekPos.QuadPart = 0LL;
				ULARGE_INTEGER nLength = {0};
				hr = spStream->Seek(nSeekPos, STREAM_SEEK_END, &nLength);
				CString strStreamName;
				WCHAR2TCHAR(StatStg.pwcsName, szSwap, _countof(szSwap));
				if (SUCCEEDED(hr))
				{
					nStorageLength.QuadPart += nLength.QuadPart;
					strStreamName.Format(TEXT("%s(%ld)"), szSwap, nLength);
				}
				else
				{
					strStreamName.Format(TEXT("%s(0)"), szSwap);
				}
                TREE_ITEM_DATA * pData = new TREE_ITEM_DATA(spStream, StatStg.type); 
                m_wndCatalog.InsertItem ( 
                    TVIF_IMAGE|TVIF_TEXT|TVIF_PARAM|TVIF_SELECTEDIMAGE, 
                    strStreamName, 
                    2, 2, TVIS_EXPANDED, 0, 
                    reinterpret_cast<LPARAM>(pData), 
                    htiParent, NULL); 
            } 
            break; 
        case STGTY_LOCKBYTES: 
            ATLTRACE(_T("===== STGTY_LOCKBYTES %d ====="), StatStg.type); 
            break; 
        case STGTY_PROPERTY: 
            ATLTRACE(_T("===== STGTY_PROPERTY %d ====="), StatStg.type); 
            break; 
        default: 
            ATLASSERT(!_T("Unknown storage type!!!")); 
            break; 
        } 

        ::CoTaskMemFree( StatStg.pwcsName ); // 释放名称所使用的内存 
    }

    return 0;
}
Beispiel #21
0
// Does:   Saves The Picture That Is Stored In The IPicture Object As a Bitmap
// ~~~~    (Converts From Any Known Picture Type To a Bitmap / Icon File)
//
// InPut:  sFilePathName - Path And FileName Target To Save
// ~~~~~
//
// OutPut: TRUE If Succeeded...
// ~~~~~~
//-----------------------------------------------------------------------------
BOOL CPicture_Ex::SaveAsBitmap(CString sFilePathName)
//=============================================================================
{
 BOOL bResult = FALSE;
 ILockBytes *Buffer = 0;
 IStorage   *pStorage = 0;
 IStream    *FileStream = 0;
 BYTE    *BufferBytes;
 STATSTG  BytesStatistics;
 DWORD  OutData;
 long  OutStream;
 CFile  BitmapFile; CFileException e;
 double  SkipFloat = 0;
 DWORD  ByteSkip = 0;
 _ULARGE_INTEGER RealData;



 CreateILockBytesOnHGlobal(NULL, TRUE, &Buffer); // Create ILockBytes Buffer



 HRESULT hr = ::StgCreateDocfileOnILockBytes(Buffer,
     STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, &pStorage);



 hr = pStorage->CreateStream(L"PICTURE",
   STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, 0, &FileStream);



 m_pPict->SaveAsFile(FileStream, TRUE, &OutStream); // Copy Data Stream
 FileStream->Release();
 pStorage->Release();
 Buffer->Flush(); 



 // Get Statistics For Final Size Of Byte Array
 Buffer->Stat(&BytesStatistics, STATFLAG_NONAME);



 // Cut UnNeeded Data Coming From SaveAsFile() (Leave Only "Pure" Picture Data)
 SkipFloat = (double(OutStream) / 512); // Must Be In a 512 Blocks...
 if(SkipFloat > DWORD(SkipFloat)) ByteSkip = (DWORD)SkipFloat + 1;
 else ByteSkip = (DWORD)SkipFloat;
 ByteSkip = ByteSkip * 512; // Must Be In a 512 Blocks...
 
 // Find Difference Between The Two Values
 ByteSkip = (DWORD)(BytesStatistics.cbSize.QuadPart - ByteSkip);



 // Allocate Only The "Pure" Picture Data
 RealData.LowPart = 0;
 RealData.HighPart = 0;
 RealData.QuadPart = ByteSkip;
 BufferBytes = (BYTE*)malloc(OutStream);
 if(BufferBytes == NULL)
  {
  Buffer->Release();
  HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
  MessageBoxEx(hWnd, "Can not allocate enough memory\t", "ERROR"/*ERROR_TITLE*/, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
  }



 Buffer->ReadAt(RealData, BufferBytes, OutStream, &OutData);



 if(BitmapFile.Open(sFilePathName, CFile::typeBinary | CFile::modeCreate | CFile::modeWrite, &e))
  {
  BitmapFile.Write(BufferBytes, OutData);
  BitmapFile.Close();
  bResult = TRUE;
  }
 else // Write File Failed...
  {
  TCHAR szCause[255];
  e.GetErrorMessage(szCause, 255, NULL);
  HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
  MessageBoxEx(hWnd, szCause, "ERROR"/*ERROR_TITLE*/, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
  bResult = FALSE;
  }
 
 Buffer->Release();
 free(BufferBytes);



 return(bResult);
}
Beispiel #22
0
// Static member functions
void CImageDataObject::InsertBitmap(IRichEditOle* pRichEditOle, HBITMAP hBitmap) {
	LPLOCKBYTES lpLockBytes = NULL;
	SCODE sc = ::CreateILockBytesOnHGlobal(NULL, TRUE, &lpLockBytes);

	if(sc != S_OK) {
		DeleteObject(hBitmap);
		pRichEditOle->Release();	
		dcdebug("Thrown OLE Exception: %d\n", sc);
		return;
	}
	dcassert(lpLockBytes != NULL);
	
	// Initialize a Storage Object
	IStorage *pStorage = NULL;	
	sc = ::StgCreateDocfileOnILockBytes(lpLockBytes,
		STGM_SHARE_EXCLUSIVE|STGM_CREATE|STGM_READWRITE, 0, &pStorage);
	
	if(sc != S_OK) {
		DeleteObject(hBitmap);
		pRichEditOle->Release();	
		lpLockBytes->Release();
		lpLockBytes = NULL;
		dcdebug("Thrown OLE Exception: %d\n", sc);
		return;
	}
	dcassert(pStorage != NULL);

	CImageDataObject pods;
                        pods.SetBitmap(hBitmap);

	// Get the RichEdit container site
                        IOleClientSite *pOleClientSite;
	pRichEditOle->GetClientSite(&pOleClientSite);
		
	// The final ole object which will be inserted in the richedit control
	IOleObject* pOleObject = pods.GetOleObject(pOleClientSite, pStorage);

	if(pOleObject != NULL) {
		// all items are "contained" -- this makes our reference to this object
		//  weak -- which is needed for links to embedding silent update.
                                        OleSetContainedObject(pOleObject, TRUE);

		// Now Add the object to the RichEdit 
		REOBJECT reobject = { 0 };
		reobject.cbStruct = sizeof(REOBJECT);
	
		CLSID clsid;
		sc = pOleObject->GetUserClassID(&clsid);

		if(sc != S_OK) {
			pRichEditOle->Release();
			DeleteObject(hBitmap);
			dcdebug("Thrown OLE Exception: %d\n", sc);
			return;
		}

		reobject.clsid = clsid;
		reobject.cp = REO_CP_SELECTION;
		reobject.dvaspect = DVASPECT_CONTENT;
		reobject.dwFlags = REO_BELOWBASELINE;
		reobject.poleobj = pOleObject;
		reobject.polesite = pOleClientSite;
		reobject.pstg = pStorage;

		// Insert the bitmap at the current location in the richedit control
		pRichEditOle->InsertObject(&reobject);

		// Release all unnecessary interfaces
                                        pOleObject->Release();
                                }

                                pOleClientSite->Release();
                lpLockBytes->Release();
	pStorage->Release();
    pRichEditOle->Release();
	DeleteObject(hBitmap);
}
Beispiel #23
0
// returns true on success, false on failure
bool ImageDataObject::InsertBitmap(IRichEditOle* pRichEditOle, HBITMAP hBitmap)
{
	BITMAP bminfo;

	// Get the image data object
	//
	ImageDataObject *pods = new ImageDataObject;

	GetObject(hBitmap, sizeof(bminfo), &bminfo);
	pods->SetBitmap(hBitmap);

	// Get the RichEdit container site
	//
	IOleClientSite *pOleClientSite;
	pRichEditOle->GetClientSite(&pOleClientSite);

	// Initialize a Storage Object
	//

	LPLOCKBYTES lpLockBytes = nullptr;
	SCODE sc = ::CreateILockBytesOnHGlobal(nullptr, TRUE, &lpLockBytes);
	if (sc != S_OK) {
		pOleClientSite->Release();
		return false;
	}

	IStorage *pStorage;
	sc = ::StgCreateDocfileOnILockBytes(lpLockBytes, STGM_SHARE_EXCLUSIVE | STGM_CREATE | STGM_READWRITE, 0, &pStorage);
	if (sc != S_OK) {
		lpLockBytes = nullptr;
		pOleClientSite->Release();
		return false;
	}
	// The final ole object which will be inserted in the richedit control
	//
	IOleObject *pOleObject;
	pOleObject = pods->GetOleObject(pOleClientSite, pStorage);
	if (pOleObject == nullptr) {
		pStorage->Release();
		pOleClientSite->Release();
		return false;
	}

	// all items are "contained" -- this makes our reference to this object
	//  weak -- which is needed for links to embedding silent update.
	OleSetContainedObject(pOleObject, TRUE);

	// Now Add the object to the RichEdit
	//
	REOBJECT reobject;
	memset(&reobject, 0, sizeof(REOBJECT));
	reobject.cbStruct = sizeof(REOBJECT);

	CLSID clsid;
	sc = pOleObject->GetUserClassID(&clsid);
	if (sc != S_OK) {
		pOleObject->Release();
		pStorage->Release();
		pOleClientSite->Release();
		return false;
	}

	reobject.clsid = clsid;
	reobject.cp = REO_CP_SELECTION;
	reobject.dvaspect = DVASPECT_CONTENT;
	reobject.poleobj = pOleObject;
	reobject.polesite = pOleClientSite;
	reobject.pstg = pStorage;
	reobject.dwFlags = bminfo.bmHeight <= 12 ? 0 : REO_BELOWBASELINE;

	// Insert the bitmap at the current location in the richedit control
	//
	sc = pRichEditOle->InsertObject(&reobject);

	// Release all unnecessary interfaces
	//
	pOleObject->Release();
	pOleClientSite->Release();
	lpLockBytes->Release();
	pStorage->Release();
	return sc == S_OK;
}
Beispiel #24
0
BOOL CDocFile::Load(TCHAR* wszFilePath)
{
	IStorage *pStorage = NULL;
    IPropertySetStorage *pPropSetStg = NULL;
	IStream *pStream = NULL, *pTableStream = NULL;
    HRESULT hr;
	
	// Open the document as an OLE compound document.
	hr = ::StgOpenStorage(wszFilePath, NULL,
    STGM_READWRITE | STGM_SHARE_EXCLUSIVE, NULL, 0, &pStorage);
	if(FAILED(hr)) {
		_tprintf( L"A file is locked by another program: [%s]\n", wszFilePath);
		return FALSE;
	}

#ifdef CONTENT_EXTRACTION

	hr = pStorage->OpenStream(L"WordDocument", NULL, STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, &pStream);
	if(FAILED(hr)) {
		_tprintf( L"A file is invalid or damaged: [%s]\n", wszFilePath);
		pStorage->Release();
		return FALSE;
	}
	STATSTG stat;
	pStream->Stat(&stat, 0);
	UINT size = (UINT) stat.cbSize.QuadPart;
	BYTE *buffer = new BYTE[size];
	USHORT usFlag;
	INT	pdcOffset;
	UINT pdcLength;
	LARGE_INTEGER liTmpSeek;
	ULONG cbRead;
	liTmpSeek.QuadPart = 10;
	pStream->Seek(liTmpSeek, 0, NULL);
	pStream->Read(&usFlag, 2, &cbRead);
	liTmpSeek.QuadPart = 418;
	pStream->Seek(liTmpSeek, 0, NULL);
	pStream->Read(&pdcOffset, 4, &cbRead);
	pStream->Read(&pdcLength, 4, &cbRead);

	hr = pStorage->OpenStream((usFlag & (0x1 << 9)) ? L"1Table" : L"0Table", NULL, STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, &pTableStream);
	liTmpSeek.QuadPart = pdcOffset;
    pTableStream->Seek(liTmpSeek, 0, NULL);

	INT nCount = 0;
	INT *aOffsets = NULL;
	struct Desc {
		BYTE Flags;
		BYTE Fn;
		UINT32  Fc;
		SHORT Prm;
	} *aDescs = NULL;
	UINT nPointer = 0;

	while (nPointer < pdcLength)
	{
		BYTE nType = 0;
		pTableStream->Read(&nType, 1, &cbRead);
        
		switch(nType)
		{
		case 0:
			BYTE nTmp;
			pTableStream->Read(&nTmp, 1, &cbRead);
			nPointer++;
			break;

		case 1:
			{
			SHORT cbGrpprl;
			BYTE *grpprlData = NULL;
			pTableStream->Read(&cbGrpprl, 2, &cbRead);
			nPointer+=2;
			grpprlData = new BYTE[cbGrpprl];
			pTableStream->Read(grpprlData, cbGrpprl, &cbRead);
			nPointer+=cbGrpprl;
			delete grpprlData;
			break;
			}
		case 2:

			INT nTableLen = 0;
			pTableStream->Read(&nTableLen, 4, &cbRead);
			nPointer+=4;

			nCount = (nTableLen - 4) / (8 + 4) + 1;
			aOffsets = new INT[nCount];
			for(int i = 0; i < nCount; i++) {
				pTableStream->Read(&aOffsets[i], 4, &cbRead);
				nPointer +=4;
			}

			aDescs = new Desc[nCount-1];
			for(int i = 0; i < nCount-1; i++) {
				pTableStream->Read(&aDescs[i].Flags, 1, &cbRead);
				pTableStream->Read(&aDescs[i].Fn, 1, &cbRead);
				pTableStream->Read(&aDescs[i].Fc, 4, &cbRead);
				pTableStream->Read(&aDescs[i].Prm, 2, &cbRead);
				nPointer+=sizeof(struct Desc);
			}
			break;
		}
	}

	for (int i = 0; i < nCount - 1; i++)
	{
		UINT pieceStart = 0xffffffff;
		UINT pieceEnd = 0xffffffff;
		BOOL bUnicode = FALSE;

		bUnicode = (aDescs[i].Fc & (1 << 30)) == 0 ? 1 : 0;
		if (!bUnicode)
			pieceStart = (aDescs[i].Fc & ~(1 << 30)) / 2;
		else
			pieceStart = aDescs[i].Fc;

		UINT nLength = aOffsets[i + 1] - aOffsets[i];
		pieceEnd = pieceStart + nLength * (bUnicode ? 2 : 1);

		liTmpSeek.QuadPart = pieceStart;
		hr = pStream->Seek(liTmpSeek, 0, NULL);
		//m_wszContent += ReadString(documentReader, pieceEnd - pieceStart, isUnicode);
		if (nLength == 0)
			continue;

		for (UINT i = 0; i < nLength; i++)
		{
			if (!bUnicode)
			{
				BYTE ch = 0;
				pStream->Read(&ch, 1, NULL);
				m_wszContent += (CHAR)ch;
			}
			else
			{
				SHORT ch = 0;
				pStream->Read(&ch, 2, NULL);
				m_wszContent += (WCHAR)ch;
			}	
		}
	}
	pStream->Release();
	pTableStream->Release();

#endif

	// Obtain the IPropertySetStorage interface.
	hr = pStorage->QueryInterface(IID_IPropertySetStorage, (void **)&pPropSetStg);
	IPropertyStorage *pPropStg = NULL;

	struct pidsiStruct {
		TCHAR *name;
		LONG pid;
	} pidsiArr[] = {
		{L"Author",           PIDSI_AUTHOR},
		{L"Title",            PIDSI_TITLE},
		{L"Subject",          PIDSI_SUBJECT},
		{L"Keywords",         PIDSI_KEYWORDS},
		{L"Status",			  PIDMSI_STATUS},
		{L"AppName",          PIDSI_APPNAME}, 
		{L"Comments",         PIDSI_COMMENTS},
		{L"Template",         PIDSI_TEMPLATE},
		{L"Revision Number",  PIDSI_REVNUMBER},
		{L"Created",          PIDSI_CREATE_DTM},
		{L"Edit Time",        PIDSI_EDITTIME},
		{L"Last Saved",       PIDSI_LASTSAVE_DTM},
		{L"LastAuthor",       PIDSI_LASTAUTHOR},
		{L"Last printed",     PIDSI_LASTPRINTED},
		{L"Page Count",       PIDSI_PAGECOUNT},
		{L"Word Count",       PIDSI_WORDCOUNT},
		{L"Char Count",       PIDSI_CHARCOUNT},
		{L"Thumbnail",        PIDSI_THUMBNAIL},
		{L"Doc Security",     PIDSI_DOC_SECURITY},
		{0, 0}
	}, pidsdiArr[] = {
		{L"Company",		  PIDDSI_COMPANY},
		{L"Slide notes",      PIDDSI_SLIDECOUNT},
		{0, 0}
	};
	
	// Count elements in pidsiArr.
	INT nPidsi = 0, nPidsdi = 0;
	for(nPidsi=0; pidsiArr[nPidsi].name; nPidsi++);
	for(nPidsdi=0; pidsdiArr[nPidsdi].name; nPidsdi++);
	  
	// Initialize PROPSPEC for the properties you want.
	PROPSPEC *pPropSpec = new PROPSPEC [nPidsi];
	PROPVARIANT *pPropVar = new PROPVARIANT [nPidsi];
	PROPSPEC *pDocPropSpec = new PROPSPEC [nPidsdi];
	PROPVARIANT *pDocPropVar = new PROPVARIANT [nPidsdi];

	for(INT i=0; i<nPidsi; i++) {
		ZeroMemory(&pPropSpec[i], sizeof(PROPSPEC));
		pPropSpec[i].ulKind = PRSPEC_PROPID;
		pPropSpec[i].propid = pidsiArr[i].pid;
	}
	for(INT i=0; i<nPidsdi; i++) {
		ZeroMemory(&pDocPropSpec[i], sizeof(PROPSPEC));
		pDocPropSpec[i].ulKind = PRSPEC_PROPID;
		pDocPropSpec[i].propid = pidsdiArr[i].pid;
	}

	// Obtain meta infos from FMTID_SummaryInformation
	hr = pPropSetStg->Open(FMTID_SummaryInformation, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
	// Read properties.
	hr = pPropStg->ReadMultiple(nPidsi, pPropSpec, pPropVar);
	if(FAILED(hr)) {
         _tprintf(L"IPropertyStg::ReadMultiple() failed w/error %08lx",hr);
    }
	pPropStg->Release();
	pPropStg = NULL;

	// Obtain meta infos from FMTID_DocSummaryInformation
	hr = pPropSetStg->Open(FMTID_DocSummaryInformation, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
	// Read properties.
	hr = pPropStg->ReadMultiple(nPidsdi, pDocPropSpec, pDocPropVar);
	if(FAILED(hr)) {
         _tprintf(L"IPropertyStg::ReadMultiple() failed w/error %08lx",hr);
    }
	pPropStg->Release();

	// Copy Meta fields out from FMTID_SummaryInformation
	for(int i = 0; i < nPidsi; i++) {
		switch(pidsiArr[i].pid) {
		case PIDSI_AUTHOR:
			DumpPropVariant(pPropVar + i, m_wszAuthor, MAX_META_LEN);
			break;
		case PIDSI_TITLE:
			DumpPropVariant(pPropVar + i, m_wszTitle, MAX_META_LEN);
			break;
		case PIDSI_SUBJECT:
			DumpPropVariant(pPropVar + i, m_wszSubject, MAX_META_LEN);
			break;
		case PIDSI_KEYWORDS:
			DumpPropVariant(pPropVar + i, m_wszKeywords, MAX_META_LEN);
			break;
		case PIDSI_APPNAME:
			DumpPropVariant(pPropVar + i, m_wszApplication, MAX_META_LEN);
			break;
		case PIDSI_COMMENTS:
			DumpPropVariant(pPropVar + i, m_wszComments, MAX_META_LEN);
			break;
		case PIDSI_TEMPLATE:
			DumpPropVariant(pPropVar + i, m_wszTemplateUsed, MAX_META_LEN);
			break;
		case PIDSI_REVNUMBER:
			DumpPropVariant(pPropVar + i, m_wszRevisionNumber, MAX_META_LEN);
			break;
		case PIDSI_EDITTIME:
			DumpPropVariant(pPropVar + i, m_wszTotalEditingTime, MAX_META_LEN);
			break;
		case PIDSI_LASTSAVE_DTM:
			DumpPropVariant(pPropVar + i, m_wszLastSaved, MAX_META_LEN);
			break;
		case PIDSI_LASTAUTHOR:
			DumpPropVariant(pPropVar + i, m_wszLastEditedBy, MAX_META_LEN);
			break;
		case PIDSI_LASTPRINTED:
			DumpPropVariant(pPropVar + i, m_wszLastPrinted, MAX_META_LEN);
			break;
		case PIDSI_PAGECOUNT:
			DumpPropVariant(pPropVar + i, m_wszPageCount, MAX_META_LEN);
			break;
		case PIDSI_WORDCOUNT:
			DumpPropVariant(pPropVar + i, m_wszWordCount, MAX_META_LEN);
			break;
		case PIDSI_CHARCOUNT:
			DumpPropVariant(pPropVar + i, m_wszCharacterCount, MAX_META_LEN);
			break;
		}
	}

	// Copy Meta fields out from FMTID_DocSummaryInformation
	for(int i = 0; i < nPidsdi; i++) {
		switch(pidsdiArr[i].pid) {
		case PIDDSI_COMPANY:
			DumpPropVariant(pDocPropVar + i, m_wszCompany, MAX_META_LEN);
			break;
		}
	}

	// De-allocate memory.
	delete [] pPropVar;
	delete [] pPropSpec;
	delete [] pDocPropVar;
	delete [] pDocPropSpec;

	// Release obtained interface.
	pPropSetStg->Release();
    pStorage->Release();

	return TRUE;
}