您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ CoInitializeEx函数代码示例

51自学网 2021-06-01 20:12:04
  C++
这篇教程C++ CoInitializeEx函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中CoInitializeEx函数的典型用法代码示例。如果您正苦于以下问题:C++ CoInitializeEx函数的具体用法?C++ CoInitializeEx怎么用?C++ CoInitializeEx使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了CoInitializeEx函数的28个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: main

void main(int argc, char**argv){	std::wcout << L"/n ===================================/n";	std::wcout << L"/n  TextFinderComponent C++ Interface ";	std::wcout << L"/n ===================================/n";	HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);	if (!SUCCEEDED(hr))	{		std::wcout << L"/n  could not initialize COM";	}	try	{		CComQIPtr<ITextCompCOM> TextFinderComp;		TextFinderComp.CoCreateInstance(CLSID_TextCompCOM);				if (TextFinderComp != 0)		{			std::wcout << L"/n =============================================================/n";			std::wcout << "The Text Component Interface was successfully initialized" << std::endl;			std::wcout << L"/n =============================================================/n";			InputArgumentParser parser;			if (parser.parseCommandLineArgs2TextCompArguments(argc, argv))			{				HRESULT h0 = TextFinderComp->InitializeComponent();				HRESULT h1 = TextFinderComp->SetSearchPath(CComBSTR(parser.getDirectoryPath().c_str()));				BSTR allPatterns;				BSTR recursion;				allPatterns = convertstdSTR2BSTR(bool2String(true)) ;    //By default find all patterns								recursion = convertstdSTR2BSTR(bool2String(false)) ;  // By default Recursion is disabled				if (parser.getRecursionFlag())				{					recursion = convertstdSTR2BSTR(bool2String(true));				}				if (!parser.getAllPatternsFlag())				{					allPatterns = convertstdSTR2BSTR(bool2String(false));				}				HRESULT h2 = TextFinderComp->SetSpecialSearchClause(recursion, allPatterns);				HRESULT h3 = TextFinderComp->SetFilePatterns(convertVector2CCOMSafeArray(parser.getFilePatterns()).GetSafeArrayPtr());				HRESULT h4 = TextFinderComp->SetTextPatterns(convertVector2CCOMSafeArray(parser.getTextPatterns()).GetSafeArrayPtr());				if (SUCCEEDED(h0) && SUCCEEDED(h1) && SUCCEEDED(h2) && SUCCEEDED(h3) && SUCCEEDED(h4))				{										SAFEARRAY files;									SAFEARRAY* pFiles = &files;					TextFinderComp->GetQualifyingFileList(&pFiles);					CComSafeArray<BSTR> Files;					Files.Attach(pFiles);						std::wcout << L"/n =============================================================/n";					std::wcout << L"/n =============================================================/n";					std::wcout<<"The Qualifying Files from the Text Search Component via C++ COM interface"<<std::endl;					displayCCOMBSTRFiles(Files);					std::cout << "End of C++ Client for Text Search Component" << std::endl;					std::wcout << L"/n =============================================================/n";				}			}			else			{				parser.displayIllegalArgumentMessage();			}		}	}	catch (std::exception& ex)	{		std::wcout << L"/n  Exception Encountered during COM Stuff .. Contact Admin and Bug Him!" << ex.what() << L"/n/n";		return;	}	std::wcout << L"/n/n";//.........这里部分代码省略.........
开发者ID:mohitb117,项目名称:TextSearch_Windows,代码行数:101,


示例2: CheckForUpdatesThread

/* * Background thread to check for updates */static DWORD WINAPI CheckForUpdatesThread(LPVOID param){	BOOL releases_only, found_new_version = FALSE;	int status = 0;	const char* server_url = RUFUS_URL "/";	int i, j, k, verbose = 0, verpos[4];	static const char* archname[] = {"win_x86", "win_x64"};	static const char* channel[] = {"release", "beta"};		// release channel	const char* accept_types[] = {"*/*/0", NULL};	DWORD dwFlags, dwSize, dwDownloaded, dwTotalSize, dwStatus;	char* buf = NULL;	char agent[64], hostname[64], urlpath[128], mime[32];	OSVERSIONINFOA os_version = {sizeof(OSVERSIONINFOA), 0, 0, 0, 0, ""};	HINTERNET hSession = NULL, hConnection = NULL, hRequest = NULL;	URL_COMPONENTSA UrlParts = {sizeof(URL_COMPONENTSA), NULL, 1, (INTERNET_SCHEME)0,		hostname, sizeof(hostname), 0, NULL, 1, urlpath, sizeof(urlpath), NULL, 1};	SYSTEMTIME ServerTime, LocalTime;	FILETIME FileTime;	int64_t local_time = 0, reg_time, server_time, update_interval;	update_check_in_progress = TRUE;	verbose = ReadRegistryKey32(REGKEY_HKCU, REGKEY_VERBOSE_UPDATES);	// Without this the FileDialog will produce error 0x8001010E when compiled for Vista or later	IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED));	// Unless the update was forced, wait a while before performing the update check	if (!force_update_check) {		// It would of course be a lot nicer to use a timer and wake the thread, but my		// development time is limited and this is FASTER to implement.		do {			for (i=0; (i<30) && (!force_update_check); i++)				Sleep(500);		} while ((!force_update_check) && ((iso_op_in_progress || format_op_in_progress || (dialog_showing>0))));		if (!force_update_check) {			if ((ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL) == -1)) {				vuprintf("Check for updates disabled, as per registry settings./n");				goto out;			}			reg_time = ReadRegistryKey64(REGKEY_HKCU, REGKEY_LAST_UPDATE);			update_interval = (int64_t)ReadRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL);			if (update_interval == 0) {				WriteRegistryKey32(REGKEY_HKCU, REGKEY_UPDATE_INTERVAL, DEFAULT_UPDATE_INTERVAL);				update_interval = DEFAULT_UPDATE_INTERVAL;			}			GetSystemTime(&LocalTime);			if (!SystemTimeToFileTime(&LocalTime, &FileTime))				goto out;			local_time = ((((int64_t)FileTime.dwHighDateTime)<<32) + FileTime.dwLowDateTime) / 10000000;			vvuprintf("Local time: %" PRId64 "/n", local_time);			if (local_time < reg_time + update_interval) {				vuprintf("Next update check in %" PRId64 " seconds./n", reg_time + update_interval - local_time);				goto out;			}		}	}	PrintStatus(3000, TRUE, MSG_243);	status++;	// 1	if (!GetVersionExA(&os_version)) {		uprintf("Could not read Windows version - Check for updates cancelled./n");		goto out;	}	if ((!InternetCrackUrlA(server_url, (DWORD)safe_strlen(server_url), 0, &UrlParts)) || (!InternetGetConnectedState(&dwFlags, 0)))		goto out;	hostname[sizeof(hostname)-1] = 0;	safe_sprintf(agent, ARRAYSIZE(agent), APPLICATION_NAME "/%d.%d.%d.%d", rufus_version[0], rufus_version[1], rufus_version[2], rufus_version[3]);	hSession = InternetOpenA(agent, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);	if (hSession == NULL)		goto out;	hConnection = InternetConnectA(hSession, UrlParts.lpszHostName, UrlParts.nPort, NULL, NULL, INTERNET_SERVICE_HTTP, 0, (DWORD_PTR)NULL);	if (hConnection == NULL)		goto out;	status++;	// 2	releases_only = !GetRegistryKeyBool(REGKEY_HKCU, REGKEY_INCLUDE_BETAS);	for (k=0; (k<(releases_only?1:(int)ARRAYSIZE(channel))) && (!found_new_version); k++) {		uprintf("Checking %s channel.../n", channel[k]);		// At this stage we can query the server for various update version files.		// We first try to lookup for "<appname>_<os_arch>_<os_version_major>_<os_version_minor>.ver"		// and then remove each each of the <os_> components until we find our match. For instance, we may first		// look for rufus_win_x64_6.2.ver (Win8 x64) but only get a match for rufus_win_x64_6.ver (Vista x64 or later)		// This allows sunsetting OS versions (eg XP) or providing different downloads for different archs/groups.		safe_sprintf(urlpath, sizeof(urlpath), "%s%s%s_%s_%d.%d.ver", APPLICATION_NAME, (k==0)?"":"_",			(k==0)?"":channel[k], archname[is_x64()?1:0], os_version.dwMajorVersion, os_version.dwMinorVersion);		vuprintf("Base update check: %s/n", urlpath);		for (i=0, j=(int)safe_strlen(urlpath)-5; (j>0)&&(i<ARRAYSIZE(verpos)); j--) {			if ((urlpath[j] == '.') || (urlpath[j] == '_')) {				verpos[i++] = j;			}		}		if (i != ARRAYSIZE(verpos)) {			uprintf("Broken code in CheckForUpdatesThread()!/n");			goto out;		}//.........这里部分代码省略.........
开发者ID:JBTech,项目名称:rufus,代码行数:101,


示例3: wmi_initialize

		}	}	return FALSE;}/** * Initialise the WMI client that will connect to the local machine WMI * namespace. It will return TRUE if the connection was successful, FALSE * otherwise. */int wmi_initialize(const wchar_t *query_namespace, IWbemServices **services) {	BSTR namespace;	IWbemLocator *locator = NULL;	int result;	HRESULT hresult = CoInitializeEx(0, COINIT_MULTITHREADED);	if (FAILED(hresult)) {		return FALSE;	}	hresult = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT,		RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);	if (FAILED(hresult)) {		CoUninitialize();		return FALSE;	}	hresult = CoCreateInstance(&CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER,
开发者ID:a0rtega,项目名称:pafish,代码行数:31,


示例4: wan

/*!   /brief Opens the wan (dialup, vpn...) adapter.  /return If the function succeeds, the return value is the pointer to a properly initialized WAN_ADAPTER structure,   otherwise the return value is NULL.*/PWAN_ADAPTER WanPacketOpenAdapter(){	PWAN_ADAPTER pWanAdapter = NULL;	PBLOB_TABLE pBlobTable = NULL;	HBLOB hFilterBlob = NULL;	HRESULT hResult;	DWORD i;	if ( g_hModule == NULL)	{		g_hModule = LoadLibrary("npp//ndisnpp.dll");	}	if ( g_hModule == NULL)	{		return NULL;	}	hResult = CoInitialize(NULL);	// 	// if  the calling thread has already initialized COM with a  	// different threading model, we have this error 	// however, we are able to support another threading model, 	// so we try to initialize COM with another threading model. 	// This new call should succeed with S_FALSE. 	// 	if (hResult == RPC_E_CHANGED_MODE)	{		hResult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);			//MULTITHREADED threading is only supported on Windows 2000		if (hResult == RPC_E_CHANGED_MODE && IsWindows2000())		{			hResult = CoInitializeEx(NULL, COINIT_MULTITHREADED);		}	}	if (hResult != S_OK && hResult != S_FALSE)		return NULL;	pWanAdapter = (PWAN_ADAPTER)GlobalAlloc(GPTR, sizeof (WAN_ADAPTER));	if ( pWanAdapter == NULL )		goto error;		memset(pWanAdapter, 0, sizeof(WAN_ADAPTER));		if ( CreateBlob(&hFilterBlob) != NMERR_SUCCESS )	{		goto error;	}		if ( SetBoolInBlob(hFilterBlob, OWNER_NPP, CATEGORY_CONFIG, TAG_INTERFACE_REALTIME_CAPTURE, TRUE) != NMERR_SUCCESS )	{		DestroyBlob( hFilterBlob);		goto error;	}	if ( SetBoolInBlob(hFilterBlob, OWNER_NPP, CATEGORY_LOCATION, TAG_RAS, TRUE) != NMERR_SUCCESS )	{		DestroyBlob( hFilterBlob);		goto error;	}	if ( GetNPPBlobTable(hFilterBlob, &pBlobTable) != NMERR_SUCCESS )	{		DestroyBlob( hFilterBlob);		goto error;	}	DestroyBlob (hFilterBlob);	if ( pBlobTable->dwNumBlobs == 0 || pBlobTable->dwNumBlobs > 1)	{		///fixme.....		for ( i = 0 ; i < pBlobTable->dwNumBlobs ; i++ )			DestroyBlob(pBlobTable->hBlobs[i]);				GlobalFree(pBlobTable);		goto error;	}	pWanAdapter->hCaptureBlob = pBlobTable->hBlobs[0];	GlobalFree(pBlobTable);	InitializeCriticalSection(&pWanAdapter->CriticalSection);	pWanAdapter->hReadEvent = CreateEvent(NULL, TRUE, FALSE, NULL);	if ( pWanAdapter->hReadEvent == NULL )		goto error;	pWanAdapter->MemEx.buffer = (PUCHAR)GlobalAlloc(GPTR, DEFAULT_MEM_EX_SIZE);//.........这里部分代码省略.........
开发者ID:chongyc,项目名称:natblaster,代码行数:101,


示例5: wWinMain

INT WINAPI wWinMain(    _In_ HINSTANCE hInstance,    _In_opt_ HINSTANCE hPrevInstance,    _In_ PWSTR lpCmdLine,    _In_ INT nCmdShow){    LONG result;#ifdef DEBUG    PHP_BASE_THREAD_DBG dbg;#endif    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);#ifndef DEBUG    SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);#endif    PhInstanceHandle = (HINSTANCE)NtCurrentPeb()->ImageBaseAddress;    if (!NT_SUCCESS(PhInitializePhLib()))        return 1;    if (!PhInitializeAppSystem())        return 1;    PhInitializeCommonControls();    if (PhCurrentTokenQueryHandle)    {        PTOKEN_USER tokenUser;        if (NT_SUCCESS(PhGetTokenUser(PhCurrentTokenQueryHandle, &tokenUser)))        {            PhCurrentUserName = PhGetSidFullName(tokenUser->User.Sid, TRUE, NULL);            PhFree(tokenUser);        }    }    PhLocalSystemName = PhGetSidFullName(&PhSeLocalSystemSid, TRUE, NULL);    // There has been a report of the above call failing.    if (!PhLocalSystemName)        PhLocalSystemName = PhCreateString(L"NT AUTHORITY//SYSTEM");    PhApplicationFileName = PhGetApplicationFileName();    PhApplicationDirectory = PhGetApplicationDirectory();    // Just in case    if (!PhApplicationFileName)        PhApplicationFileName = PhCreateString(L"ProcessHacker.exe");    if (!PhApplicationDirectory)        PhApplicationDirectory = PhReferenceEmptyString();    PhpProcessStartupParameters();    PhSettingsInitialization();    PhpEnablePrivileges();    if (PhStartupParameters.RunAsServiceMode)    {        RtlExitUserProcess(PhRunAsServiceStart(PhStartupParameters.RunAsServiceMode));    }    PhpInitializeSettings();    // Activate a previous instance if required.    if (PhGetIntegerSetting(L"AllowOnlyOneInstance") &&            !PhStartupParameters.NewInstance &&            !PhStartupParameters.ShowOptions &&            !PhStartupParameters.CommandMode &&            !PhStartupParameters.PhSvc)    {        PhActivatePreviousInstance();    }    if (PhGetIntegerSetting(L"EnableKph") && !PhStartupParameters.NoKph && !PhIsExecutingInWow64())        PhInitializeKph();    if (PhStartupParameters.CommandMode && PhStartupParameters.CommandType && PhStartupParameters.CommandAction)    {        NTSTATUS status;        status = PhCommandModeStart();        if (!NT_SUCCESS(status) && !PhStartupParameters.Silent)        {            PhShowStatus(NULL, L"Unable to execute the command", status, 0);        }        RtlExitUserProcess(status);    }#ifdef DEBUG    dbg.ClientId = NtCurrentTeb()->ClientId;    dbg.StartAddress = wWinMain;    dbg.Parameter = NULL;    InsertTailList(&PhDbgThreadListHead, &dbg.ListEntry);    TlsSetValue(PhDbgThreadDbgTlsIndex, &dbg);#endif    PhInitializeAutoPool(&BaseAutoPool);//.........这里部分代码省略.........
开发者ID:ventsislav-georgiev,项目名称:processhacker2,代码行数:101,


示例6: StringCchCopyW

/******************************Public*Routine******************************/* OpenMovie*/**************************************************************************/HRESULTCMovie::OpenMovie(    TCHAR *lpFileName    ){    IUnknown        *pUnk;    HRESULT         hres;    WCHAR           FileName[MAX_PATH];    // Check input string    if (lpFileName == NULL)        return E_POINTER;    hres = StringCchCopyW(FileName, NUMELMS(FileName), lpFileName);    hres = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);    if(hres == S_FALSE)        CoUninitialize();    hres = CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC,                            IID_IUnknown, (LPVOID *)&pUnk);    if(SUCCEEDED(hres))    {        m_Mode = MOVIE_OPENED;        hres = pUnk->QueryInterface(IID_IFilterGraph, (LPVOID *)&m_Fg);        if(FAILED(hres))        {            pUnk->Release();            return hres;        }        hres = AddVideoMixingRendererToFG();        if(FAILED(hres))        {            m_Fg->Release(); m_Fg = NULL;            return hres;        }        hres = pUnk->QueryInterface(IID_IGraphBuilder, (LPVOID *)&m_Gb);        if(FAILED(hres))        {            pUnk->Release();            m_Fg->Release(); m_Fg = NULL;            m_Wc->Release(); m_Wc = NULL;            return hres;        }        hres = RenderFileToVideoRenderer( m_Gb, FileName, TRUE);        if(FAILED(hres))        {            pUnk->Release();            m_Fg->Release(); m_Fg = NULL;            m_Wc->Release(); m_Wc = NULL;            m_Gb->Release(); m_Gb = NULL;            return hres;        }        hres = m_Wc->QueryInterface(IID_IVMRMixerControl9, (LPVOID *) &m_pMixControl);        if(FAILED(hres))        {            pUnk->Release();            m_Fg->Release(); m_Fg = NULL;            m_Wc->Release(); m_Wc = NULL;            m_Gb->Release(); m_Gb = NULL;            m_pMixControl = NULL;            return hres;        }        hres = pUnk->QueryInterface(IID_IMediaControl, (LPVOID *)&m_Mc);        if(FAILED(hres))        {            pUnk->Release();            m_Fg->Release(); m_Fg = NULL;            m_Wc->Release(); m_Wc = NULL;            m_Gb->Release(); m_Gb = NULL;            return hres;        }        //        // Not being able to get the IMediaEvent interface doesn't        // necessarly mean that we can't play the graph.        //        pUnk->QueryInterface(IID_IMediaEvent, (LPVOID *)&m_Me);        GetMovieEventHandle();        pUnk->QueryInterface(IID_IMediaSeeking, (LPVOID *)&m_Ms);        pUnk->Release();        return S_OK;    }    else    {        m_Fg = NULL;    }    return hres;//.........这里部分代码省略.........
开发者ID:Essjay1,项目名称:Windows-classic-samples,代码行数:101,


示例7: wWinMain

INT WINAPI wWinMain(    _In_ HINSTANCE hInstance,    _In_opt_ HINSTANCE hPrevInstance,    _In_ PWSTR lpCmdLine,    _In_ INT nCmdShow    ){    PROPSHEETPAGE propSheetPage = { sizeof(PROPSHEETPAGE) };    PROPSHEETHEADER propSheetHeader = { sizeof(PROPSHEETHEADER) };    HPROPSHEETPAGE pages[5];    if (!NT_SUCCESS(PhInitializePhLibEx(0, 0, 0)))        return 1;    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);    PhApplicationName = L"Process Hacker - Setup";    PhGuiSupportInitialization();    PvpInitializeDpi();    propSheetHeader.dwFlags =        PSH_NOAPPLYNOW |        PSH_NOCONTEXTHELP |        PSH_USECALLBACK |        PSH_WIZARD_LITE;    propSheetHeader.hInstance = PhLibImageBase;    propSheetHeader.pszIcon = MAKEINTRESOURCE(IDI_ICON1);    propSheetHeader.pfnCallback = MainPropSheet_Callback;    propSheetHeader.phpage = pages;    // page    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);    propSheetPage.dwFlags = PSP_USETITLE;    propSheetPage.pszTitle = PhApplicationName;    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG1);    propSheetPage.pfnDlgProc = PropSheetPage1_WndProc;    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);    // page    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);    propSheetPage.dwFlags = PSP_USETITLE;    propSheetPage.pszTitle = PhApplicationName;    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG2);    propSheetPage.pfnDlgProc = PropSheetPage2_WndProc;    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);    // page    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG3);    propSheetPage.pfnDlgProc = PropSheetPage3_WndProc;    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);    // page    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);    propSheetPage.dwFlags = PSP_USETITLE;    propSheetPage.pszTitle = PhApplicationName;    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG4);    propSheetPage.pfnDlgProc = PropSheetPage4_WndProc;    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);    // page    memset(&propSheetPage, 0, sizeof(PROPSHEETPAGE));    propSheetPage.dwSize = sizeof(PROPSHEETPAGE);    propSheetPage.dwFlags = PSP_USETITLE;    propSheetPage.pszTitle = PhApplicationName;    propSheetPage.pszTemplate = MAKEINTRESOURCE(IDD_DIALOG5);    propSheetPage.pfnDlgProc = PropSheetPage5_WndProc;    pages[propSheetHeader.nPages++] = CreatePropertySheetPage(&propSheetPage);    PhModalPropertySheet(&propSheetHeader);    return EXIT_SUCCESS;}
开发者ID:Azarien,项目名称:processhacker2,代码行数:77,


示例8: _tWinMain

int APIENTRY _tWinMain(HINSTANCE hInstance,                       HINSTANCE /*hPrevInstance*/,                       LPTSTR    lpCmdLine,                       int       /*nCmdShow*/){    SetDllDirectory(L"");    SetTaskIDPerUUID();    CRegStdDWORD loc = CRegStdDWORD(L"Software//TortoiseGit//LanguageID", 1033);    long langId = loc;    CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);    CLangDll langDLL;    hResource = langDLL.Init(L"TortoiseIDiff", langId);    if (!hResource)        hResource = hInstance;    git_libgit2_init();    CCmdLineParser parser(lpCmdLine);    if (parser.HasKey(L"?") || parser.HasKey(L"help"))    {        TCHAR buf[1024] = { 0 };        LoadString(hResource, IDS_COMMANDLINEHELP, buf, _countof(buf));        MessageBox(nullptr, buf, L"TortoiseIDiff", MB_ICONINFORMATION);        langDLL.Close();        return 0;    }    MSG msg;    hInst = hInstance;    INITCOMMONCONTROLSEX used = {        sizeof(INITCOMMONCONTROLSEX),        ICC_STANDARD_CLASSES | ICC_BAR_CLASSES | ICC_WIN95_CLASSES    };    InitCommonControlsEx(&used);    // load the cursors we need    curHand = static_cast<HCURSOR>(LoadImage(hInst, MAKEINTRESOURCE(IDC_PANCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE));    curHandDown = static_cast<HCURSOR>(LoadImage(hInst, MAKEINTRESOURCE(IDC_PANDOWNCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE));    auto mainWindow = std::make_unique<CMainWindow>(hResource);    mainWindow->SetRegistryPath(L"Software//TortoiseGit//TortoiseIDiffWindowPos");    std::wstring leftfile = parser.HasVal(L"left") ? parser.GetVal(L"left") : L"";    std::wstring rightfile = parser.HasVal(L"right") ? parser.GetVal(L"right") : L"";    if ((leftfile.empty()) && (lpCmdLine[0] != 0))    {        int nArgs;        LPWSTR * szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);        if (szArglist)        {            if (nArgs == 3)            {                // Four parameters:                // [0]: Program name                // [1]: left file                // [2]: right file                if (PathFileExists(szArglist[1]) && PathFileExists(szArglist[2]))                {                    leftfile = szArglist[1];                    rightfile = szArglist[2];                }            }        }        // Free memory allocated for CommandLineToArgvW arguments.        LocalFree(szArglist);    }    mainWindow->SetLeft(leftfile.c_str(), parser.HasVal(L"lefttitle") ? parser.GetVal(L"lefttitle") : L"");    mainWindow->SetRight(rightfile.c_str(), parser.HasVal(L"righttitle") ? parser.GetVal(L"righttitle") : L"");    if (parser.HasVal(L"base"))        mainWindow->SetSelectionImage(FileTypeBase, parser.GetVal(L"base"), parser.HasVal(L"basetitle") ? parser.GetVal(L"basetitle") : L"");    if (parser.HasVal(L"mine"))        mainWindow->SetSelectionImage(FileTypeMine, parser.GetVal(L"mine"), parser.HasVal(L"minetitle") ? parser.GetVal(L"minetitle") : L"");    if (parser.HasVal(L"theirs"))        mainWindow->SetSelectionImage(FileTypeTheirs, parser.GetVal(L"theirs"), parser.HasVal(L"theirstitle") ? parser.GetVal(L"theirstitle") : L"");    if (parser.HasVal(L"result"))        mainWindow->SetSelectionResult(parser.GetVal(L"result"));    mainWindow->resolveMsgWnd = parser.HasVal(L"resolvemsghwnd") ? reinterpret_cast<HWND>(parser.GetLongLongVal(L"resolvemsghwnd")) : 0;    mainWindow->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? static_cast<WPARAM>(parser.GetLongLongVal(L"resolvemsgwparam")) : 0;    mainWindow->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? static_cast<LPARAM>(parser.GetLongLongVal(L"resolvemsglparam")) : 0;    if (mainWindow->RegisterAndCreateWindow())    {        HACCEL hAccelTable = LoadAccelerators(hResource, MAKEINTRESOURCE(IDR_TORTOISEIDIFF));        if (!parser.HasVal(L"left") && parser.HasVal(L"base") && !parser.HasVal(L"mine") && !parser.HasVal(L"theirs"))        {            PostMessage(*mainWindow, WM_COMMAND, ID_FILE_OPEN, 0);        }        if (parser.HasKey(L"overlay"))        {            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_OVERLAPIMAGES, 0);        }        if (parser.HasKey(L"fit"))        {            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEHEIGHTS, 0);            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEWIDTHS, 0);        }        if (parser.HasKey(L"fitwidth"))//.........这里部分代码省略.........
开发者ID:TortoiseGit,项目名称:TortoiseGit,代码行数:101,


示例9: Msg

void ALDeviceList::Enumerate(){    char *devices;    int major, minor, index;    const char *actualDeviceName;    Msg("SOUND: OpenAL: enumerate devices...");    // have a set of vectors storing the device list, selection status, spec version #, and XRAM support status    // -- empty all the lists and reserve space for 10 devices    m_devices.clear				();    CoUninitialize();    // grab function pointers for 1.0-API functions, and if successful proceed to enumerate all devices    if (alcIsExtensionPresent(NULL, "ALC_ENUMERATION_EXT"))    {        Msg("SOUND: OpenAL: EnumerationExtension Present");        devices				= (char *)alcGetString(NULL, ALC_DEVICE_SPECIFIER);        Msg					("devices %s",devices);        m_defaultDeviceName	= (char *)alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);        Msg("SOUND: OpenAL: system  default SndDevice name is %s", m_defaultDeviceName.c_str());        // ManowaR        // "Generic Hardware" device on software AC'97 codecs introduce        // high CPU usage ( up to 30% ) as a consequence - freezes, FPS drop        // So if default device is "Generic Hardware" which maps to DirectSound3D interface        // We re-assign it to "Generic Software" to get use of old good DirectSound interface        // This makes 3D-sound processing unusable on cheap AC'97 codecs        // Also we assume that if "Generic Hardware" exists, than "Generic Software" is also exists        // Maybe wrong        if(0==stricmp(m_defaultDeviceName.c_str(),AL_GENERIC_HARDWARE))        {            m_defaultDeviceName			= AL_GENERIC_SOFTWARE;            Msg("SOUND: OpenAL: default SndDevice name set to %s", m_defaultDeviceName.c_str());        }        index				= 0;        // go through device list (each device terminated with a single NULL, list terminated with double NULL)        while (*devices != NULL)        {            ALCdevice *device		= alcOpenDevice(devices);            if (device)            {                ALCcontext *context = alcCreateContext(device, NULL);                if (context)                {                    alcMakeContextCurrent(context);                    // if new actual device name isn't already in the list, then add it...                    actualDeviceName = alcGetString(device, ALC_DEVICE_SPECIFIER);                    if ( (actualDeviceName != NULL) && xr_strlen(actualDeviceName)>0 )                    {                        alcGetIntegerv					(device, ALC_MAJOR_VERSION, sizeof(int), &major);                        alcGetIntegerv					(device, ALC_MINOR_VERSION, sizeof(int), &minor);                        m_devices.push_back				(ALDeviceDesc(actualDeviceName,minor,major));                        m_devices.back().xram			= (alIsExtensionPresent("EAX-RAM") == TRUE);                        m_devices.back().eax			= (alIsExtensionPresent("EAX2.0") == TRUE);                        // KD: disable unwanted eax flag to force eax on all devices                        m_devices.back().eax_unwanted	= 0;/*((0==xr_strcmp(actualDeviceName,AL_GENERIC_HARDWARE))||														   (0==xr_strcmp(actualDeviceName,AL_GENERIC_SOFTWARE)));*/                        ++index;                    }                    alcDestroyContext(context);                } else                    Msg("SOUND: OpenAL: cant create context for %s",device);                alcCloseDevice(device);            } else                Msg("SOUND: OpenAL: cant open device %s",devices);            devices		+= xr_strlen(devices) + 1;        }    } else        Msg("SOUND: OpenAL: EnumerationExtension NOT Present");    ResetFilters();    if(0!=GetNumDevices())        Msg("SOUND: OpenAL: All available devices:");    int majorVersion, minorVersion;    for (int i = 0; i < GetNumDevices(); i++)    {        GetDeviceVersion		(i, &majorVersion, &minorVersion);        Msg	("%d. %s, Spec Version %d.%d %s",             i+1,             GetDeviceName(i).c_str(),             majorVersion,             minorVersion,             (GetDeviceName(i)==m_defaultDeviceName)? "(default)":"" );    }    CoInitializeEx (NULL, COINIT_MULTITHREADED);}
开发者ID:Karlan88,项目名称:xray,代码行数:93,


示例10: CoInitializeEx

WMI::WMI(){    wbem = NULL;    result = S_OK;    CoInitializeEx(NULL, COINIT_MULTITHREADED);}
开发者ID:Krillsson,项目名称:sigar,代码行数:6,


示例11: main

int main() {	int argc;	wchar_t **_argv;	wchar_t **env;	int si = 0;	__wgetmainargs(&argc, &_argv, &env, _CRT_glob, &si);#elseint wmain(int argc, wchar_t *_argv[]) {#endif	char **argv = (char**)malloc(argc*sizeof(char*));	for (int i=0; i<argc; i++) {		int len = WideCharToMultiByte(CP_UTF8, 0, _argv[i], -1, NULL, 0, NULL, NULL);		if (!len) {			std::cout << "Failed to translate commandline to Unicode" << std::endl;			return 1;		}		char *temp = (char*)malloc(len*sizeof(char));		len = WideCharToMultiByte(CP_UTF8, 0, _argv[i], -1, temp, len, NULL, NULL);		if (!len) {			std::cout << "Failed to translate commandline to Unicode" << std::endl;			return 1;		}		argv[i] = temp;	}#else /* defined(_WIN32) && !defined(__MINGW32__) */int main(int argc, char *argv[]) {#endif /* defined(_WIN32) && !defined(__MINGW32__) */	try {		ParseCMDLine(argc, argv);	} catch (const char *Error) {		std::cout << std::endl << Error << std::endl;		return 1;	} catch (std::string Error) {		std::cout << std::endl << Error << std::endl;		return 1;	} catch (...) {		std::cout << std::endl << "Unknown error" << std::endl;		return 1;	}#ifdef _WIN32	if (FAILED(CoInitializeEx(NULL, COINIT_MULTITHREADED))) {		std::cout << "COM initialization failure" << std::endl;		return 1;	}#endif /* _WIN32 */	FFMS_Init(0, 1);	switch (Verbose) {		case 0: FFMS_SetLogLevel(AV_LOG_QUIET); break;		case 1: FFMS_SetLogLevel(AV_LOG_WARNING); break;		case 2: FFMS_SetLogLevel(AV_LOG_INFO); break;		case 3:	FFMS_SetLogLevel(AV_LOG_VERBOSE); break;		default: FFMS_SetLogLevel(AV_LOG_DEBUG); // if user used -v 4 or more times, he deserves the spam	}	try {		DoIndexing();	} catch (const char *Error) {		std::cout << Error << std::endl;		if (Index)			FFMS_DestroyIndex(Index);		return 1;	} catch (std::string Error) {		std::cout << std::endl << Error << std::endl;		if (Index)			FFMS_DestroyIndex(Index);		return 1;	} catch (...) {		std::cout << std::endl << "Unknown error" << std::endl;		if (Index)			FFMS_DestroyIndex(Index);		return 1;	}	if (Index)		FFMS_DestroyIndex(Index);#ifdef _WIN32	CoUninitialize();#endif	return 0;}
开发者ID:tgoyne,项目名称:ffms2,代码行数:83,


示例12: main

intmain (int argc, char *argv[]){	int i;	int ret;        // BEGIN NEW CODE        server *fake_serv;        GIOChannel *channel;        session *sess;        // END NEW CODE#ifdef WIN32	HRESULT coinit_result;#endif	srand ((unsigned int) time (NULL)); /* CL: do this only once! */	/* We must check for the config dir parameter, otherwise load_config() will behave incorrectly.	 * load_config() must come before fe_args() because fe_args() calls gtk_init() which needs to	 * know the language which is set in the config. The code below is copy-pasted from fe_args()	 * for the most part. */	if (argc >= 2)	{		for (i = 1; i < argc; i++)		{			if ((strcmp (argv[i], "-d") == 0 || strcmp (argv[i], "--cfgdir") == 0)				&& i + 1 < argc)			{				xdir = g_strdup (argv[i + 1]);			}			else if (strncmp (argv[i], "--cfgdir=", 9) == 0)			{				xdir = g_strdup (argv[i] + 9);			}			if (xdir != NULL)			{				if (xdir[strlen (xdir) - 1] == G_DIR_SEPARATOR)				{					xdir[strlen (xdir) - 1] = 0;				}				break;			}		}	}#if ! GLIB_CHECK_VERSION (2, 36, 0)        // RFM: Don't think we hit this	g_type_init ();#endif	if (check_config_dir () == 0)	{		if (load_config () != 0)			load_default_config ();	} else	{		/* this is probably the first run */		load_default_config ();		make_config_dirs ();		make_dcc_dirs ();	}	/* we MUST do this after load_config () AND before fe_init (thus gtk_init) otherwise it will fail */	// RFM: Does nothing on *NIX        set_locale ();        // RFM: Parses some command line crap. Not important	ret = fe_args (argc, argv);	if (ret != -1)		return ret;	#ifdef USE_DBUS	hexchat_remote ();#endif#ifdef USE_LIBPROXY        // RFM: Not using	libproxy_factory = px_proxy_factory_new();#endif#ifdef WIN32	coinit_result = CoInitializeEx (NULL, COINIT_APARTMENTTHREADED);	if (SUCCEEDED (coinit_result))	{		CoInitializeSecurity (NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_DEFAULT, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, NULL);	}#endif        // RFM: Inits some fe-text stuff	fe_init ();        // RFM: Pretty sure this just allows us to save chats...	/* This is done here because cfgfiles.c is too early in	* the startup process to use gtk functions. */	if (g_access (get_xdir (), W_OK) != 0)	{		char buf[2048];//.........这里部分代码省略.........
开发者ID:rfmcpherson,项目名称:hexchat,代码行数:101,


示例13: CoInitializeEx

CFilterPosition::CFilterPosition(void){    CoInitializeEx(NULL, NULL);    this->p_IsInitialized = FALSE;}
开发者ID:jokoho48,项目名称:acre2,代码行数:5,


示例14: wmain

int wmain(int argc, wchar_t* argv[]){    HRESULT hr = S_OK;    HANDLE completionEvent = NULL;    IXpsPrintJob* job = NULL;    IXpsPrintJobStream* jobStream = NULL;    IXpsOMObjectFactory* xpsFactory = NULL;    IOpcPartUri* partUri = NULL;    IXpsOMPackageWriter* packageWriter = NULL;    XPS_SIZE pageSize = {816, 1056};    IXpsOMPage* xpsPage = NULL;    IXpsOMFontResource* fontResource = NULL;    XPS_POINT origin = {50.0f, 200.0f};    XPS_JOB_STATUS jobStatus = {};    if (argc < 2 || argc > 3)    {        Usage(argv[0]);        return 1;    }    if (FAILED(hr = CoInitializeEx(0, COINIT_MULTITHREADED)))    {        fwprintf(stderr, L"ERROR: CoInitializeEx failed with HRESULT 0x%X/n", hr);        return 1;    }    if (SUCCEEDED(hr))    {        completionEvent = CreateEvent(NULL, TRUE, FALSE, NULL);        if (!completionEvent)        {            hr = HRESULT_FROM_WIN32(GetLastError());            fwprintf(stderr, L"ERROR: Could not create competion event: %08X/n", hr);        }    }    if (SUCCEEDED(hr))    {        if (FAILED(hr = StartXpsPrintJob(                    argv[1],                    NULL,                    argc == 3 ? argv[2] : NULL,                    NULL,                    completionEvent,                    NULL,                    0,                    &job,                    &jobStream,                    NULL                    )))        {            fwprintf(stderr, L"ERROR: Could not start XPS print job: %08X/n", hr);        }    }    if (SUCCEEDED(hr))    {        if (FAILED(hr = CoCreateInstance(                    __uuidof(XpsOMObjectFactory),                    NULL,                    CLSCTX_INPROC_SERVER,                    __uuidof(IXpsOMObjectFactory),                    reinterpret_cast<void**>(&xpsFactory)                    )                )            )        {            fwprintf(stderr, L"ERROR: Could not create XPS OM Object Factory: %08X/n", hr);        }    }    if (SUCCEEDED(hr))    {        if (FAILED(hr = xpsFactory->CreatePartUri(L"/FixedDocumentSequence.fdseq", &partUri)))        {            fwprintf(stderr, L"ERROR: Could not create part URI: %08X/n", hr);        }    }    if (SUCCEEDED(hr))    {        if (FAILED(hr = xpsFactory->CreatePackageWriterOnStream(                    jobStream,                    TRUE,                    XPS_INTERLEAVING_ON,                    partUri,                    NULL,                    NULL,                    NULL,                    NULL,                    &packageWriter                    )                )           )        {            fwprintf(stderr, L"ERROR: Could not create package writer: 0x%X/n", hr);        }    }//.........这里部分代码省略.........
开发者ID:Ippei-Murofushi,项目名称:WindowsSDK7-Samples,代码行数:101,


示例15: HrGetINetCfg

//+---------------------------------------------------------------------------//// Function:  HrGetINetCfg//// Purpose:   Initialize COM, create and initialize INetCfg.//            Obtain write lock if indicated.//// Arguments://    fGetWriteLock [in]  whether to get write lock//    ppnc          [in]  pointer to pointer to INetCfg object//// Returns:   S_OK on success, otherwise an error code//// Notes://HRESULT HrGetINetCfg(IN BOOL fGetWriteLock,                     INetCfg** ppnc){    HRESULT hr=S_OK;    // Initialize the output parameters.    *ppnc = NULL;    // initialize COM    hr = CoInitializeEx(NULL,                        COINIT_DISABLE_OLE1DDE | COINIT_APARTMENTTHREADED );    if (SUCCEEDED(hr))    {        // Create the object implementing INetCfg.        //        INetCfg* pnc;        hr = CoCreateInstance(CLSID_CNetCfg, NULL, CLSCTX_INPROC_SERVER,                              IID_INetCfg, (void**)&pnc);        if (SUCCEEDED(hr))        {            INetCfgLock * pncLock = NULL;            if (fGetWriteLock)            {                // Get the locking interface                hr = pnc->QueryInterface(IID_INetCfgLock,                                         (LPVOID *)&pncLock);                if (SUCCEEDED(hr))                {                    // Attempt to lock the INetCfg for read/write                    static const ULONG c_cmsTimeout = 15000;                    static const WCHAR c_szSampleNetcfgApp[] =                        L"Sample Netcfg Application (netcfg.exe)";                    PWSTR szLockedBy;                    hr = pncLock->AcquireWriteLock(c_cmsTimeout,                                                   c_szSampleNetcfgApp,                                                   &szLockedBy);                    if (S_FALSE == hr)                    {                        hr = NETCFG_E_NO_WRITE_LOCK;                    }                }            }            if (SUCCEEDED(hr))            {                // Initialize the INetCfg object.                //                hr = pnc->Initialize(NULL);                if (SUCCEEDED(hr))                {                    *ppnc = pnc;                    pnc->AddRef();                }                else                {                    // initialize failed, if obtained lock, release it                    if (pncLock)                    {                        pncLock->ReleaseWriteLock();                    }                }            }            ReleaseObj(pncLock);            ReleaseObj(pnc);        }        if (FAILED(hr))        {            CoUninitialize();        }    }    return hr;}
开发者ID:OPEXGroup,项目名称:winpcap,代码行数:91,


示例16: Shortcut_Init

void Shortcut_Init (void){   CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);}
开发者ID:snktagarwal,项目名称:openafs,代码行数:4,


示例17: wmi_initialize

int wmi_initialize() {	// Initialize default value	locator = NULL;	services = NULL;	//enumerator = NULL;	// Initialize COM	HRESULT result = CoInitializeEx(0, COINIT_MULTITHREADED);		if (FAILED(result)) {        log_err("Failed to initialize COM library. Error code = %x", result);        return -1;    }	// Set general COM security levels	result = CoInitializeSecurity(        NULL,         -1,                          // COM authentication        NULL,                        // Authentication services        NULL,                        // Reserved        RPC_C_AUTHN_LEVEL_DEFAULT,   // Default authentication         RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation          NULL,                        // Authentication info        EOAC_NONE,                   // Additional capabilities         NULL                         // Reserved    );	if (FAILED(result)) {       log_err("Failed to initialize security. Error code = %x", result);        CoUninitialize();        return -1;    }	// Obtain the initial locator to WMI	result = CoCreateInstance(        CLSID_WbemLocator,                     0,         CLSCTX_INPROC_SERVER,         IID_IWbemLocator, (LPVOID *) &locator);     if (FAILED(result)) {       log_err("Failed to create IWbemLocator object. Error code = %x", result);        CoUninitialize();        return -1;                 // Program has failed.    }	// Connect to WMI through the IWbemLocator::ConnectServer method	// Connect to the root/cimv2 namespace with    // the current user and obtain pointer 'services'    // to make IWbemServices calls.	result = locator->ConnectServer(         _bstr_t(L"ROOT//CIMV2"), // Object path of WMI namespace         NULL,                    // User name. NULL = current user         NULL,                    // User password. NULL = current         0,                       // Locale. NULL indicates current         NULL,                    // Security flags.         0,                       // Authority (for example, Kerberos)         0,                       // Context object          &services                // pointer to IWbemServices proxy    );	if (FAILED(result)) {        log_err("Could not connect. Error code = %x", result);        locator->Release();             CoUninitialize();        return -1;    }	//std::cout << "Connected to ROOT//CIMV2 WMI namespace" << std::endl;	// Set security levels on the proxy	result = CoSetProxyBlanket(       services,                        // Indicates the proxy to set       RPC_C_AUTHN_WINNT,           // RPC_C_AUTHN_xxx       RPC_C_AUTHZ_NONE,            // RPC_C_AUTHZ_xxx       NULL,                        // Server principal name        RPC_C_AUTHN_LEVEL_CALL,      // RPC_C_AUTHN_LEVEL_xxx        RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx       NULL,                        // client identity       EOAC_NONE                    // proxy capabilities     );	if (FAILED(result)) {        log_err("Could not set proxy blanket. Error code = %x", result);        services->Release();        locator->Release();             CoUninitialize();        return -1;    }	get_initial_values();	_initialized = 1;//.........这里部分代码省略.........
开发者ID:hanappe,项目名称:low-energy-boinc,代码行数:101,


示例18: RedirectInputThread

// Function name	: RedirectInputThread// Description	    : // Return type		: void // Argument         : RedirectInputThreadArg *argvoid RedirectInputThread(RedirectInputThreadArg *arg){	IRemoteShell *pLaunch=NULL;	HRESULT hr=S_OK;	HANDLE hObject[2];	long error=0;	BSTR berror_msg;	DWORD ret_val;	hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);	berror_msg = SysAllocString(L"");	CoGetInterfaceAndReleaseStream (*arg->ppStream, IID_IRemoteShell, (void**) &pLaunch);	delete arg->ppStream;	DWORD dwThreadID;	HANDLE hRSIThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ReadStdinThread, NULL, 0, &dwThreadID);	hObject[0] = arg->hEvent;	hObject[1] = g_hBufferEvent1;	berror_msg = SysAllocString(L"");	while (true)	{		ret_val = WaitForMultipleObjects(2, hObject, FALSE, INFINITE);		if (ret_val == WAIT_OBJECT_0+1)		{			if (g_num_read > 0)			{				SAFEARRAYBOUND bound;				VARIANT vInput;				void *pBuf;				VariantInit(&vInput);				bound.lLbound = 0;				bound.cElements = g_num_read;				vInput.vt = VT_UI1 | VT_ARRAY;				vInput.parray = SafeArrayCreate(VT_UI1, 1, &bound);				SafeArrayAccessData(vInput.parray, &pBuf);				memcpy(pBuf, g_pBuffer, g_num_read);				SafeArrayUnaccessData(vInput.parray);				error = 0;				hr = pLaunch->PutProcessInput(vInput, &error, &berror_msg);				if (FAILED(hr))				{					VariantClear(&vInput);					printf("PutInteractiveInput failed: %d/n", hr);					PrintError(hr);					break;				}				if (error)				{					VariantClear(&vInput);					if (wcslen(berror_msg) < 1)						wprintf(L"PutInteractiveInput failed: %d %s/n", error, berror_msg);					else						wprintf(L"PutInteractiveInput failed: %s/n", berror_msg);					break;				}				VariantClear(&vInput);			}			ResetEvent(g_hBufferEvent1);			SetEvent(g_hBufferEvent2);		}		else		{			//printf("g_hFinishedEvent signalled/n");		    TerminateThread(hRSIThread, 0);			break;		}	}	pLaunch->Release();	CoUninitialize();}
开发者ID:hpc,项目名称:mvapich-cce,代码行数:81,


示例19: EnterMTA

static void EnterMTA(void){    HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);    if (unlikely(FAILED(hr)))        abort();}
开发者ID:motiz88,项目名称:vlc-plugin-sapispeechsynthesizer,代码行数:6,


示例20: CoInitializeEx

JNIEXPORT void JNICALL Java_com_jacob2_com_ComThread_doCoInitialize  (JNIEnv *env, jclass cls, jint mode){  int threadModel = mode;  CoInitializeEx(NULL, threadModel);}
开发者ID:wangkm,项目名称:zeroDoc,代码行数:6,


示例21: SetCommandBatching

// Initialisation of the CXAudio2 enginevoid CXAudio2::Init(const CXAudio2SetupParameters& params){	// Copy parameters	numChannels = params.numChannels;	maxFrequencyRatio = params.maxFrequencyRatio;	SetCommandBatching(params.commandBatching);	SetCacheMode(params.cacheMode);	SetCacheLimit(params.cacheLimit);	// Initialize COM	CoInitializeEx(NULL, COINIT_MULTITHREADED);#ifdef _DEBUG	// Request debug XAudio2 engine	hr = XAudio2Create(&pXAudio2, XAUDIO2_DEBUG_ENGINE,	XAUDIO2_DEFAULT_PROCESSOR);#else	// Request standard XAudio2 engine	hr = XAudio2Create(&pXAudio2, 0,					XAUDIO2_DEFAULT_PROCESSOR);#endif	// XAudio2Create failed	if (FAILED(hr))		throw CXAudio2Error(hr, "Failed to create XAudio2");	// Mastering limiter & volume meter effect chain for mastering voice	XAUDIO2_EFFECT_DESCRIPTOR descriptor[2];	int count = 0;	// Create the mastering limiter if enabled	if (params.limiter_enable) {		IUnknown* pLimiter;		hr = CreateFX(__uuidof(FXMasteringLimiter), &pLimiter);		if (FAILED(hr))			throw CXAudio2Error(hr, "Failed to create mastering limiter");		descriptor[0].InitialState = true;		descriptor[0].OutputChannels = 2;		descriptor[0].pEffect = pLimiter;		// Write volume meter to next descriptor		count++;	}	// Create the volume meter for the mastering voice#ifdef _DEBUG	hr = XAudio2CreateVolumeMeter(&(master.pVolumeMeter), XAUDIO2FX_DEBUG);#else	hr = XAudio2CreateVolumeMeter(&(master.pVolumeMeter), 0);#endif	if (FAILED(hr))		throw CXAudio2Error(hr, "Failed to create XAudio2 volume meter");	// Set up the effect chain to apply the volume metering to the mastering voice	descriptor[count].InitialState = true;	descriptor[count].OutputChannels = 2;	descriptor[count].pEffect = master.pVolumeMeter;	master.volumeMeterEffectIndex = count;	count++;	XAUDIO2_EFFECT_CHAIN chain;	chain.EffectCount = count;	chain.pEffectDescriptors = descriptor;	// Create stereo mastering voice	hr = pXAudio2->CreateMasteringVoice(&(master.pMaster), 2, XAUDIO2_DEFAULT_SAMPLERATE, 										0, 0, &chain);	if (FAILED(hr))		throw CXAudio2Error(hr, "Failed to create XAudio2 mastering voice");	// Get the device details	pXAudio2->GetDeviceDetails(0, &deviceDetails);	// Set up the channel strip	channels.reserve(numChannels);	for (int i = 0; i < numChannels; i++)		channels.push_back(Channel(this, i));	// Set the master volume as per parameters; -3.0dB by default to help prevent clipping	master.SetVolume(params.masterGain);}
开发者ID:segafan,项目名称:Construct-classic,代码行数:85,


示例22: _tWinMain

extern "C" int WINAPI _tWinMain(HINSTANCE hInstance,     HINSTANCE /*hPrevInstance*/, LPTSTR lpCmdLine, int /*nShowCmd*/){    lpCmdLine = GetCommandLine(); //this line necessary for _ATL_MIN_CRT#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)    HRESULT hRes = CoInitializeEx(NULL, COINIT_MULTITHREADED);#else    HRESULT hRes = CoInitialize(NULL);#endif    _ASSERTE(SUCCEEDED(hRes));    _Module.Init(ObjectMap, hInstance, &LIBID_ETSMANAGERLib);    _Module.dwThreadID = GetCurrentThreadId();    TCHAR szTokens[] = _T("-/");    int nRet = 0;    BOOL bRun = TRUE;    LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);    while (lpszToken != NULL)    {        if (lstrcmpi(lpszToken, _T("UnregServer"))==0)        {            _Module.UpdateRegistryFromResource(IDR_ETSManager, FALSE);            nRet = _Module.UnregisterServer(TRUE);            bRun = FALSE;            break;        }        if (lstrcmpi(lpszToken, _T("RegServer"))==0)        {            _Module.UpdateRegistryFromResource(IDR_ETSManager, TRUE);            nRet = _Module.RegisterServer(TRUE);            bRun = FALSE;            break;        }        lpszToken = FindOneOf(lpszToken, szTokens);    }    if (bRun)    {        _Module.StartMonitor();#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER,             REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);        _ASSERTE(SUCCEEDED(hRes));        hRes = CoResumeClassObjects();#else        hRes = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER,             REGCLS_MULTIPLEUSE);#endif        _ASSERTE(SUCCEEDED(hRes));        MSG msg;        while (GetMessage(&msg, 0, 0, 0))            DispatchMessage(&msg);        _Module.RevokeClassObjects();        Sleep(dwPause); //wait for any threads to finish    }    _Module.Term();    CoUninitialize();    return nRet;}
开发者ID:AlexS2172,项目名称:IVRM,代码行数:63,


示例23: InitMFStreamer

HRESULT InitMFStreamer(){	printf("InitMFStreamer./n");	CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);	CHECK_HR(InitVPXEncoder(&_vpxConfig, &_vpxCodec, WIDTH, HEIGHT), L"Failed to intialise the VPX encoder./n");	// Create an attribute store to hold the search criteria.	CHECK_HR(MFCreateAttributes(&videoConfig, 1), L"Error creating video configuation.");	//CHECK_HR(MFCreateAttributes(&audioConfig, 1), L"Error creating audio configuation.");;	// Request video capture devices.	CHECK_HR(videoConfig->SetGUID(		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,		MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_GUID), L"Error initialising video configuration object.");	// Request audio capture devices.	/*CHECK_HR(audioConfig->SetGUID(	MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE,	MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_AUDCAP_GUID), L"Error initialising audio configuration object.");*/	// Enumerate the devices,	CHECK_HR(MFEnumDeviceSources(videoConfig, &videoDevices, &videoDeviceCount), L"Error enumerating video devices.");	//CHECK_HR(MFEnumDeviceSources(audioConfig, &audioDevices, &audioDeviceCount), L"Error enumerating audio devices.");	//printf("Video device Count: %i, Audio device count: %i./n", videoDeviceCount, audioDeviceCount);	printf("Video device Count: %i./n", videoDeviceCount);	CHECK_HR(videoDevices[0]->ActivateObject(IID_PPV_ARGS(&videoSource)), L"Error activating video device.");	//CHECK_HR(audioDevices[0]->ActivateObject(IID_PPV_ARGS(&audioSource)), L"Error activating audio device.");	// Initialize the Media Foundation platform.	CHECK_HR(MFStartup(MF_VERSION), L"Error on Media Foundation startup.");	/*WCHAR *pwszFileName = L"sample.mp4";	IMFSinkWriter *pWriter;*/	/*CHECK_HR(MFCreateSinkWriterFromURL(	pwszFileName,	NULL,	NULL,	&pWriter), L"Error creating mp4 sink writer.");*/	// Create the source readers.	CHECK_HR(MFCreateSourceReaderFromMediaSource(		videoSource,		videoConfig,		&videoReader), L"Error creating video source reader.");	//ListModes(videoReader);	/*CHECK_HR(MFCreateSourceReaderFromMediaSource(	audioSource,	audioConfig,	&audioReader), L"Error creating audio source reader.");*/	FindVideoMode(videoReader, MF_INPUT_FORMAT, WIDTH, HEIGHT, desiredInputVideoType);	if (desiredInputVideoType == NULL) {		printf("The specified media type could not be found for the MF video reader./n");	}	else {		CHECK_HR(videoReader->SetCurrentMediaType((DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM, NULL, desiredInputVideoType),			L"Error setting video reader media type./n");		CHECK_HR(videoReader->GetCurrentMediaType(			(DWORD)MF_SOURCE_READER_FIRST_VIDEO_STREAM,			&videoType), L"Error retrieving current media type from first video stream.");		CMediaTypeTrace *videoTypeMediaTrace = new CMediaTypeTrace(videoType);		printf("Video input media type: %s./n", videoTypeMediaTrace->GetString());		LONG pStride = 0;		GetDefaultStride(videoType, &pStride);		printf("Stride %i./n", pStride);					/*printf("Press any key to continue...");		getchar();*/		/*audioReader->GetCurrentMediaType(		(DWORD)MF_SOURCE_READER_FIRST_AUDIO_STREAM,		&audioType);*/		//CMediaTypeTrace *audioTypeMediaTrace = new CMediaTypeTrace(audioType);		//printf("Audio input media type: %s./n", audioTypeMediaTrace->GetString());		//printf("Configuring H.264 sink./n");		// Set up the H.264 sink.		/*CHECK_HR(ConfigureEncoder(videoType, &videoStreamIndex, &audioStreamIndex, pWriter), L"Error configuring encoder.");		printf("Video stream index %i, audio stream index %i./n", videoStreamIndex, audioStreamIndex);*/		// Register the color converter DSP for this process, in the video 		// processor category. This will enable the sink writer to enumerate		// the color converter when the sink writer attempts to match the		// media types.		CHECK_HR(MFTRegisterLocalByCLSID(			__uuidof(CColorConvertDMO),			MFT_CATEGORY_VIDEO_PROCESSOR,			L"",//.........这里部分代码省略.........
开发者ID:3wcorner,项目名称:sipsorcery,代码行数:101,


示例24: wasapi_init

int wasapi_init(cubeb ** context, char const * context_name){  HRESULT hr;  IMMDeviceEnumerator * enumerator = NULL;  hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);  if (FAILED(hr)) {    LOG("Could not init COM.");    return CUBEB_ERROR;  }  cubeb * ctx = (cubeb *)calloc(1, sizeof(cubeb));  ctx->ops = &wasapi_ops;  hr = CoCreateInstance(__uuidof(MMDeviceEnumerator),                        NULL, CLSCTX_INPROC_SERVER,                        IID_PPV_ARGS(&enumerator));  if (FAILED(hr)) {    LOG("Could not get device enumerator.");    wasapi_destroy(ctx);    return CUBEB_ERROR;  }  /* eMultimedia is okay for now ("Music, movies, narration, [...]").   * We will need to change this when we distinguish streams by use-case, other   * possible values being eConsole ("Games, system notification sounds [...]")   * and eCommunication ("Voice communication"). */  hr = enumerator->GetDefaultAudioEndpoint(eRender,                                           eMultimedia,                                           &ctx->device);  if (FAILED(hr)) {    LOG("Could not get default audio endpoint.");    SafeRelease(enumerator);    wasapi_destroy(ctx);    return CUBEB_ERROR;  }  ctx->mmcss_module = LoadLibraryA("Avrt.dll");  if (ctx->mmcss_module) {    ctx->set_mm_thread_characteristics =      (set_mm_thread_characteristics_function) GetProcAddress(          ctx->mmcss_module, "AvSetMmThreadCharacteristicsA");    ctx->revert_mm_thread_characteristics =      (revert_mm_thread_characteristics_function) GetProcAddress(          ctx->mmcss_module, "AvRevertMmThreadCharacteristics");    if (!(ctx->set_mm_thread_characteristics && ctx->revert_mm_thread_characteristics)) {      LOG("Could not load AvSetMmThreadCharacteristics or AvRevertMmThreadCharacteristics: %d", GetLastError());      FreeLibrary(ctx->mmcss_module);    }  } else {    // This is not a fatal error, but we might end up glitching when    // the system is under high load.    LOG("Could not load Avrt.dll");    ctx->set_mm_thread_characteristics = &set_mm_thread_characteristics_noop;    ctx->revert_mm_thread_characteristics = &revert_mm_thread_characteristics_noop;  }    SafeRelease(enumerator);  *context = ctx;  return CUBEB_OK;}
开发者ID:birtles,项目名称:mozilla-central,代码行数:65,


示例25: InitWMI

PWMIUT InitWMI(PGLOBAL g, char *nsp, char *classname){  IWbemLocator *loc;  char         *p;  HRESULT       res;  PWMIUT        wp = (PWMIUT)PlugSubAlloc(g, NULL, sizeof(WMIUTIL));  if (trace)    htrc("WMIColumns class %s space %s/n", SVP(classname), SVP(nsp));  /*********************************************************************/  /*  Set default values for the namespace and class name.             */  /*********************************************************************/  if (!nsp)    nsp = "root//cimv2";  if (!classname) {    if (!stricmp(nsp, "root//cimv2"))      classname = "ComputerSystemProduct";    else if (!stricmp(nsp, "root//cli"))      classname = "Msft_CliAlias";    else {      strcpy(g->Message, "Missing class name");      return NULL;      } // endif classname    } // endif classname  /*********************************************************************/  /*  Initialize WMI.                                                  */  /*********************************************************************///res = CoInitializeEx(NULL, COINIT_MULTITHREADED);  res = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);  if (FAILED(res)) {    sprintf(g->Message, "Failed to initialize COM library. "             "Error code = %p", res);    return NULL;    } // endif res#if 0 // irrelevant for a DLL  res = CoInitializeSecurity(NULL, -1, NULL, NULL,                       RPC_C_AUTHN_LEVEL_CONNECT,                       RPC_C_IMP_LEVEL_IMPERSONATE,                       NULL, EOAC_NONE, NULL);    if (res != RPC_E_TOO_LATE && FAILED(res)) {    sprintf(g->Message, "Failed to initialize security. "             "Error code = %p", res);    CoUninitialize();    return NULL;    }  // endif Res#endif // 0  res = CoCreateInstance(CLSID_WbemLocator, NULL,                          CLSCTX_INPROC_SERVER, IID_IWbemLocator,                          (void**) &loc);  if (FAILED(res)) {    sprintf(g->Message, "Failed to create Locator. "             "Error code = %p", res);    CoUninitialize();    return NULL;    }  // endif res      res = loc->ConnectServer(_bstr_t(nsp),                     NULL, NULL, NULL, 0, NULL, NULL, &wp->Svc);  if (FAILED(res)) {    sprintf(g->Message, "Could not connect. Error code = %p", res);     loc->Release();         CoUninitialize();    return NULL;    }  // endif res  loc->Release();  if (trace)    htrc("Successfully connected to namespace./n");  /*********************************************************************/  /*  Perform a full class object retrieval.                           */  /*********************************************************************/  p = (char*)PlugSubAlloc(g, NULL, strlen(classname) + 7);  if (strchr(classname, '_'))    strcpy(p, classname);  else    strcat(strcpy(p, "Win32_"), classname);  res = wp->Svc->GetObject(bstr_t(p), 0, 0, &wp->Cobj, 0);  if (FAILED(res)) {    sprintf(g->Message, "failed GetObject %s in %s/n", classname, nsp);    wp->Svc->Release();    wp->Svc = NULL;    // MUST be set to NULL  (why?)    return NULL;    }  // endif res  return wp;} // end of InitWMI
开发者ID:asmlib,项目名称:mariadb-server,代码行数:100,


示例26: WinMain

int PASCAL WinMain(HINSTANCE hInstance, HINSTANCE hInstP, LPSTR lpCmdLine, int nCmdShow){    MSG msg={0};    WNDCLASS wc;    // Initialize COM    if(FAILED(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED)))    {        Msg(TEXT("CoInitialize Failed!/r/n"));           exit(1);    }     // Register the window class    ZeroMemory(&wc, sizeof wc);    wc.lpfnWndProc   = WndMainProc;    wc.hInstance     = hInstance;    wc.lpszClassName = CLASSNAME;    wc.lpszMenuName  = NULL;    wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);    wc.hIcon         = NULL;    if(!RegisterClass(&wc))    {        Msg(TEXT("RegisterClass Failed! Error=0x%x/r/n"), GetLastError());        CoUninitialize();        exit(1);    }    // Create the main window.  The WS_CLIPCHILDREN style is required.    ghApp = CreateWindow(CLASSNAME, APPLICATIONNAME,                         WS_OVERLAPPEDWINDOW | WS_CAPTION | WS_CLIPCHILDREN,                         CW_USEDEFAULT, CW_USEDEFAULT,                         DEFAULT_VIDEO_WIDTH, DEFAULT_VIDEO_HEIGHT,                         0, 0, hInstance, 0);    if(ghApp)    {        HRESULT hr;        // Create DirectShow graph and start capturing video        hr = CaptureVideo();        if (FAILED (hr))        {            CloseInterfaces();            DestroyWindow(ghApp);        }        else        {            // Don't display the main window until the DirectShow            // preview graph has been created.  Once video data is            // being received and processed, the window will appear            // and immediately have useful video data to display.            // Otherwise, it will be black until video data arrives.            ShowWindow(ghApp, nCmdShow);        }               // Main message loop        while(GetMessage(&msg,NULL,0,0))        {            TranslateMessage(&msg);            DispatchMessage(&msg);        }    }    // Release COM    CoUninitialize();    return (int) msg.wParam;}
开发者ID:Essjay1,项目名称:Windows-classic-samples,代码行数:69,


示例27: SetupForIsXInputDevice

HRESULT SetupForIsXInputDevice(){	IWbemLocator *pIWbemLocator = NULL;	IEnumWbemClassObject *pEnumDevices = NULL;	IWbemClassObject *pDevices[20] = {0};	IWbemServices *pIWbemServices = NULL;	BSTR bstrNamespace = NULL;	BSTR bstrDeviceID = NULL;	BSTR bstrClassName = NULL;	DWORD uReturned = 0;	BOOL bIsXinputDevice = FALSE;	UINT iDevice = 0;	VARIANT var;	HRESULT hr;	hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);	bCleanupCOM = SUCCEEDED(hr);		// Create WMI	hr = CoCreateInstance( &CLSID_WbemContext,		NULL,		CLSCTX_INPROC_SERVER,		&IID_IWbemContext,		(LPVOID*) &pIWbemLocator);	if( FAILED(hr) || pIWbemLocator == NULL )		goto bail;	bstrNamespace = SysAllocString( L"////.//root//cimv2" );if( bstrNamespace == NULL ) goto bail;	bstrClassName = SysAllocString( L"Win32_PNPEntity" );   if( bstrClassName == NULL ) goto bail;	bstrDeviceID  = SysAllocString( L"DeviceID" );          if( bstrDeviceID == NULL )  goto bail;	// Connect to WMI 		hr = IWbemLocator_ConnectServer(pIWbemLocator, bstrNamespace, NULL, NULL, NULL, 		0L, NULL, NULL, &pIWbemServices );	if( FAILED(hr) || pIWbemServices == NULL )		goto bail;	// Switch security level to IMPERSONATE	CoSetProxyBlanket( (IUnknown *)pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, 		RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE );                    	hr = IWbemServices_CreateInstanceEnum( pIWbemServices, bstrClassName, 0, NULL, &pEnumDevices ); 	if( FAILED(hr) || pEnumDevices == NULL )		goto bail;	// Loop over all devices	for(;;)	{		// Get 20 at a time				hr = IEnumWbemClassObject_Next( pEnumDevices, 10000, 20, pDevices, &uReturned );		if( FAILED(hr) || 			uReturned == 0 )			break;		for( iDevice=0; iDevice<uReturned; iDevice++ )		{			// For each device, get its device ID			hr = IWbemClassObject_Get( pDevices[iDevice], bstrDeviceID, 0L, &var, NULL, NULL );			if( SUCCEEDED( hr ) && var.vt == VT_BSTR && var.bstrVal != NULL )			{				// Check if the device ID contains "IG_".  If it does, then it's an XInput device				// This information can not be found from DirectInput 				if( wcsstr( var.bstrVal, L"IG_" ) )				{					// If it does, then get the VID/PID from var.bstrVal					DWORD dwPid = 0, dwVid = 0;					WCHAR* strVid;					WCHAR* strPid;					DWORD dwVidPid;					XINPUT_DEVICE_NODE* pNewNode;					strVid = wcsstr( var.bstrVal, L"VID_" );					if( strVid && swscanf( strVid, L"VID_%4X", &dwVid ) != 1 )						dwVid = 0;					strPid = wcsstr( var.bstrVal, L"PID_" );					if( strPid && swscanf( strPid, L"PID_%4X", &dwPid ) != 1 )						dwPid = 0;					dwVidPid = MAKELONG( dwVid, dwPid );					// Add the VID/PID to a linked list					pNewNode = malloc(sizeof(XINPUT_DEVICE_NODE));					if( pNewNode )					{						pNewNode->dwVidPid = dwVidPid;						pNewNode->pNext = (struct XINPUT_DEVICE_NODE *)g_pXInputDeviceList;						g_pXInputDeviceList = pNewNode;					}				}			}			SAFE_RELEASE( pDevices[iDevice] );		}	}bail:	if(bstrNamespace)		SysFreeString(bstrNamespace);	if(bstrDeviceID)		SysFreeString(bstrDeviceID);//.........这里部分代码省略.........
开发者ID:EdCornejo,项目名称:emu-ex-plus-alpha,代码行数:101,


示例28: wmain

//// Main entry point of the sample//int wmain(){    wprintf(L"Copyright (c) Microsoft Corporation.  All rights reserved./n");    wprintf(L"CreateBundle sample/n/n");    HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);    if (SUCCEEDED(hr))    {        // Create a bundle writer object        IAppxBundleWriter* bundleWriter = NULL;        wprintf(L"/nCreating bundle writer/n/n");        hr = GetBundleWriter(OutputBundlePath, &bundleWriter);        // Add all payload packages to the package writer        for (int i = 0; SUCCEEDED(hr) && (i < PayloadPackagesCount); i++)        {            IStream* payloadPackageStream = NULL;            wprintf(L"Adding payload package: %s/n", PayloadPackagesName[i]);            hr = GetFileStream(DataPath, PayloadPackagesName[i], &payloadPackageStream);            if (SUCCEEDED(hr))            {                bundleWriter->AddPayloadPackage(                    PayloadPackagesName[i],                    payloadPackageStream);            }            if (payloadPackageStream != NULL)            {                payloadPackageStream->Release();                payloadPackageStream = NULL;            }        }        // Close the bundle writer to flush the output stream        if (SUCCEEDED(hr))        {            hr = bundleWriter->Close();        }        // Clean up allocated resources        if (bundleWriter != NULL)        {            bundleWriter->Release();            bundleWriter = NULL;        }        CoUninitialize();    }    if (SUCCEEDED(hr))    {        wprintf(L"/nBundle successfully saved to %s./n", OutputBundlePath);    }    else    {        wprintf(L"/nBundle creation failed with HRESULT 0x%08X./n", hr);    }    return SUCCEEDED(hr) ? 0 : 1;}
开发者ID:9578577,项目名称:Windows-classic-samples,代码行数:67,



注:本文中的CoInitializeEx函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


C++ CoTaskMemFree函数代码示例
C++ CoCreateInstance函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。