Ejemplo n.º 1
0
//
// Purpose: 
//   Entry point for the process
//
// Parameters:
//   None
// 
// Return value:
//   None
//
void __cdecl main() 
{ 
    DWORD result = NO_ERROR;
	HRESULT hr = S_OK;
    INetFwProduct* product = NULL;
    INetFwProducts* products = NULL;
    IUnknown* registration = NULL;
    long *categories = NULL;
    BSTR displayName = NULL;
    VARIANT varCategories = { VT_EMPTY };
    int numberOfCategories = 1;
    long count=0;
    BOOL comInit =  FALSE;

    //Allocate Memory
    categories = (long *)calloc (numberOfCategories , sizeof(long));
    BAIL_ON_ALLOC_FAILURE(categories, calloc);

    //Take Firewall Category Ownership
    categories[0] = NET_FW_RULE_CATEGORY_FIREWALL;
    result = ArrayOfLongsToVariant(numberOfCategories, categories, &varCategories);
    
	displayName = SysAllocString(L"@RegisterFirewallSample.exe,-127");
    BAIL_ON_ALLOC_FAILURE(displayName, SysAllocString);

    hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    if (FAILED(hr))
    {
        //COM initialize failed
        wprintf(L"CoInitialize failed: 0x%08lx\n", result);
        goto CLEANUP;
    }
    comInit = TRUE;


    hr = CoCreateInstance(__uuidof(NetFwProduct),NULL,CLSCTX_INPROC_SERVER,__uuidof(INetFwProduct),(void**)&product );

    if (FAILED(hr))
    {
        //CoCreateInstance Failed
        wprintf(L"CoCreateInstance for INetFwProduct failed: 0x%08lx\n", hr);
        goto CLEANUP;
    }

    hr = product->put_DisplayName(displayName);

    if (FAILED(hr))
    {
        //Put_displayName failed
        wprintf(L"put_DisplayName for INetFwProduct failed Error: 0x%08lx\n", hr);
        goto CLEANUP;
    }
    hr = product->put_RuleCategories(varCategories);

    if (FAILED(hr))
    {
        //Put_rulecategories failed
        wprintf(L"put_RuleCategories failed for INetFwProduct Error: 0x%08lx\n", hr);
        goto CLEANUP;
    }


    hr = CoCreateInstance(__uuidof(NetFwProducts),NULL,CLSCTX_INPROC_SERVER,__uuidof(INetFwProducts),(void**)&products );

    if (FAILED(hr))
    {
        //CoCreateInstance Failed
        wprintf(L"CoCreateInstance for INetFwProducts failed: 0x%08lx\n", hr);
        goto CLEANUP;
    }

    hr = products->Register(product, &registration);
    if (FAILED(hr))
    {
        //Failed to Register Products
        wprintf(L"Register failed: 0x%08lx\n", hr);
        goto CLEANUP;
    }			

    hr = products->get_Count( &count);
    if (FAILED(hr))
    {
        //Failed to get Count of Products
        wprintf(L"Get count failed: 0x%08lx\n", hr);
        goto CLEANUP;
    }		
    wprintf(L"INetFwProducts_Count returned %ld.\n", count);

    wprintf(L"Hit any key to unregister.\n");
    _getch();

CLEANUP:
	if (registration != NULL)
   {
      registration->Release();
   }
   if (products != NULL)
   {
      products->Release();
   }
   if (product != NULL)
   {
      product->Release();
   }
   if (comInit)
   {
      CoUninitialize();
   }
   free(categories);
   SysFreeString(displayName);
   VariantClear(&varCategories);
   return;
} 
Ejemplo n.º 2
0
void
WMFDecoderModule::OnDecodeThreadFinish()
{
  MOZ_ASSERT(!NS_IsMainThread(), "Must be on main thread.");
  CoUninitialize();
}
Ejemplo n.º 3
0
/***************************************************************************
 *                              MCIQTZ_mciOpen                  [internal]
 */
static DWORD MCIQTZ_mciOpen(UINT wDevID, DWORD dwFlags,
                            LPMCI_DGV_OPEN_PARMSW lpOpenParms)
{
    WINE_MCIQTZ* wma;
    HRESULT hr;
    DWORD style = 0;
    RECT rc = { 0, 0, 0, 0 };

    TRACE("(%04x, %08X, %p)\n", wDevID, dwFlags, lpOpenParms);

    wma = MCIQTZ_mciGetOpenDev(wDevID);
    if (!wma)
        return MCIERR_INVALID_DEVICE_ID;

    MCIQTZ_mciStop(wDevID, MCI_WAIT, NULL);

    hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
    wma->uninit = SUCCEEDED(hr);

    hr = CoCreateInstance(&CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER, &IID_IGraphBuilder, (LPVOID*)&wma->pgraph);
    if (FAILED(hr)) {
        TRACE("Cannot create filtergraph (hr = %x)\n", hr);
        goto err;
    }

    hr = IGraphBuilder_QueryInterface(wma->pgraph, &IID_IMediaControl, (LPVOID*)&wma->pmctrl);
    if (FAILED(hr)) {
        TRACE("Cannot get IMediaControl interface (hr = %x)\n", hr);
        goto err;
    }

    hr = IGraphBuilder_QueryInterface(wma->pgraph, &IID_IMediaSeeking, (void**)&wma->seek);
    if (FAILED(hr)) {
        TRACE("Cannot get IMediaSeeking interface (hr = %x)\n", hr);
        goto err;
    }

    hr = IGraphBuilder_QueryInterface(wma->pgraph, &IID_IMediaEvent, (void**)&wma->mevent);
    if (FAILED(hr)) {
        TRACE("Cannot get IMediaEvent interface (hr = %x)\n", hr);
        goto err;
    }

    hr = IGraphBuilder_QueryInterface(wma->pgraph, &IID_IVideoWindow, (void**)&wma->vidwin);
    if (FAILED(hr)) {
        TRACE("Cannot get IVideoWindow interface (hr = %x)\n", hr);
        goto err;
    }

    hr = IGraphBuilder_QueryInterface(wma->pgraph, &IID_IBasicVideo, (void**)&wma->vidbasic);
    if (FAILED(hr)) {
        TRACE("Cannot get IBasicVideo interface (hr = %x)\n", hr);
        goto err;
    }

    hr = IGraphBuilder_QueryInterface(wma->pgraph, &IID_IBasicAudio, (void**)&wma->audio);
    if (FAILED(hr)) {
        TRACE("Cannot get IBasicAudio interface (hr = %x)\n", hr);
        goto err;
    }

    if (!(dwFlags & MCI_OPEN_ELEMENT) || (dwFlags & MCI_OPEN_ELEMENT_ID)) {
        TRACE("Wrong dwFlags %x\n", dwFlags);
        goto err;
    }

    if (!lpOpenParms->lpstrElementName || !lpOpenParms->lpstrElementName[0]) {
        TRACE("Invalid filename specified\n");
        goto err;
    }

    TRACE("Open file %s\n", debugstr_w(lpOpenParms->lpstrElementName));

    hr = IGraphBuilder_RenderFile(wma->pgraph, lpOpenParms->lpstrElementName, NULL);
    if (FAILED(hr)) {
        TRACE("Cannot render file (hr = %x)\n", hr);
        goto err;
    }

    IVideoWindow_put_AutoShow(wma->vidwin, OAFALSE);
    IVideoWindow_put_Visible(wma->vidwin, OAFALSE);
    if (dwFlags & MCI_DGV_OPEN_WS)
        style = lpOpenParms->dwStyle;
    if (dwFlags & MCI_DGV_OPEN_PARENT) {
        IVideoWindow_put_MessageDrain(wma->vidwin, (OAHWND)lpOpenParms->hWndParent);
        IVideoWindow_put_WindowState(wma->vidwin, SW_HIDE);
        IVideoWindow_put_WindowStyle(wma->vidwin, style|WS_CHILD);
        IVideoWindow_put_Owner(wma->vidwin, (OAHWND)lpOpenParms->hWndParent);
        GetClientRect(lpOpenParms->hWndParent, &rc);
        IVideoWindow_SetWindowPosition(wma->vidwin, rc.left, rc.top, rc.right - rc.top, rc.bottom - rc.top);
        wma->parent = (HWND)lpOpenParms->hWndParent;
    }
    else if (style)
        IVideoWindow_put_WindowStyle(wma->vidwin, style);
    IBasicVideo_GetVideoSize(wma->vidbasic, &rc.right, &rc.bottom);
    wma->opened = TRUE;

    if (dwFlags & MCI_NOTIFY)
        mciDriverNotify(HWND_32(LOWORD(lpOpenParms->dwCallback)), wDevID, MCI_NOTIFY_SUCCESSFUL);

    return 0;

err:
    if (wma->audio)
        IBasicAudio_Release(wma->audio);
    wma->audio = NULL;
    if (wma->vidbasic)
        IBasicVideo_Release(wma->vidbasic);
    wma->vidbasic = NULL;
    if (wma->seek)
        IMediaSeeking_Release(wma->seek);
    wma->seek = NULL;
    if (wma->vidwin)
        IVideoWindow_Release(wma->vidwin);
    wma->vidwin = NULL;
    if (wma->pgraph)
        IGraphBuilder_Release(wma->pgraph);
    wma->pgraph = NULL;
    if (wma->mevent)
        IMediaEvent_Release(wma->mevent);
    wma->mevent = NULL;
    if (wma->pmctrl)
        IMediaControl_Release(wma->pmctrl);
    wma->pmctrl = NULL;

    if (wma->uninit)
        CoUninitialize();
    wma->uninit = FALSE;

    return MCIERR_INTERNAL;
}
Ejemplo n.º 4
0
static void UnCOM (void)
{
	CoUninitialize ();
}
int main(int argc, char* argv[])
{
	
	
	IGraphBuilder         *pGraph = NULL;
	ICaptureGraphBuilder2 *pBuilder = NULL;
	IBaseFilter           *pSrc = NULL;
	IBaseFilter           *ppf = NULL;
	IFileSinkFilter       *pSink = NULL;
	IMediaControl         *pMC   = NULL;
	HRESULT hr;
	
	CoInitialize (NULL);
	// Create the filter graph.
	CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC,
	      IID_IGraphBuilder, (void **)&pGraph);

	// Create the capture graph builder.
	CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC, 
	      IID_ICaptureGraphBuilder2, (void **)&pBuilder);

	pBuilder->SetFiltergraph(pGraph);    
	
	pSrc=GetAudioDevice ();
	// add the first audio filter in the list
	pGraph->AddFilter(pSrc, L"Video Capture");

/*	pBuilder->SetOutputFileName(
		&MEDIASUBTYPE_Avi,
		L"C:\\Example.avi", 
		&ppf, 
		&pSink);*/
//	pBuilder->AllocCapFile (L"C:\\temp.avi", _MAX_PATH);

	pBuilder->RenderStream(
        &PIN_CATEGORY_CAPTURE,  // Pin category
        &MEDIATYPE_Audio,       // Media type
        pSrc,                   // Capture filter
        NULL,                   // Compression filter (optional)
        ppf                     // Multiplexer or renderer filter
    );


 
	REFERENCE_TIME  rtStart = 20000000, 
                rtStop = 50000000;

/*	pBuilder->ControlStream(
        &PIN_CATEGORY_CAPTURE, 
        &MEDIATYPE_Audio, 
        pSrc,       // Source filter
        &rtStart,   // Start time
        &rtStop,    // Stop time
        0,          // Start cookie
        0           // Stop cookie
	 );*/

	pGraph->QueryInterface (IID_IMediaControl, (void **) &pMC);
	pMC->Run ();

	MessageBox (NULL, "Stop Recording", NULL, NULL);
	pMC->Stop ();

/*	CProgress *pProg = new CProgress(TEXT(""), NULL, &hr);
        IAMCopyCaptureFileProgress *pIProg = NULL;
        
            hr = pProg->QueryInterface(IID_IAMCopyCaptureFileProgress,
                                            (void **)&pIProg);
	//pBuilder->CopyCaptureFile (L"C:\\temp.avi", L"C:\\final.avi", TRUE, pIProg);*/
   
	CoUninitialize ();
	
	return 0;
}
Ejemplo n.º 6
0
int main(int argc, char* argv[])
{
	HRESULT hr;
	IADs *pADs=NULL;
	LPWSTR pszADsPath = L"LDAP://CN=Jane Johnson,OU=testOU,DC=testDom1,DC=testDom2,DC=microsoft,DC=com";

	CoInitialize(NULL);

	///////////////////////////////////
	// Modifying attributes via IADs
	////////////////////////////////////
	hr = ADsGetObject(pszADsPath,
		              IID_IADs, 
			   	      (void**) &pADs );

	if (!SUCCEEDED(hr) )
	{
		return hr;
	}

	VARIANT var;
	
	
	// we omit checking result for brevity..

	// First Name
	VariantInit(&var);
	V_BSTR(&var) = SysAllocString(L"Janet");
	V_VT(&var) = VT_BSTR;
	hr = pADs->Put( L"givenName", var );

	// Last Name
	VariantClear(&var);
	V_BSTR(&var) = SysAllocString(L"Johns");
	V_VT(&var) = VT_BSTR;
	hr = pADs->Put( L"sn", var ); 
	VariantClear(&var);


	// Other Telephones
	LPWSTR pszPhones[] = { L"425 844 1234", L"425 924 4321" };
	DWORD dwNumber = sizeof( pszPhones ) /sizeof(LPWSTR);

	hr = ADsBuildVarArrayStr( pszPhones, dwNumber, &var );
	hr = pADs->Put( L"otherTelephone", var ); 
	VariantClear(&var);

	hr = pADs->SetInfo();
	pADs->Release();

	if (!SUCCEEDED(hr) )
	{
		
		return hr;
	}



	/////////////////////////////////////////////////
	// Alternatively, you can use IDirectoryObject
	//////////////////////////////////////////////////
	IDirectoryObject *pDir=NULL;
	hr = ADsGetObject(pszADsPath,
		              IID_IDirectoryObject, 
			   	      (void**) &pDir );

	if ( !SUCCEEDED(hr) )
	{
		return hr;
	}


	
	DWORD  dwReturn;
	ADSVALUE  snValue;
	ADSVALUE  fNameValue;
	ADSVALUE  phoneValue[2];

	ADS_ATTR_INFO  attrInfo[] = {   
		{L"givenName",ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING,&snValue,1},
		{L"sn", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING,&fNameValue,1 },
		{L"otherTelephone", ADS_ATTR_UPDATE, ADSTYPE_CASE_IGNORE_STRING, phoneValue,2 }
								};
	DWORD dwAttrs = sizeof(attrInfo)/sizeof(ADS_ATTR_INFO); 

	///// First Name ///////////
	fNameValue.dwType=ADSTYPE_CASE_IGNORE_STRING;
	fNameValue.CaseIgnoreString = L"Janet";
	
 
	///// Last Name ///////////
	snValue.dwType= ADSTYPE_CASE_IGNORE_STRING;
	snValue.CaseIgnoreString = L"Johns";
	
	///// Other Telephone ///////////
	phoneValue[0].dwType = ADSTYPE_CASE_IGNORE_STRING;
	phoneValue[0].CaseIgnoreString = L"425 844 1234";

	phoneValue[1].dwType = ADSTYPE_CASE_IGNORE_STRING;
	phoneValue[1].CaseIgnoreString = L"425 924 4321";

	hr = pDir->SetObjectAttributes(attrInfo, dwAttrs, &dwReturn);

	pDir->Release();

	if ( !SUCCEEDED(hr) )
	{
		return hr;
	}



	CoUninitialize();
	return 0;
}
bool PromptFileLocation(std::wstring& resultPath, std::wstring title=L"Open", fileType filterType=ft_exe)
{
    HRESULT hr;
    
    hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
    if (!SUCCEEDED(hr))
    {
        CoUninitialize();
        return false;
    }

    IFileOpenDialog *pFileOpen;
    // Create the FileOpenDialog object.
    hr = CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_ALL, IID_IFileOpenDialog, reinterpret_cast<void**>(&pFileOpen));
    if (!SUCCEEDED(hr))
    {
        pFileOpen->Release();
        CoUninitialize();
        return false;
    }

    // Set the filter type
    switch (filterType)
    {
    case ft_exe:
            {
                COMDLG_FILTERSPEC filter;
                filter.pszName = L"Windows Executable";
                filter.pszSpec = L"*.exe";
                hr = pFileOpen->SetFileTypes(1, &filter);
                break;
            }
    default:
        {
            break;
        }
    }
    if (!SUCCEEDED(hr))
    {
        pFileOpen->Release();
        CoUninitialize();
        return false;
    }

    // Set the title
    hr = pFileOpen->SetTitle(L"Please locate your Blender executable.");
    if (!SUCCEEDED(hr))
    {
        pFileOpen->Release();
        CoUninitialize();
        return false;
    }

    // Show the Open dialog box.
    hr = pFileOpen->Show(NULL);
    if (!SUCCEEDED(hr))
    {
        pFileOpen->Release();
        CoUninitialize();
        return false;
    }

    // Get the file name from the open dialog box.
    IShellItem *pItem;
    hr = pFileOpen->GetResult(&pItem);
    if (!SUCCEEDED(hr))
    {
        pItem->Release();
        pFileOpen->Release();
        CoUninitialize();
        return false;
    }

    PWSTR pszFilePath;
    hr = pItem->GetDisplayName(SIGDN_FILESYSPATH, &pszFilePath);

    if (!SUCCEEDED(hr))
    {
        pItem->Release();
        pFileOpen->Release();
        CoUninitialize();
        CoTaskMemFree(pszFilePath);
        return false;
    }

    resultPath = pszFilePath;
    CoTaskMemFree(pszFilePath);
    pItem->Release();
    pFileOpen->Release();
    CoUninitialize();
    return true;
}
Ejemplo n.º 8
0
		FX_WINOLEAPI_(void)		FX_CoUninitialize(void)
		{
			CoUninitialize();
		}
Ejemplo n.º 9
0
DWORD WINAPI ContentPartnerThreadProc(LPVOID lpParameter)
{
   CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx = NULL;
   CComPtr<IWMPContentPartnerCallback> spCallback;
   MSG msg = {0};
   HRESULT hr = S_OK;
   BOOL comInitialized = FALSE;

   if(NULL == lpParameter)
   {
      hr = E_INVALIDARG;
      goto cleanup;
   }

   pThreadCtx = static_cast<CONTENT_PARTNER_THREAD_CONTEXT*>(lpParameter);

   if(NULL == pThreadCtx->pIStream)
   {
      hr = E_INVALIDARG;
      goto cleanup;
   }

   hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

   if(FAILED(hr))
   {
      ATLTRACE2("%x: ContentPartnerThreadProc(type %d): CoInitializeEx failed. %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);
      goto cleanup;
   }  

   comInitialized = TRUE;

   // Get a pointer to an IWMPContentPartnerCallback interface.

   hr = CoGetInterfaceAndReleaseStream(
      pThreadCtx->pIStream,
      __uuidof(IWMPContentPartnerCallback),
      reinterpret_cast<LPVOID*>(&spCallback) );

   // The stream was released (even if CoGetInterfaceAndReleaseStream failed). 
   // Set the stream pointer to NULL.
   pThreadCtx->pIStream = NULL;

   if(FAILED(hr))
   {
      ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Failed to get IWMPContentPartnerCallback interface. %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);
      goto cleanup;
   }

   if(NULL == spCallback)
   {
      hr = E_UNEXPECTED;
      goto cleanup;
   }

   ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Succeeded in getting IWMPContentPartnerCallback interface.\n", GetCurrentThreadId(), pThreadCtx->threadType);

   // Make sure we have a message queue.
   PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);

   // Tell the main thread that we are ready to receive messages.
   SetEvent(pThreadCtx->hInitialized);

   hr = ContentPartnerMessageLoop(pThreadCtx, spCallback);

cleanup:

   if(NULL != pThreadCtx)
   {
      // Set this event here, just in case there was a "goto cleanup"
      // before the event was set.
      SetEvent(pThreadCtx->hInitialized);

      // The thread that started this thread allocated a
      // CONTENT_PARTNER_THREAD_CONTEXT structure.
      // We must free that memory here.
   
     if(NULL != pThreadCtx->pIStream)
      {
         // For some reason, CoGetInterfaceAndReleaseStream never got called.
         // So release the stream here.
         pThreadCtx->pIStream->Release();
         pThreadCtx->pIStream = NULL;
      }

      ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Returning %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);

      delete pThreadCtx;
      pThreadCtx = NULL;
   }
                   
   if(comInitialized)
   {
      CoUninitialize();
   } 

 
   return hr;
}
Ejemplo n.º 10
0
void  main()
{
	// DirectShowのインスタンス宣言
	IGraphBuilder *p_graph=NULL;
	IMediaControl *p_control=NULL;
	IMediaEvent   *p_event=NULL;

	HRESULT hr;   // 処理結果

	long event_code;   // イベントコード

	// COMライブラリの初期化
	hr=CoInitialize(NULL);

	// フィルタグラフのインスタンスを生成
	hr=CoCreateInstance(
			CLSID_FilterGraph,	  // フィルタグラフのクラスID
			NULL,				// 非アグリゲートオブジェクト
			CLSCTX_INPROC_SERVER,   // 呼び出し側と同じプロセスで実行
			IID_IGraphBuilder,	  // グラフビルダでオブジェクト間通信する
			(void **)&p_graph);	 // インスタンスを入れるポインタ

	// フィルタグラフからIMediaControlを取得する
	hr=p_graph->QueryInterface(
			IID_IMediaControl,	  //IMediaControlのインターフェース指定
			(void **)&p_control);   //IMediaControlを入れるポインタ

	// フィルタグラフからIMediaEventを取得する
	hr=p_graph->QueryInterface(
			IID_IMediaEvent,		//IMediaEventのインターフェース指定
			(void **)&p_event);	 //IMediaEventを入れるポインタ

	// 再生するファイルを指定する
	hr=p_graph->RenderFile(
			L"C:\\workdir\\testh.mp3",  // メディアファイル名
			NULL);								// 予約(NULL固定)

	// ファイルのレンダリングに成功したらグラフを実行する
	if(SUCCEEDED(hr))
	{
	  // グラフを実行する
	  hr=p_control->Run();

	 if( hr == S_OK )
	  {
		// グラフの実行に成功したら完了するまでイベントを待つ
		p_event->WaitForCompletion(
			INFINITE,				 // イベントタイマー(無期限)
			&event_code);			 // イベント結果コード
	  }
	}

	// IMediaControlを開放する
	p_control->Release();

	// IMediaEventを開放する
	p_event->Release();

	// フィルタグラフを開放する
	p_graph->Release();

	// COMライブラリを開放する
	CoUninitialize();
}
Ejemplo n.º 11
0
int WINAPI WinMain_(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
	// make vnc last service to stop
	SetProcessShutdownParameters(0x100,false);
	// handle dpi on aero
	HMODULE hUser32 = LoadLibrary(_T("user32.dll"));
	typedef BOOL (*SetProcessDPIAwareFunc)();
	SetProcessDPIAwareFunc setDPIAware = (SetProcessDPIAwareFunc)GetProcAddress(hUser32, "SetProcessDPIAware");
	if (setDPIAware) setDPIAware();
	FreeLibrary(hUser32);

#ifdef IPP
	InitIpp();
#endif
#ifdef CRASHRPT
	Install(NULL, _T("*****@*****.**"), _T(""));
#endif
	bool Injected_autoreconnect=false;
	SPECIAL_SC_EXIT=false;
	SPECIAL_SC_PROMPT=false;
	SetOSVersion();
	setbuf(stderr, 0);

	// [v1.0.2-jp1 fix] Load resouce from dll
	hInstResDLL = NULL;

	 //limit the vnclang.dll searchpath to avoid
	char szCurrentDir[MAX_PATH];
	char szCurrentDir_vnclangdll[MAX_PATH];
	if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH))
	{
		char* p = strrchr(szCurrentDir, '\\');
		*p = '\0';
	}
	strcpy (szCurrentDir_vnclangdll,szCurrentDir);
	strcat (szCurrentDir_vnclangdll,"\\");
	strcat (szCurrentDir_vnclangdll,"vnclang_server.dll");

	hInstResDLL = LoadLibrary(szCurrentDir_vnclangdll);

	if (hInstResDLL == NULL)
	{
		hInstResDLL = hInstance;
	}
//	RegisterLinkLabel(hInstResDLL);

    //Load all messages from ressource file
    Load_Localization(hInstResDLL) ;

	char WORKDIR[MAX_PATH];
	if (GetModuleFileName(NULL, WORKDIR, MAX_PATH))
		{
		char* p = strrchr(WORKDIR, '\\');
		if (p == NULL) return 0;
		*p = '\0';
		}
    char progname[MAX_PATH];
    strncpy(progname, WORKDIR, sizeof progname);
    progname[MAX_PATH - 1] = 0;
	//strcat(WORKDIR,"\\");
	//strcat(WORKDIR,"WinVNC.log");

	vnclog.SetFile();
//	vnclog.SetMode(2);
//	vnclog.SetLevel(10);

#ifdef _DEBUG
	{
		// Get current flag
		int tmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );

		// Turn on leak-checking bit
		tmpFlag |= _CRTDBG_LEAK_CHECK_DF;

		// Set flag to the new value
		_CrtSetDbgFlag( tmpFlag );
	}
#endif

	// Save the application instance and main thread id
	hAppInstance = hInstance;
	mainthreadId = GetCurrentThreadId();

	// Initialise the VSocket system
	VSocketSystem socksys;
	if (!socksys.Initialised())
	{
		MessageBoxSecure(NULL, sz_ID_FAILED_INIT, szAppName, MB_OK);
		return 0;
	}
    // look up the current service name in the registry.
    GetServiceName(progname, service_name);

	// Make the command-line lowercase and parse it
	size_t i;
	for (i = 0; i < strlen(szCmdLine); i++)
	{
		szCmdLine[i] = tolower(szCmdLine[i]);
	}
	BOOL argfound = FALSE;
	for (i = 0; i < strlen(szCmdLine); i++)
	{
		if (szCmdLine[i] <= ' ')
			continue;
		argfound = TRUE;

		if (strncmp(&szCmdLine[i], winvncSettingshelper, strlen(winvncSettingshelper)) == 0)
		{
			Sleep(3000);
			char mycommand[MAX_PATH];
			i+=strlen(winvncSettingshelper);
			strcpy( mycommand, &(szCmdLine[i+1]));
			Set_settings_as_admin(mycommand);
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncStopserviceHelper, strlen(winvncStopserviceHelper)) == 0)
		{
			Sleep(3000);
			Set_stop_service_as_admin();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncKill, strlen(winvncKill)) == 0)
		{
			static HANDLE		hShutdownEventTmp;
			hShutdownEventTmp = OpenEvent(EVENT_ALL_ACCESS, FALSE, "Global\\SessionEventUltra");
			SetEvent(hShutdownEventTmp);
			CloseHandle(hShutdownEventTmp);

			//adzm 2010-02-10 - Finds the appropriate VNC window for any process. Sends this message to all of them!
			HWND hservwnd = NULL;
			do {
				if (hservwnd!=NULL)
				{
					PostMessage(hservwnd, WM_COMMAND, 40002, 0);
					PostMessage(hservwnd, WM_CLOSE, 0, 0);
				}
				hservwnd = FindWinVNCWindow(false);
			} while (hservwnd!=NULL);
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncopenhomepage, strlen(winvncopenhomepage)) == 0)
		{
			Open_homepage();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncopenforum, strlen(winvncopenforum)) == 0)
		{
			Open_forum();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncStartserviceHelper, strlen(winvncStartserviceHelper)) == 0)
		{
			Sleep(3000);
			Set_start_service_as_admin();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncInstallServiceHelper, strlen(winvncInstallServiceHelper)) == 0)
			{
				//Sleeps are realy needed, else runas fails...
				Sleep(3000);
				Set_install_service_as_admin();
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncUnInstallServiceHelper, strlen(winvncUnInstallServiceHelper)) == 0)
			{
				Sleep(3000);
				Set_uninstall_service_as_admin();
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncSoftwarecadHelper, strlen(winvncSoftwarecadHelper)) == 0)
			{
				Sleep(3000);
				Enable_softwareCAD_elevated();
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncdelSoftwarecadHelper, strlen(winvncdelSoftwarecadHelper)) == 0)
			{
				Sleep(3000);
				delete_softwareCAD_elevated();
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncRebootSafeHelper, strlen(winvncRebootSafeHelper)) == 0)
			{
				Sleep(3000);
				Reboot_in_safemode_elevated();
				return 0;
			}

		if (strncmp(&szCmdLine[i], winvncRebootForceHelper, strlen(winvncRebootForceHelper)) == 0)
			{
				Sleep(3000);
				Reboot_with_force_reboot_elevated();
				return 0;
			}

		if (strncmp(&szCmdLine[i], winvncSecurityEditorHelper, strlen(winvncSecurityEditorHelper)) == 0)
			{
				Sleep(3000);
				winvncSecurityEditorHelper_as_admin();
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncSecurityEditor, strlen(winvncSecurityEditor)) == 0)
			{
			    typedef void (*vncEditSecurityFn) (HWND hwnd, HINSTANCE hInstance);
				vncEditSecurityFn vncEditSecurity = 0;
				char szCurrentDir[MAX_PATH];
					if (GetModuleFileName(NULL, szCurrentDir, MAX_PATH)) {
						char* p = strrchr(szCurrentDir, '\\');
						*p = '\0';
						strcat (szCurrentDir,"\\authSSP.dll");
					}
					HMODULE hModule = LoadLibrary(szCurrentDir);
					if (hModule) {
						vncEditSecurity = (vncEditSecurityFn) GetProcAddress(hModule, "vncEditSecurity");
						HRESULT hr = CoInitialize(NULL);
						vncEditSecurity(NULL, hAppInstance);
						CoUninitialize();
						FreeLibrary(hModule);
					}
				return 0;
			}

		if (strncmp(&szCmdLine[i], winvncSettings, strlen(winvncSettings)) == 0)
		{
			char mycommand[MAX_PATH];
			i+=strlen(winvncSettings);
			strcpy( mycommand, &(szCmdLine[i+1]));
			Real_settings(mycommand);
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncSoftwarecad, strlen(winvncSoftwarecad)) == 0)
		{
			Enable_softwareCAD();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncdelSoftwarecad, strlen(winvncdelSoftwarecad)) == 0)
		{
			delete_softwareCAD();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncRebootSafe, strlen(winvncRebootSafe)) == 0)
		{
			Reboot_in_safemode();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncRebootForce, strlen(winvncRebootForce)) == 0)
		{
			Reboot_with_force_reboot();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncStopservice, strlen(winvncStopservice)) == 0)
		{
			Real_stop_service();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncStartservice, strlen(winvncStartservice)) == 0)
		{
			Real_start_service();
			return 0;
		}

		if (strncmp(&szCmdLine[i], winvncInstallService, strlen(winvncInstallService)) == 0)
			{
                // rest of command line service name, if provided.
                char *pServiceName = &szCmdLine[i];
                // skip over command switch, find next whitepace
                while (*pServiceName && !isspace(*(unsigned char*)pServiceName))
                    ++pServiceName;

                // skip past whitespace to service name
                while (*pServiceName && isspace(*(unsigned char*)pServiceName))
                    ++pServiceName;

                // strip off any quotes
                if (*pServiceName && *pServiceName == '\"')
                    ++pServiceName;

                if (*pServiceName)
                {
                    // look for trailing quote, if found, terminate the string there.
                    char *pQuote = pServiceName;
                    pQuote = strrchr(pServiceName, '\"');
                    if (pQuote)
                        *pQuote = 0;
                }
                // if a service name is supplied, and it differs except in case from
                // the default, use the supplied service name instead
                if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0))
                {
                    strncpy(service_name, pServiceName, 256);
                    service_name[255] = 0;
                }
				install_service();
				Sleep(2000);
				char command[MAX_PATH + 32]; // 29 January 2008 jdp
                _snprintf(command, sizeof command, "net start \"%s\"", service_name);
				WinExec(command,SW_HIDE);
				return 0;
			}
		if (strncmp(&szCmdLine[i], winvncUnInstallService, strlen(winvncUnInstallService)) == 0)
			{
				char command[MAX_PATH + 32]; // 29 January 2008 jdp
                // rest of command line service name, if provided.
                char *pServiceName = &szCmdLine[i];
                // skip over command switch, find next whitepace
                while (*pServiceName && !isspace(*(unsigned char*)pServiceName))
                    ++pServiceName;

                // skip past whitespace to service name
                while (*pServiceName && isspace(*(unsigned char*)pServiceName))
                    ++pServiceName;

                // strip off any quotes
                if (*pServiceName && *pServiceName == '\"')
                    ++pServiceName;

                if (*pServiceName)
                {
                    // look for trailing quote, if found, terminate the string there.
                    char *pQuote = pServiceName;
                    pQuote = strrchr(pServiceName, '\"');
                    if (pQuote)
                        *pQuote = 0;
                }

                if (*pServiceName && (_strcmpi(pServiceName, service_name) != 0))
                {
                    strncpy(service_name, pServiceName, 256);
                    service_name[255] = 0;
                }
                _snprintf(command, sizeof command, "net stop \"%s\"", service_name);
				WinExec(command,SW_HIDE);
				uninstall_service();
				return 0;
			}

		if (strncmp(&szCmdLine[i], winvncRunService, strlen(winvncRunService)) == 0)
		{
			//Run as service
			if (!Myinit(hInstance)) return 0;
			fRunningFromExternalService = true;
			vncService::RunningFromExternalService(true);
			return WinVNCAppMain();
		}

		if (strncmp(&szCmdLine[i], winvncStartService, strlen(winvncStartService)) == 0)
		{
		start_service(szCmdLine);
		return 0;
		}

		if (strncmp(&szCmdLine[i], winvncRunAsUserApp, strlen(winvncRunAsUserApp)) == 0)
		{
			// WinVNC is being run as a user-level program
			if (!Myinit(hInstance)) return 0;
			return WinVNCAppMain();
		}

		if (strncmp(&szCmdLine[i], winvncSCexit, strlen(winvncSCexit)) == 0)
		{
			SPECIAL_SC_EXIT=true;
			i+=strlen(winvncSCexit);
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncSCprompt, strlen(winvncSCprompt)) == 0)
		{
			SPECIAL_SC_PROMPT=true;
			i+=strlen(winvncSCprompt);
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncmulti, strlen(winvncmulti)) == 0)
		{
			multi=true;
			i+=strlen(winvncmulti);
			continue;
		}

		if (strncmp(&szCmdLine[i], winvnchttp, strlen(winvnchttp)) == 0)
		{
			G_HTTP=true;
			i+=strlen(winvnchttp);
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncStopReconnect, strlen(winvncStopReconnect)) == 0)
		{
			i+=strlen(winvncStopReconnect);
			vncService::PostAddStopConnectClientAll();
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncAutoReconnect, strlen(winvncAutoReconnect)) == 0)
		{
			// Note that this "autoreconnect" param MUST be BEFORE the "connect" one
			// on the command line !
			// wa@2005 -- added support for the AutoReconnectId
			i+=strlen(winvncAutoReconnect);
			Injected_autoreconnect=true;
			int start, end;
			char* pszId = NULL;
			start = i;
			// skip any spaces and grab the parameter
			while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++;

			if ( strncmp( &szCmdLine[start], winvncAutoReconnectId, strlen(winvncAutoReconnectId) ) == 0 )
			{
				end = start;
				while (szCmdLine[end] > ' ') end++;

				pszId = new char[ end - start + 1 ];
				if (pszId != 0)
				{
					strncpy( pszId, &(szCmdLine[start]), end - start );
					pszId[ end - start ] = 0;
					pszId = _strupr( pszId );
				}
//multiple spaces between autoreconnect and id
				i = end;
			}// end of condition we found the ID: parameter

			// NOTE:  id must be NULL or the ID:???? (pointer will get deleted when message is processed)
			// We can not contact a runnning service, permissions, so we must store the settings
			// and process until the vncmenu has been started

			if (!vncService::PostAddAutoConnectClient( pszId ))
			{
				PostAddAutoConnectClient_bool=true;
				if (pszId==NULL)
				{
					PostAddAutoConnectClient_bool_null=true;
					PostAddAutoConnectClient_bool=false;
				}
				else
				{
					strcpy(pszId_char,pszId);
					//memory leak fix
					delete [] pszId;
				}
			}
			continue;
		}

		if ( strncmp( &szCmdLine[i], winvncReconnectId, strlen(winvncReconnectId) ) == 0 )
			{
				i+=strlen("-");
				int start, end;
				char* pszId = NULL;
				start = i;
				end = start;
				while (szCmdLine[end] > ' ') end++;

				pszId = new char[ end - start + 1 ];
				if (pszId != 0)
				{
					strncpy( pszId, &(szCmdLine[start]), end - start );
					pszId[ end - start ] = 0;
					pszId = _strupr( pszId );
				}
				i = end;
			if (!vncService::PostAddConnectClient( pszId ))
			{
				PostAddConnectClient_bool=true;
				if (pszId==NULL)
				{
					PostAddConnectClient_bool_null=true;
					PostAddConnectClient_bool=false;
				}
				else
				{
					strcpy(pszId_char,pszId);
					//memory leak fix
					delete [] pszId;
				}
				}
			continue;
		}

		if (strncmp(&szCmdLine[i], winvncConnect, strlen(winvncConnect)) == 0)
		{
			if (!Injected_autoreconnect)
			{
				vncService::PostAddStopConnectClient();
			}
			// Add a new client to an existing copy of winvnc
			i+=strlen(winvncConnect);

			// First, we have to parse the command line to get the filename to use
			int start, end;
			start=i;
			while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++;
			end = start;
			while (szCmdLine[end] > ' ') end++;

			// Was there a hostname (and optionally a port number) given?
			if (end-start > 0)
			{
				char *name = new char[end-start+1];
				if (name != 0) {
					strncpy(name, &(szCmdLine[start]), end-start);
					name[end-start] = 0;

					int port = INCOMING_PORT_OFFSET;
					char *portp = strchr(name, ':');
					if (portp) {
						*portp++ = '\0';
						if (*portp == ':') {
							port = atoi(++portp);	// Port number after "::"
						} else {
							port = atoi(portp);	// Display number after ":"
						}
					}
					vnclog.Print(LL_STATE, VNCLOG("test... %s %d\n"),name,port);
					strcpy_s(dnsname,name);
					VCard32 address = VSocket::Resolve(name);
					delete [] name;
					if (address != 0) {
						// Post the IP address to the server
						// We can not contact a runnning service, permissions, so we must store the settings
						// and process until the vncmenu has been started
						vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient III \n"));
						if (!vncService::PostAddNewClientInit(address, port))
						{
						PostAddNewClient_bool=true;
						port_int=port;
						address_vcard=address;
						}
					}
					else
					{
						//ask for host,port
						PostAddNewClient_bool=true;
						port_int=0;
						address_vcard=0;
						Sleep(2000);
						//Beep(200,1000);
						return 0;
					}
				}
				i=end;
				continue;
			}
			else
			{
				// Tell the server to show the Add New Client dialog
				// We can not contact a runnning service, permissions, so we must store the settings
				// and process until the vncmenu has been started
				vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n"));
				if (!vncService::PostAddNewClient(0, 0))
				{
				PostAddNewClient_bool=true;
				port_int=0;
				address_vcard=0;
				}
			}
			continue;
		}

		//adzm 2009-06-20
		if (strncmp(&szCmdLine[i], winvncRepeater, strlen(winvncRepeater)) == 0)
		{
			// set the default repeater host
			i+=strlen(winvncRepeater);

			// First, we have to parse the command line to get the host to use
			int start, end;
			start=i;
			while (szCmdLine[start] <= ' ' && szCmdLine[start] != 0) start++;
			end = start;
			while (szCmdLine[end] > ' ') end++;

			// Was there a hostname (and optionally a port number) given?
			if (end-start > 0)
			{
				if (g_szRepeaterHost) {
					delete[] g_szRepeaterHost;
					g_szRepeaterHost = NULL;
				}
				g_szRepeaterHost = new char[end-start+1];
				if (g_szRepeaterHost != 0) {
					strncpy(g_szRepeaterHost, &(szCmdLine[start]), end-start);
					g_szRepeaterHost[end-start] = 0;

					// We can not contact a runnning service, permissions, so we must store the settings
					// and process until the vncmenu has been started
					vnclog.Print(LL_INTERR, VNCLOG("PostAddNewRepeaterClient I\n"));
					if (!vncService::PostAddNewRepeaterClient())
					{
						PostAddNewRepeaterClient_bool=true;
						port_int=0;
						address_vcard=0;
					}
				}
				i=end;
				continue;
			}
			else
			{
				/*
				// Tell the server to show the Add New Client dialog
				// We can not contact a runnning service, permissions, so we must store the settings
				// and process until the vncmenu has been started
				vnclog.Print(LL_INTERR, VNCLOG("PostAddNewClient IIII\n"));
				if (!vncService::PostAddNewClient(0, 0))
				{
				PostAddNewClient_bool=true;
				port_int=0;
				address_vcard=0;
				}
				*/
			}
			continue;
		}

		// Either the user gave the -help option or there is something odd on the cmd-line!

		// Show the usage dialog
		MessageBoxSecure(NULL, winvncUsageText, sz_ID_WINVNC_USAGE, MB_OK | MB_ICONINFORMATION);
		break;
	};

	// If no arguments were given then just run
	if (!argfound)
	{
		if (!Myinit(hInstance)) return 0;
		return WinVNCAppMain();
	}

	return 0;
}
Ejemplo n.º 12
0
static DWORD CALLBACK watch_desktop_folders( LPVOID param )
{
    HWND hwnd = param;
    HRESULT init = CoInitialize( NULL );
    HANDLE dir0, dir1, events[2];
    OVERLAPPED ovl0, ovl1;
    char *buf0 = NULL, *buf1 = NULL;
    DWORD count, size = 4096, error = ERROR_OUTOFMEMORY;
    BOOL ret, redraw;

    dir0 = CreateFileW( desktop_folder, FILE_LIST_DIRECTORY|SYNCHRONIZE, FILE_SHARE_READ|FILE_SHARE_WRITE,
                        NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED, NULL );
    if (dir0 == INVALID_HANDLE_VALUE) return GetLastError();
    dir1 = CreateFileW( desktop_folder_public, FILE_LIST_DIRECTORY|SYNCHRONIZE, FILE_SHARE_READ|FILE_SHARE_WRITE,
                        NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OVERLAPPED, NULL );
    if (dir1 == INVALID_HANDLE_VALUE)
    {
        CloseHandle( dir0 );
        return GetLastError();
    }
    if (!(ovl0.hEvent = events[0] = CreateEventW( NULL, FALSE, FALSE, NULL ))) goto error;
    if (!(ovl1.hEvent = events[1] = CreateEventW( NULL, FALSE, FALSE, NULL ))) goto error;
    if (!(buf0 = HeapAlloc( GetProcessHeap(), 0, size ))) goto error;
    if (!(buf1 = HeapAlloc( GetProcessHeap(), 0, size ))) goto error;

    for (;;)
    {
        ret = ReadDirectoryChangesW( dir0, buf0, size, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME, NULL, &ovl0, NULL );
        if (!ret)
        {
            error = GetLastError();
            goto error;
        }
        ret = ReadDirectoryChangesW( dir1, buf1, size, FALSE, FILE_NOTIFY_CHANGE_FILE_NAME, NULL, &ovl1, NULL );
        if (!ret)
        {
            error = GetLastError();
            goto error;
        }

        redraw = FALSE;
        switch ((error = WaitForMultipleObjects( 2, events, FALSE, INFINITE )))
        {
        case WAIT_OBJECT_0:
            if (!GetOverlappedResult( dir0, &ovl0, &count, FALSE ) || !count) break;
            if (process_changes( desktop_folder, buf0 )) redraw = TRUE;
            break;

        case WAIT_OBJECT_0 + 1:
            if (!GetOverlappedResult( dir1, &ovl1, &count, FALSE ) || !count) break;
            if (process_changes( desktop_folder_public, buf1 )) redraw = TRUE;
            break;

        default:
            goto error;
        }
        if (redraw) InvalidateRect( hwnd, NULL, TRUE );
    }

error:
    CloseHandle( dir0 );
    CloseHandle( dir1 );
    CloseHandle( events[0] );
    CloseHandle( events[1] );
    HeapFree( GetProcessHeap(), 0, buf0 );
    HeapFree( GetProcessHeap(), 0, buf1 );
    if (SUCCEEDED( init )) CoUninitialize();
    return error;
}
Ejemplo n.º 13
0
static void LeaveMTA(void)
{
    CoUninitialize();
}
Ejemplo n.º 14
0
CCameraDS::~CCameraDS()
{
	CloseCamera();
	CoUninitialize();
}
Ejemplo n.º 15
0
//=============================================================================
// 初期化
//=============================================================================
HRESULT InitSound(HWND hWnd)
{
	HRESULT hr;

	// COMライブラリの初期化
	CoInitializeEx(NULL, COINIT_MULTITHREADED);

	// XAudio2オブジェクトの作成
	hr = XAudio2Create(&g_pXAudio2, 0);
	if(FAILED(hr))
	{
		// COMライブラリの終了処理
		CoUninitialize();
		return E_FAIL;
	}
	
	// マスターボイスの生成
	hr = g_pXAudio2->CreateMasteringVoice(&g_pMasteringVoice);
	if(FAILED(hr))
	{
		if(g_pXAudio2)
		{
			// XAudio2オブジェクトの開放
			g_pXAudio2->Release();
			g_pXAudio2 = NULL;
		}

		// COMライブラリの終了処理
		CoUninitialize();

		return E_FAIL;
	}

	// サウンドデータの初期化
	for(int nCntSound = 0; nCntSound < SOUND_LABEL_MAX; nCntSound++)
	{
		HANDLE hFile;
		DWORD dwChunkSize = 0;
		DWORD dwChunkPosition = 0;
		DWORD dwFiletype;
		WAVEFORMATEXTENSIBLE wfx;
		XAUDIO2_BUFFER buffer;

		// バッファのクリア
		memset(&wfx, 0, sizeof(WAVEFORMATEXTENSIBLE));
		memset(&buffer, 0, sizeof(XAUDIO2_BUFFER));

		// サウンドデータファイルの生成
		hFile = CreateFile(g_aParam[nCntSound].pFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
		if(hFile == INVALID_HANDLE_VALUE)
		{
			return HRESULT_FROM_WIN32(GetLastError());
		}
		if(SetFilePointer(hFile, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
		{// ファイルポインタを先頭に移動
			return HRESULT_FROM_WIN32(GetLastError());
		}
	
		// WAVEファイルのチェック
		hr = CheckChunk(hFile, 'FFIR', &dwChunkSize, &dwChunkPosition);
		if(FAILED(hr))
		{
			return S_FALSE;
		}
		hr = ReadChunkData(hFile, &dwFiletype, sizeof(DWORD), dwChunkPosition);
		if(FAILED(hr))
		{
			return S_FALSE;
		}
		if(dwFiletype != 'EVAW')
		{
			return S_FALSE;
		}
	
		// フォーマットチェック
		hr = CheckChunk(hFile, ' tmf', &dwChunkSize, &dwChunkPosition);
		if(FAILED(hr))
		{
			return S_FALSE;
		}
		hr = ReadChunkData(hFile, &wfx, dwChunkSize, dwChunkPosition);
		if(FAILED(hr))
		{
			return S_FALSE;
		}

		// オーディオデータ読み込み
		hr = CheckChunk(hFile, 'atad', &g_aSizeAudio[nCntSound], &dwChunkPosition);
		if(FAILED(hr))
		{
			return S_FALSE;
		}
		g_apDataAudio[nCntSound] = (BYTE*)malloc(g_aSizeAudio[nCntSound]);
		hr = ReadChunkData(hFile, g_apDataAudio[nCntSound], g_aSizeAudio[nCntSound], dwChunkPosition);
		if(FAILED(hr))
		{
			return S_FALSE;
		}
	
		// ソースボイスの生成
		g_pXAudio2->CreateSourceVoice(&g_apSourceVoice[nCntSound], &(wfx.Format));

		memset(&buffer, 0, sizeof(XAUDIO2_BUFFER));
		buffer.AudioBytes = g_aSizeAudio[nCntSound];
		buffer.pAudioData = g_apDataAudio[nCntSound];
		buffer.Flags      = XAUDIO2_END_OF_STREAM;
		buffer.LoopCount  = 0;

		// オーディオバッファの登録
		g_apSourceVoice[nCntSound]->SubmitSourceBuffer(&buffer);
	}

	return S_OK;
}
Ejemplo n.º 16
0
//=============================================================================
// 初期化
//=============================================================================
bool Sound::Initialize(HWND hWnd)
{
	HRESULT hr;

	//----------------------------
	// COMライブラリの初期化
	//----------------------------
	CoInitializeEx(nullptr, COINIT_MULTITHREADED);

	//----------------------------
	// XAudio2オブジェクトの作成
	//----------------------------
	hr = XAudio2Create(&m_xAudio2, 0);
	if(FAILED(hr))
	{
		MessageBox(hWnd, "XAudio2オブジェクトの作成に失敗!", "警告!", MB_ICONWARNING);

		// COMライブラリの終了処理
		CoUninitialize();
		return false;
	}

	//----------------------------
	// マスターボイスの生成
	//----------------------------
	hr = m_xAudio2->CreateMasteringVoice(&m_masteringVoice);
	if(FAILED(hr))
	{
		MessageBox(hWnd, "マスターボイスの生成に失敗!", "警告!", MB_ICONWARNING);

		// XAudio2オブジェクトの開放
		SafeRelease(m_xAudio2);

		// COMライブラリの終了処理
		CoUninitialize();

		return false;
	}

	//----------------------------
	// サウンドデータの初期化
	//----------------------------
	DWORD	dwChunkSize		= 0;
	DWORD	dwChunkPosition	= 0;
	DWORD	dwFiletype		= 0;
	WAVEFORMATEXTENSIBLE wfx;
	XAUDIO2_BUFFER		 buffer;
	HANDLE	file;
	char	str[512];

	for(int cnt = 0; cnt < SOUND_MAX; ++cnt)
	{
		dwChunkSize		= 0;
		dwChunkPosition	= 0;
		dwFiletype		= 0;

		//----------------------------
		// バッファのクリア
		//----------------------------
		memset(&wfx, 0, sizeof(WAVEFORMATEXTENSIBLE));
		memset(&buffer, 0, sizeof(XAUDIO2_BUFFER));

		//----------------------------
		// パス連結
		//----------------------------
		memset(str, 0, sizeof(str));
		strcpy_s(str, _sound_path);
		strcat_s(str, sizeof(str), _sound_data[cnt].fileName);

		//----------------------------
		// サウンドデータファイルの生成
		//----------------------------
		file = CreateFile(str, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr);
		if(file == INVALID_HANDLE_VALUE)
		{
			MessageBox(hWnd, "サウンドデータファイルの生成に失敗!(1)", "警告!", MB_ICONWARNING);
			//return HRESULT_FROM_WIN32(GetLastError());
			return false;
		}
		if(SetFilePointer(file, 0, nullptr, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
		{// ファイルポインタを先頭に移動
			MessageBox(hWnd, "サウンドデータファイルの生成に失敗!(2)", "警告!", MB_ICONWARNING);
			//return HRESULT_FROM_WIN32(GetLastError());
			return false;
		}

		//----------------------------
		// WAVEファイルのチェック
		//----------------------------
		hr = CheckChunk(file, 'FFIR', &dwChunkSize, &dwChunkPosition);
		if(FAILED(hr))
		{
			MessageBox(hWnd, "WAVEファイルのチェックに失敗!(1)", "警告!", MB_ICONWARNING);
			return false;
		}
		hr = ReadChunkData(file, &dwFiletype, sizeof(DWORD), dwChunkPosition);
		if(FAILED(hr))
		{
			MessageBox(hWnd, "WAVEファイルのチェックに失敗!(2)", "警告!", MB_ICONWARNING);
			return false;
		}
		if(dwFiletype != 'EVAW')
		{
			MessageBox(hWnd, "WAVEファイルのチェックに失敗!(3)", "警告!", MB_ICONWARNING);
			return false;
		}

		//----------------------------
		// フォーマットチェック
		//----------------------------
		hr = CheckChunk(file, ' tmf', &dwChunkSize, &dwChunkPosition);
		if(FAILED(hr))
		{
			MessageBox(hWnd, "フォーマットチェックに失敗!(1)", "警告!", MB_ICONWARNING);
			return false;
		}
		hr = ReadChunkData(file, &wfx, dwChunkSize, dwChunkPosition);
		if(FAILED(hr))
		{
			MessageBox(hWnd, "フォーマットチェックに失敗!(2)", "警告!", MB_ICONWARNING);
			return false;
		}

		//----------------------------
		// オーディオデータ読み込み
		//----------------------------
		hr = CheckChunk(file, 'atad', &m_sizeAudio[cnt], &dwChunkPosition);
		if(FAILED(hr))
		{
			MessageBox(hWnd, "オーディオデータ読み込みに失敗!(1)", "警告!", MB_ICONWARNING);
			return false;
		}
		m_dataAudio[cnt] = (BYTE*)malloc(m_sizeAudio[cnt]);
		hr = ReadChunkData(file, m_dataAudio[cnt], m_sizeAudio[cnt], dwChunkPosition);
		if(FAILED(hr))
		{
			MessageBox(hWnd, "オーディオデータ読み込みに失敗!(2)", "警告!", MB_ICONWARNING);
			return false;
		}

		//----------------------------
		// ソースボイスの生成
		//----------------------------
		hr = m_xAudio2->CreateSourceVoice(&m_sourceVoice[cnt], &(wfx.Format));
		if(FAILED(hr))
		{
			MessageBox(hWnd, "ソースボイスの生成に失敗!", "警告!", MB_ICONWARNING);
			return false;
		}

		memset(&buffer, 0, sizeof(XAUDIO2_BUFFER));
		buffer.AudioBytes	= m_sizeAudio[cnt];
		buffer.pAudioData	= m_dataAudio[cnt];
		buffer.Flags		= XAUDIO2_END_OF_STREAM;
		buffer.LoopCount	= 0;

		//----------------------------
		// オーディオバッファの登録
		//----------------------------
		m_sourceVoice[cnt]->SubmitSourceBuffer(&buffer);
	}

	return true;
}
Ejemplo n.º 17
0
int APIENTRY _tWinMain(HINSTANCE hInstance,
                       HINSTANCE /*hPrevInstance*/,
                       LPTSTR    lpCmdLine,
                       int       /*nCmdShow*/)
{
    SetDllDirectory(L"");
    SetTaskIDPerUUID();
    CRegStdDWORD loc = CRegStdDWORD(_T("Software\\TortoiseGit\\LanguageID"), 1033);
    long langId = loc;
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

    CLangDll langDLL;
    hResource = langDLL.Init(_T("TortoiseIDiff"), langId);
    if (hResource == NULL)
        hResource = hInstance;

    git_libgit2_init();

    CCmdLineParser parser(lpCmdLine);

    if (parser.HasKey(_T("?")) || parser.HasKey(_T("help")))
    {
        TCHAR buf[1024] = { 0 };
        LoadString(hResource, IDS_COMMANDLINEHELP, buf, _countof(buf));
        MessageBox(NULL, buf, _T("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 = (HCURSOR)LoadImage(hInst, MAKEINTRESOURCE(IDC_PANCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE);
    curHandDown = (HCURSOR)LoadImage(hInst, MAKEINTRESOURCE(IDC_PANDOWNCUR), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE);

    std::unique_ptr<CMainWindow> mainWindow(new CMainWindow(hResource));
    mainWindow->SetRegistryPath(_T("Software\\TortoiseGit\\TortoiseIDiffWindowPos"));
    std::wstring leftfile = parser.HasVal(_T("left")) ? parser.GetVal(_T("left")) : _T("");
    std::wstring rightfile = parser.HasVal(_T("right")) ? parser.GetVal(_T("right")) : _T("");
    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(_T("lefttitle")) ? parser.GetVal(_T("lefttitle")) : _T(""));
    mainWindow->SetRight(rightfile.c_str(), parser.HasVal(_T("righttitle")) ? parser.GetVal(_T("righttitle")) : _T(""));
    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") ? (HWND)parser.GetLongLongVal(L"resolvemsghwnd") : 0;
    mainWindow->resolveMsgWParam = parser.HasVal(L"resolvemsgwparam") ? (WPARAM)parser.GetLongLongVal(L"resolvemsgwparam") : 0;
    mainWindow->resolveMsgLParam = parser.HasVal(L"resolvemsglparam") ? (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(_T("overlay")))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_OVERLAPIMAGES, 0);
        }
        if (parser.HasKey(_T("fit")))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEHEIGHTS, 0);
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEWIDTHS, 0);
        }
        if (parser.HasKey(_T("fitwidth")))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEWIDTHS, 0);
        }
        if (parser.HasKey(_T("fitheight")))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_FITIMAGEHEIGHTS, 0);
        }
        if (parser.HasKey(_T("showinfo")))
        {
            PostMessage(*mainWindow, WM_COMMAND, ID_VIEW_IMAGEINFO, 0);
        }
        // Main message loop:
        while (GetMessage(&msg, NULL, 0, 0))
        {
            if (!TranslateAccelerator(*mainWindow, hAccelTable, &msg))
            {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
        return (int) msg.wParam;
    }
    langDLL.Close();
    DestroyCursor(curHand);
    DestroyCursor(curHandDown);
    CoUninitialize();
    git_libgit2_shutdown();
    return 1;
}
void AudioStreamer::Update()
{
	// this method must run on separate thread!!!

	XAUDIO2_VOICE_STATE state;

	Sound*		s;
	soundlist	canstream;
	int			stream;
	long		readbytes;
	long		totalread;
	long		toread;
	bool		play;

	// must be called in every thread
	CoInitializeEx(0, COINIT_MULTITHREADED);

	while( running )
	{
		// collect sound that need more data
		canstream.clear();

		soundguard.Lock(); // reading 'sound'

		for( soundlist::iterator it = sound.begin(); it != sound.end(); ++it )
		{
			s = (*it);

			if( s->isstream )
			{
				if( (s->readsize < s->totalsize) && (s->freebuffers > 0) )
					canstream.push_back(s);
			}
		}

		soundguard.Unlock();

		// update collected sound
		if( canstream.size() > 0 )
		{
			for( soundlist::iterator it = canstream.begin(); it != canstream.end(); ++it )
			{
				soundguard.Lock(); // watch out for 'Destroy()'

				// might have exited
				if( !running )
					return;

				s = (*it);

				totalread = 0;
				readbytes = 0;
				toread = min(STREAMING_BUFFER_SIZE, s->totalsize - s->readsize);

				// fill a free buffer with data
				do
				{
					readbytes = ov_read(&s->oggfile, s->data[s->currentbuffer] + totalread, toread - totalread, 0, 2, 1, &stream);
					totalread += readbytes;
				}
				while( readbytes > 0 && totalread < toread );

				s->readsize += totalread;
				SND_DEBUG("buffer " << s->currentbuffer << " loaded");

				// pull buffer to queue if possible
				// otherwise the sound is gonna pull it
				s->voice->GetState(&state);

				if( state.BuffersQueued < MAX_BUFFER_COUNT - 1 )
				{
					s->PullBuffer(s->currentbuffer);
					SND_DEBUG("buffer " << s->currentbuffer << " pulled (instantly)");
					
					// lock it so noone can modify s->playing
					s->playguard.Lock();
					{
						s->canplay = true;
						play = (s->playrequest && !s->playing);
					}
					s->playguard.Unlock();

					if( play )
						s->Play();
				}
				
				s->currentbuffer = (s->currentbuffer + 1) % MAX_BUFFER_COUNT;
				--s->freebuffers;

				soundguard.Unlock();
			}
		}
		else
			Sleep(100);
	}

	CoUninitialize();
}
Ejemplo n.º 19
0
JNIEXPORT void JNICALL Java_com4j_Native_coUninitialize(
	JNIEnv* env, jclass _) {

	CoUninitialize();
}
Ejemplo n.º 20
0
/* _al_win_thread_exit:
 *  Shuts down COM interface for the calling thread.
 */
void _al_win_thread_exit(void)
{
   CoUninitialize();
}
Ejemplo n.º 21
0
//============================================================================================
//   MAIN
//============================================================================================
extern "C" int WINAPI WinMain(  HINSTANCE hInstance,      // handle to current instance
                                HINSTANCE hPrevInstance,  // handle to previous instance
                                LPSTR lpCmdLine,          // command line
                                int nCmdShow   ){         // show state

  TCHAR szTokens[] = "-/";
  int iRes;
  HWND hDlgWnd;
  UINT uiTimerID; 
  HRESULT hr;

  // Parse the command line for options
  LPCTSTR lpszToken = FindOneOf(lpCmdLine, szTokens);
  while (lpszToken != NULL) {
    if (lstrcmpi(lpszToken, "UnregServer")==0) {
      iRes = g_UnregisterCOM();
      if( iRes != 0 ) { 
        MessageBox( NULL, "Error: Can't unregister server. g_UnregisterCOM() failed.", x_szTitle, MB_OK);
      }
      else {
        MessageBox( NULL, "Success: the server is unregistered.", x_szTitle, MB_OK);
      }
      return iRes;
    }
    if (lstrcmpi(lpszToken, "RegServer")==0) {
      iRes = g_RegisterCOM();
      if( iRes != 0 ) { 
        MessageBox( NULL, "Error: Can't register server. g_RegisterCOM() failed.", x_szTitle, MB_OK);
      }
      else {
        MessageBox( NULL, "Success: the server is registered.", x_szTitle, MB_OK);
      }
      return iRes;
    }
    lpszToken = FindOneOf(lpszToken, szTokens);
  } // while there are tokens


  
//-------  Windows staff starts here
  CP_printfCreate(x_szTitle); // create console window

  hDlgWnd=CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MAIN_DIALOG),
                      NULL, x_DialogProc); 
  SetWindowText(hDlgWnd, x_szTitle);
  SendMessage(hDlgWnd, WM_SETICON, ICON_BIG, 
              (LPARAM)LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON_APPL)));
  SendMessage(hDlgWnd, WM_SETICON, ICON_SMALL, 
             (LPARAM)LoadImage(hInstance, MAKEINTRESOURCE(IDI_ICON_APPL), IMAGE_ICON, 16, 16, 0));
  ShowWindow(hDlgWnd, SW_SHOW); 
  CP_printf(g_szVersion);
  CP_printf("\n\n");
  
  uiTimerID = SetTimer( hDlgWnd,  TIMER_ID,  TIMER_PERIOD_MS,  NULL ); 
 
  if ( uiTimerID == 0){ 
    CP_printf("Error: could not create timer!"); // don't exit we are still functional
  } 

  // Init COM using apartment-threaded model
  hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);   
  if( hr != S_OK) { 
    MessageBox( NULL, "Error in CoInitializeEx()", x_szTitle, MB_OK);
    return 1;
  }

  iRes = g_Init_EyeTrack( );
  if( iRes != 0 ) { 
    MessageBox( NULL, "Error: g_Init_EyeTrack() failed.", x_szTitle, MB_OK);
    return 1;
  }
  // Message loop
  MSG msg;
  while (GetMessage(&msg, 0, 0, 0)) {
    // Process dialog messages in IsDialogMessage() pass others to translate/dispatch
    if(!IsDialogMessage(hDlgWnd,&msg)){
      TranslateMessage(&msg);
      DispatchMessage(&msg); 
    }
  }  // end of message loop
  KillTimer( hDlgWnd, TIMER_ID);
	CoUninitialize();

  return 0;
}
Ejemplo n.º 22
0
static void v4w_uninit(MSFilter *f){
	V4wState *s=(V4wState*)f->data;
	int idx;
	flushq(&s->rq,0);
	ms_mutex_destroy(&s->mutex);
	for (idx=0;idx<10;idx++)
	{
		if (s->mire[idx]==NULL)
			break;
		freemsg(s->mire[idx]);
	}
	if (s->rotregvalue>0){
		HRESULT hr = s->m_pControl->Stop();
		if(FAILED(hr))
		{
			ms_message("v4w: could not stop graph");
		}

		if (s->m_pGraph!=NULL)
		{
			if (s->m_pNullRenderer!=NULL)
				s->m_pGraph->RemoveFilter(s->m_pNullRenderer);
			if (s->m_pIDXFilter!=NULL)
				s->m_pGraph->RemoveFilter(s->m_pIDXFilter);
			if (s->m_pDeviceFilter!=NULL)
				s->m_pGraph->RemoveFilter(s->m_pDeviceFilter);
		}

		if (s->m_pNullRenderer)
			s->m_pNullRenderer->Release();
		if (s->m_pIDXFilter)
			s->m_pIDXFilter->Release();
		if (s->m_pDeviceFilter)
			s->m_pDeviceFilter->Release();

		if (s->m_pBuilder)
			s->m_pBuilder->Release();
		if (s->m_pControl)
			s->m_pControl->Release();
		if (s->m_pGraph)
			s->m_pGraph->Release();

		if (s->m_pDXFilter!=NULL)
			s->m_pDXFilter->Release();

		s->m_pNullRenderer=NULL;
		s->m_pIDXFilter=NULL;
		s->m_pDeviceFilter=NULL;
		s->m_pBuilder=NULL;
		s->m_pControl=NULL;
		s->m_pGraph=NULL;
		s->m_pDXFilter=NULL;

		CoUninitialize();
		s_callback = NULL;
		flushq(&s->rq,0);
		ms_message("v4w: graph destroyed");
		s->rotregvalue=0;
	}
	ms_free(s);
}
Ejemplo n.º 23
0
Archivo: main.cpp Proyecto: mojjia/blog
 ~CoUninitializeOnExit() {
     CoUninitialize();
 }
Ejemplo n.º 24
0
unsigned int __stdcall CreateBrokerThreadEntry(void *data)
{
TRY_CATCH

	CoInitialize(0);

	SBrokerThreadEntryData* inData = reinterpret_cast<SBrokerThreadEntryData*>(data);
	SStartBroker *startBroker = reinterpret_cast<SStartBroker*>(inData->buf);
	if (NULL == startBroker->buf || 0 == startBroker->bufSize)
		throw MCException("NULL == startBroker->buf || 0 == startBroker->bufSize");

	CComPtr<IDispatch> broker;
	HRESULT hr;
	if((hr=broker.CoCreateInstance(L"Broker.CoBroker",NULL,CLSCTX_LOCAL_SERVER))!=S_OK)
		throw CExceptionBase(__LINE__,_T(__FILE__),_T(__DATE__),tstring(_T("CoBroker creation failed")),hr);

	CScopedTracker<HGLOBAL> globalMem;	
	globalMem.reset(GlobalAlloc(GMEM_MOVEABLE, startBroker->bufSize), GlobalFree);
	if (NULL == globalMem)
		throw MCException_Win("Failed to GlobalAlloc");

	CComPtr<IStream> stream;
	hr = CreateStreamOnHGlobal(globalMem, FALSE, &stream);
	if (S_OK != hr)
		throw MCException_Win(Format(_T("Failed to GlobalAlloc; result = %X"),hr));

	ULARGE_INTEGER size;
	size.QuadPart = startBroker->bufSize;
	hr = stream->SetSize(size);
	if (S_OK != hr)
		throw MCException_Win(Format(_T("Failed to stream->SetSize; result = %X"),hr));

	hr = CoMarshalInterface(stream, IID_IDispatch, broker, MSHCTX_LOCAL, NULL, MSHLFLAGS_NORMAL);
	if (S_OK != hr)
		throw MCException_Win(Format(_T("Failed to CoMarshalInterface; result = %X"),hr));

	ULARGE_INTEGER uLi;
	LARGE_INTEGER li;
	li.QuadPart = 0;

	/// Writing stream to client process memory
	stream->Seek(li, STREAM_SEEK_SET, NULL);
	boost::scoped_array<char> localBuf;
	ULONG readCount;
	localBuf.reset(new char[startBroker->bufSize]);
	hr = stream->Read(localBuf.get(), startBroker->bufSize, &readCount);
	if (S_OK != hr)
		throw MCException_Win(Format(_T("stream->Read; result = %X"),hr));

	/// Writing stream date into client process memory
	ULONG writtenCount;
	if (FALSE == WriteProcessMemory(inData->clientProcess, startBroker->buf, localBuf.get(), readCount, &writtenCount))
		throw MCException_Win("Failed to WriteProcessMemory ");

	CoUninitialize();

	Log.Add(_MESSAGE_,_T("Broker created and marshaled to BrokerProxy process"));

	return TRUE;

CATCH_LOG()

	CoUninitialize();
	return FALSE;
}
Ejemplo n.º 25
0
static int VBoxNetFltUninstall()
{
    INetCfg *pnc;
    LPWSTR lpszLockedBy = NULL;
    int r;

    VBoxNetCfgWinSetLogging(winNetCfgLogger);

    HRESULT hr = CoInitialize(NULL);
    if(hr == S_OK)
    {
        int i = 0;
        do
        {
            hr = VBoxNetCfgWinQueryINetCfg(&pnc, TRUE, VBOX_NETCFG_APP_NAME, 10000, &lpszLockedBy);
            if(hr == S_OK)
            {
                hr = VBoxNetCfgWinNetFltUninstall(pnc);
                if(hr != S_OK)
                {
                    wprintf(L"error uninstalling VBoxNetFlt (0x%x)\n", hr);
                    r = 1;
                }
                else
                {
                    wprintf(L"uninstalled successfully\n");
                    r = 0;
                }

                VBoxNetCfgWinReleaseINetCfg(pnc, TRUE);
                break;
            }
            else if(hr == NETCFG_E_NO_WRITE_LOCK && lpszLockedBy)
            {
                if(i < VBOX_NETFLT_RETRIES && !wcscmp(lpszLockedBy, L"6to4svc.dll"))
                {
                    wprintf(L"6to4svc.dll is holding the lock, retrying %d out of %d\n", ++i, VBOX_NETFLT_RETRIES);
                    CoTaskMemFree(lpszLockedBy);
                }
                else
                {
                    wprintf(L"Error: write lock is owned by another application (%s), close the application and retry uninstalling\n", lpszLockedBy);
                    r = 1;
                    CoTaskMemFree(lpszLockedBy);
                    break;
                }
            }
            else
            {
                wprintf(L"Error getting the INetCfg interface (0x%x)\n", hr);
                r = 1;
                break;
            }
        } while(true);

        CoUninitialize();
    }
    else
    {
        wprintf(L"Error initializing COM (0x%x)\n", hr);
        r = 1;
    }

    VBoxNetCfgWinSetLogging(NULL);

    return r;
}
Ejemplo n.º 26
0
//-----------------------------------------------------------------------------
// Enum each PNP device using WMI and check each device ID to see if it contains 
// "IG_" (ex. "VID_045E&PID_028E&IG_00").  If it does, then it's an XInput device
// Unfortunately this information can not be found by just using DirectInput 
//-----------------------------------------------------------------------------
BOOL isXInputDevice(const GUID* pGuidProductFromDirectInput)
{
	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;

	// CoInit if needed
	hr = CoInitialize(NULL);
	bool bCleanupCOM = SUCCEEDED(hr);

	// Create WMI
	hr = CoCreateInstance(__uuidof(WbemLocator),
		NULL,
		CLSCTX_INPROC_SERVER,
		__uuidof(IWbemLocator),
		(LPVOID*)&pIWbemLocator);
	if (FAILED(hr) || pIWbemLocator == NULL)
		goto LCleanup;

	bstrNamespace = SysAllocString(L"\\\\.\\root\\cimv2"); if (bstrNamespace == NULL) goto LCleanup;
	bstrClassName = SysAllocString(L"Win32_PNPEntity");   if (bstrClassName == NULL) goto LCleanup;
	bstrDeviceID = SysAllocString(L"DeviceID");          if (bstrDeviceID == NULL)  goto LCleanup;

	// Connect to WMI 
	hr = pIWbemLocator->ConnectServer(bstrNamespace, NULL, NULL, 0L,
		0L, NULL, NULL, &pIWbemServices);
	if (FAILED(hr) || pIWbemServices == NULL)
		goto LCleanup;

	// Switch security level to IMPERSONATE. 
	CoSetProxyBlanket(pIWbemServices, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL,
		RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);

	hr = pIWbemServices->CreateInstanceEnum(bstrClassName, 0, NULL, &pEnumDevices);
	if (FAILED(hr) || pEnumDevices == NULL)
		goto LCleanup;

	// Loop over all devices
	for (;; )
	{
		// Get 20 at a time
		hr = pEnumDevices->Next(10000, 20, pDevices, &uReturned);
		if (FAILED(hr))
			goto LCleanup;
		if (uReturned == 0)
			break;

		for (iDevice = 0; iDevice<uReturned; iDevice++)
		{
			// For each device, get its device ID
			hr = pDevices[iDevice]->Get(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 = wcsstr(var.bstrVal, L"VID_");
					if (strVid && swscanf_s(strVid, L"VID_%4X", &dwVid) != 1)
						dwVid = 0;
					WCHAR* strPid = wcsstr(var.bstrVal, L"PID_");
					if (strPid && swscanf_s(strPid, L"PID_%4X", &dwPid) != 1)
						dwPid = 0;

					// Compare the VID/PID to the DInput device
					DWORD dwVidPid = MAKELONG(dwVid, dwPid);
					if (dwVidPid == pGuidProductFromDirectInput->Data1)
					{
						bIsXinputDevice = true;
						goto LCleanup;
					}
				}
			}
			SAFE_RELEASE(pDevices[iDevice]);
		}
	}

LCleanup:
	if (bstrNamespace)
		SysFreeString(bstrNamespace);
	if (bstrDeviceID)
		SysFreeString(bstrDeviceID);
	if (bstrClassName)
		SysFreeString(bstrClassName);
	for (iDevice = 0; iDevice<20; iDevice++)
		SAFE_RELEASE(pDevices[iDevice]);
	SAFE_RELEASE(pEnumDevices);
	SAFE_RELEASE(pIWbemLocator);
	SAFE_RELEASE(pIWbemServices);

	if (bCleanupCOM)
		CoUninitialize();

	return bIsXinputDevice;
}
Ejemplo n.º 27
0
int PASCAL WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{

	MSG
		msg;

	int
		terminated;

	//
	// Initialise DCOM
	//

	CoInitializeEx ( NULL, COINIT_MULTITHREADED );

	//
	// Install our own exception handler!
	//

	initialise_application_exception_handler ();

	//
	// Set the current directory to where the executable is located
	//

	set_application_current_directory ();

	//
	// Unlink the debug.log file here.
	//

	unlink ( "debug.log" );

	system_thread_id = GetCurrentThreadId ();

	application_debug_fatal = FALSE;

	application_active = TRUE;

	//
	// Initialise the memory statistics
	//

	initialise_memory_totals ();

	if ( !initialise_windows ( hInstance, nCmdShow ) )
	{

		deinitialise_windows ();

		return ( FALSE );
	}

	application_instance = hInstance;

   number_user_message_functions = 0;

	number_system_message_functions = 0;

	number_pre_activate_message_functions = 0;

	number_post_activate_message_functions = 0;

	register_system_message_function ( WM_USER, call_user_function_routine );

	register_system_message_function ( WM_SETCURSOR, windows_cursor_routine );

	register_system_message_function ( WM_ACTIVATE, call_pre_activate_function_routine );

	register_system_message_function ( WM_ACTIVATEAPP, call_post_activate_function_routine );

	register_system_message_function ( WM_PAINT, windows_paint_routine  );

	register_system_message_function ( WM_MOVE, windows_sizemove_routine );

	register_system_message_function ( WM_SYSCOMMAND, windows_systemcommand_routine );

	register_system_message_function ( WM_CLOSE, windows_close_request_routine );

	initialise_cdrom_system ();

	initialise_system_thread_calling_function ();

	exit_message_id = get_unique_message_id ();

	register_user_message_function ( exit_message_id, windows_exit_routine );

	//
	// The graphics / 3d / 2d systems need the maths fpu to round to zero
	//

	set_fpu_rounding_mode_zero ();

	set_fpu_exceptions ();

	initialise_event_system ();

	initialise_timers_system ();

	initialise_file_system ();

	main_command_line = lpCmdLine;

	terminated = FALSE;

	application_thread_handle = CreateThread
	(
		(LPSECURITY_ATTRIBUTES) NULL,
		0,
		(LPTHREAD_START_ROUTINE) start_application,
		0,
		0,
		&application_thread_id
	);

	SetThreadPriority ( GetCurrentThread (), THREAD_PRIORITY_ABOVE_NORMAL );

	while ( !terminated )
	{

		DWORD
			message_index,
			object_count;

		HANDLE
			handle_array[2];

		object_count = 0;

		if ( keyboard_handle )
		{

			handle_array[object_count] = keyboard_handle;

			object_count++;
		}

		if ( mouse_handle )
		{

			handle_array[object_count] = mouse_handle;

			object_count++;
		}

		message_index = MsgWaitForMultipleObjects( object_count, handle_array, 0, INFINITE, QS_ALLINPUT);
//		message_index = MsgWaitForMultipleObjects( object_count, handle_array, 0, 100, QS_ALLINPUT);

		if ( ( message_index >= object_count ) || ( message_index == WAIT_TIMEOUT ) )
		{

			//
			// Default windows messaging
			//

			while ( PeekMessage ( &msg, NULL, 0, 0, PM_REMOVE ) )
			{

				if ( msg.message == WM_QUIT )
				{

					terminated = TRUE;
				}
				else
				{

					TranslateMessage(&msg);

					DispatchMessage(&msg);
				}
			}
		}
		else
		{

			if ( handle_array[message_index] == keyboard_handle )
			{

				generate_keyboard_events ();
			}
			else if ( handle_array[message_index] == mouse_handle )
			{

				generate_mouse_events ();
			}
		}
	}

	CoUninitialize ();

	return ( msg.wParam );
}
Ejemplo n.º 28
0
	void TearDown()
	{
		CoUninitialize();
	}
Ejemplo n.º 29
0
void CTortoiseProcApp::CheckUpgrade()
{
	CRegString regVersion = CRegString(_T("Software\\TortoiseGit\\CurrentVersion"));
	CString sVersion = regVersion;
	if (sVersion.Compare(_T(STRPRODUCTVER))==0)
		return;
	// we're starting the first time with a new version!

	LONG lVersion = 0;
	int pos = sVersion.Find('.');
	if (pos > 0)
	{
		lVersion = (_ttol(sVersion.Left(pos))<<24);
		lVersion |= (_ttol(sVersion.Mid(pos+1))<<16);
		pos = sVersion.Find('.', pos+1);
		lVersion |= (_ttol(sVersion.Mid(pos+1))<<8);
	}
	else
	{
		pos = sVersion.Find(',');
		if (pos > 0)
		{
			lVersion = (_ttol(sVersion.Left(pos))<<24);
			lVersion |= (_ttol(sVersion.Mid(pos+1))<<16);
			pos = sVersion.Find(',', pos+1);
			lVersion |= (_ttol(sVersion.Mid(pos+1))<<8);
		}
	}

	if (lVersion <= 0x01080401)
	{
		if (CRegStdDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\SendMail\\UseMAPI"), FALSE) == TRUE)
			CRegStdDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\SendMail\\DeliveryType")) = 1;
		CRegStdDWORD(_T("Software\\TortoiseGit\\TortoiseProc\\SendMail\\UseMAPI")).removeValue();
	}

	if (lVersion <= 0x01080202)
	{
		CSoundUtils::RegisterTGitSounds();
		// upgrade to 1.8.3: force recreation of all diff scripts.
		CAppUtils::SetupDiffScripts(true, CString());
	}

	if (lVersion <= 0x01080100)
	{
		if (CRegStdDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE) == FALSE)
			CRegStdDWORD(_T("Software\\TortoiseGit\\LogOrderBy")) = 0;

		// smoothly migrate broken msysgit path settings
		CString oldmsysGitSetting = CRegString(REG_MSYSGIT_PATH);
		oldmsysGitSetting.TrimRight(_T("\\"));
		CString right = oldmsysGitSetting.Right(4);
		if (oldmsysGitSetting.GetLength() > 4 && oldmsysGitSetting.Right(4) == _T("\\cmd"))
		{
			CString newPath = oldmsysGitSetting.Mid(0, oldmsysGitSetting.GetLength() - 3) + _T("bin");
			if (PathFileExists(newPath + _T("\\git.exe")))
			{
				CRegString(REG_MSYSGIT_PATH) = newPath;
				g_Git.m_bInitialized = FALSE;
				g_Git.CheckMsysGitDir();
			}
		}
	}

	if (lVersion <= 0x01040000)
	{
		CRegStdDWORD(_T("Software\\TortoiseGit\\OwnerdrawnMenus")).removeValue();
	}

	if (lVersion <= 0x01070600)
	{
		CoInitialize(NULL);
		EnsureGitLibrary();
		CoUninitialize();
		CRegStdDWORD(_T("Software\\TortoiseGit\\ConvertBase")).removeValue();
		CRegStdDWORD(_T("Software\\TortoiseGit\\DiffProps")).removeValue();
		if (CRegStdDWORD(_T("Software\\TortoiseGit\\CheckNewer"), TRUE) == FALSE)
			CRegStdDWORD(_T("Software\\TortoiseGit\\VersionCheck")) = FALSE;
	}

	if (lVersion <= 0x01070E00)
	{
		CRegStdDWORD(_T("Software\\TortoiseGit\\CheckNewer")).removeValue();
	}
	CAppUtils::SetupDiffScripts(false, CString());

	// set the current version so we don't come here again until the next update!
	regVersion = _T(STRPRODUCTVER);
}
Ejemplo n.º 30
0
//============================================================================================
//   MAIN
//============================================================================================
extern "C" int WINAPI WinMain(  HINSTANCE hInstance,      // handle to current instance
                                HINSTANCE hPrevInstance,  // handle to previous instance
                                LPSTR lpCmdLine,          // command line
                                int nCmdShow   ){         // show state

  HANDLE hMutex;
  TCHAR szTokens[] = "-/";
  LPCTSTR lpszToken;
  int iRes;
  HRESULT hRes;

  x_hInstance = hInstance;

  // Check for another instance
  hMutex = OpenMutex( SYNCHRONIZE,  // requested access (lowest possible)
                      FALSE,  // allow inheritance (does not matter)
                      x_szMutexName);  // unique name

  if(hMutex){
    MessageBox( NULL, "Cannot start the application because another instance is already running.\n", 
                x_szTitle, MB_OK | MB_ICONERROR );
    return 1;
  }

  hMutex = CreateMutex( NULL,  // default security
                        TRUE,  // obtain ownership
                        x_szMutexName);  // unique name
  if(!hMutex){
    MessageBox( NULL, "Cannot create application mutex.\n", 
                x_szTitle, MB_OK | MB_ICONERROR );
    return 1;
  }


  // Parse the command line for options
  lpszToken = FindOneOf(lpCmdLine, szTokens);
  while (lpszToken != NULL) {
    if (lstrcmpi(lpszToken, "UnregServer")==0) {
      iRes = g_UnregisterCOM();
      if( iRes != 0 ) { 
        MessageBox( NULL, "Error: Can't unregister server. g_UnregisterCOM() failed.", x_szTitle, MB_OK);
      }
      else {
        MessageBox( NULL, "Success: the server is unregistered.", x_szTitle, MB_OK);
      }
      return iRes;
    }
    if (lstrcmpi(lpszToken, "RegServer")==0) {
      iRes = g_RegisterCOM();
      if( iRes != 0 ) { 
        MessageBox( NULL, "Error: Can't register server. g_RegisterCOM() failed.", x_szTitle, MB_OK);
      }
      else {
        MessageBox( NULL, "Success: the server is registered.", x_szTitle, MB_OK);
      }
      return iRes;
    }
    lpszToken = FindOneOf(lpszToken, szTokens);
  } // while there are tokens

//-------  Regular run starts here
  // Init COM using single-threaded model
  hRes = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); 
  if( hRes != S_OK) { 
    MessageBox( NULL, "Error in CoInitializeEx()", x_szTitle, MB_OK);
    return 1;
  }
  
  CP_printfCreate(x_szTitle); // create console window
  CP_printf(g_szVersion);
  CP_printf("\n\n");
  CP_printfHide(); // hide console window

  //-------  Windows main loop is here
  DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN_DIALOG), NULL, x_DialogProc); 

  CP_printfDestroy();
	CoUninitialize();

  return 0;
}