예제 #1
0
int GoProcessing(const tagCMDL & cmdl)
{
	int mode = cmdl.mode;

	CreateDirectory(cmdl.temppath, NULL);

	wchar_t tempfile[MAX_PATH];
	if( lstrlen(cmdl.temppath) == 0 )
	{
		// кодируем в файл по умолчанию
		StringCchCopy(tempfile, MAX_PATH, cmdl.outputfilename);
	}else
	{
		StringCchCopy(tempfile, MAX_PATH, cmdl.temppath);
		if( tempfile[ lstrlen(tempfile) -1 ] != L'\\')
			StringCchCat(tempfile, MAX_PATH, L"\\");
		StringCchCat(tempfile, MAX_PATH, PathFindFileName(cmdl.outputfilename));
	}


	HWND fwwnd = FindWindow(wndclassnameW, NULL);
	if(fwwnd == NULL) return 4;

	int pos = -1;
	while( pos < 0 )
	{
		if( !isProcessExist() ) // проверяем мьютекс
			return 0; // преждевременный выход
		pos = (int)SendMessage(fwwnd, MES_ONNEWTHREAD, 0, 0);
		if( pos >= 0 ) break;
		Sleep(200);
	}

	//////////////////////////////////////////////////////////////////////////
	// название файла
	if( !SendFileName(fwwnd, cmdl.outputfilename, pos) )
		return 0; // выход, лажа.

	//////////////////////////////////////////////////////////////////////////
	// читаем файл из stdin и создаём временный wav-файл
	if( !ReadAndCreateFile(tempfile) )
		return 5;
	DWORD len = CorrectHeader(tempfile);
	//////////////////////////////////////////////////////////////////////////
	// сообщаем длинну трэка: sec * 4 * 44100
	if( !MySendMessage(fwwnd, MES_SENDLENGTH, pos, len) )
	{
		DeleteFile(tempfile);
		return 0;
	}
	if( len )
	{
		UINT newpriority = (UINT)SendMessage(fwwnd, MES_GETPRIORITY, 0, 0);
		SetPriorityClass(GetCurrentProcess(), newpriority );

		if( !RunProcessing(tempfile, mode, fwwnd, pos) )
		{
			DeleteFile(tempfile);
			return 0; // пытаемся безболезненно свалить :D
		}
	}
	DeleteFile(tempfile);
	if( !TrimFile(cmdl.outputfilename, pos) )
		return 6;

	return 0;
}
예제 #2
0
void DirectoryListingService::updateEntries() {
	ScopeLock lock(_mutex);

	// stat directory for modification date
	struct stat dirStat;
	if (stat(_dir.c_str(), &dirStat) != 0) {
		UM_LOG_ERR("Error with stat on directory '%s': %s", _dir.c_str(), strerror(errno));
		return;
	}

	if ((unsigned)dirStat.st_mtime >= (unsigned)_lastChecked) {
		// there are changes in the directory
		set<string> currEntries;

#ifndef WIN32
		DIR *dp;
		dp = opendir(_dir.c_str());
		if (dp == NULL) {
			UM_LOG_ERR("Error opening directory '%s': %s", _dir.c_str(), strerror(errno));
			return;
		}
		// iterate all entries and see what changed
		struct dirent* entry;
		while((entry = readdir(dp))) {
			string dname = entry->d_name;
#else
		WIN32_FIND_DATA ffd;
		HANDLE hFind = INVALID_HANDLE_VALUE;
		TCHAR szDir[MAX_PATH];
		StringCchCopy(szDir, MAX_PATH, _dir.c_str());
		StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

		hFind = FindFirstFile(szDir, &ffd);
		do {
			string dname = ffd.cFileName;
#endif

			// see if the file was changed
			char* filename;
			asprintf(&filename, "%s/%s", _dir.c_str(), dname.c_str());

			struct stat fileStat;
			if (stat(filename, &fileStat) != 0) {
				UM_LOG_ERR("Error with stat on directory entry '%s': %s", filename, strerror(errno));
				free(filename);
				continue;
			}

			if (fileStat.st_mode & S_IFDIR) {
				// ignore directories
				free(filename);
				continue;
			}

			// are we interested in such a file?
			if (!filter(dname)) {
				free(filename);
				continue;
			}
			currEntries.insert(dname);

			if (_knownEntries.find(dname) != _knownEntries.end()) {
				// we have seen this entry before
				struct stat oldStat = _knownEntries[dname];
				if (oldStat.st_mtime < fileStat.st_mtime) {
					notifyModifiedFile(dname, fileStat);
				}
			} else {
				// we have not yet seen this entry
				notifyNewFile(dname, fileStat);
			}

			free(filename);
			_knownEntries[dname] = fileStat; // gets copied on insertion
#ifndef WIN32
		}
		closedir(dp);
#else
		}
		while (FindNextFile(hFind, &ffd) != 0);
		FindClose(hFind);
#endif
		// are there any known entries we have not seen this time around?
		map<string, struct stat>::iterator fileIter = _knownEntries.begin();
		while(fileIter != _knownEntries.end()) {
			if (currEntries.find(fileIter->first) == currEntries.end()) {
				// we used to know this file
				notifyRemovedFile(fileIter->first, fileIter->second);
				_knownEntries.erase(fileIter->first);
			}
			fileIter++;
		}
		// remember when we last checked the directory for modifications
#ifndef WIN32
		time(&_lastChecked);
#else
		// TODO: this will fail with subsecond updates to the directory
		_lastChecked = dirStat.st_mtime + 1;
#endif
	}
예제 #3
0
/*!
	クリップボードのデータをいただく・同じモノが、DocInsDelCtrl.cpp にある
	@param[in]	pVoid	特になし
	@return		確保した文字列・mallocしてるので、函数呼んだ方でfree忘れないように
*/
LPTSTR ClipboardDataGet( LPVOID pVoid )
{
	LPTSTR	ptString = NULL, ptClipTxt;
	LPSTR	pcStr, pcClipTp;	//	変換用臨時
	DWORD	cbSize;
	UINT	dEnumFmt;
	INT		ixCount, iC;
	HANDLE	hClipData;

	//	クリップボードの中身をチェキ・どっちにしてもユニコードテキストフラグはある
	if( IsClipboardFormatAvailable( CF_UNICODETEXT ) )
	{
		OpenClipboard( NULL );	//	クリップボードをオーポンする
		//	開けっ放しだと他のアプリに迷惑なのですぐ閉めるように

		dEnumFmt = 0;	//	初期値は0
		ixCount = CountClipboardFormats(  );
		for( iC = 0; ixCount > iC; iC++ )
		{	//	順番に列挙して、先にヒットしたフォーマットで扱う
			dEnumFmt = EnumClipboardFormats( dEnumFmt );
			if( CF_UNICODETEXT == dEnumFmt || CF_TEXT == dEnumFmt ){	break;	}
		}
		if( 0 == dEnumFmt ){	return NULL;	}
		//	それ以上列挙が無いか、函数失敗なら0になる

		//	クリップボードのデータをゲッツ!
		//	ハンドルのオーナーはクリップボードなので、こちらからは操作しないように
		//	中身の変更などもってのほかである
		hClipData = GetClipboardData( dEnumFmt );

		if( CF_UNICODETEXT == dEnumFmt )
		{
			//	取得データを処理。TEXTなら、ハンドルはグローバルメモリハンドル
			//	新たにコピーされたらハンドルは無効になるので、中身をコピーせよ
			ptClipTxt = (LPTSTR)GlobalLock( hClipData );
			cbSize    = GlobalSize( (HGLOBAL)hClipData );
			//	確保出来るのはバイトサイズ・テキストだと末尾のNULLターミネータ含む

			if( 0 < cbSize )
			{
				ptString = (LPTSTR)malloc( cbSize );
				StringCchCopy( ptString, (cbSize / 2), ptClipTxt );
			}
		}
		else	//	非ユニコードが優先されている場合
		{
			pcClipTp = (LPSTR)GlobalLock( hClipData );
			cbSize   = GlobalSize( (HGLOBAL)hClipData );

			if( 0 < cbSize )
			{
				pcStr = (LPSTR)malloc( cbSize );
				StringCchCopyA( pcStr, cbSize, pcClipTp );

				ptString = SjisDecodeAlloc( pcStr );	//	SJISの内容をユニコードにする
				free( pcStr );
			}
		}


		//	使い終わったら閉じておく
		GlobalUnlock( hClipData );
		CloseClipboard(  );
	}

	return ptString;
}
예제 #4
0
XN_C_API XnStatus xnUSBOpenEndPoint(XN_USB_DEV_HANDLE pDevHandle, XnUInt16 nEndPointID, XnUSBEndPointType nEPType, XnUSBDirectionType nDirType, XN_USB_EP_HANDLE* pEPHandlePtr)
{
	// Local variables
	XnBool bResult = TRUE;
	XnStatus nRetVal = XN_STATUS_OK;
	XnInt32 nRetBytes = 0;
	XnChar pConfigDescBuf[MAX_CONFIG_DESC_SIZE];
	XnChar* pBuf = NULL;
	PUSB_CONFIGURATION_DESCRIPTOR pUSBConfigDesc = NULL;
	PUSB_INTERFACE_DESCRIPTOR pUSBInterfaceDesc = NULL;
	PUSB_ENDPOINT_DESCRIPTOR pUSBEndPointDesc = NULL;
	XnUInt32 nIFIdx = 0;
	XnUInt32 nEPIdx = 0;
	XnUInt32 nUBBEPType = 0;
	XN_USB_EP_HANDLE pEPHandle = NULL;	
	XnChar cpPipeID[3];
	XnUInt32 nCurrIF = 0;

	// Validate xnUSB
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_USB_PDEV_HANDLE(pDevHandle);

	// Validate the input/output pointers
	XN_VALIDATE_OUTPUT_PTR(pEPHandlePtr);

	// Allocate a new xnUSB EP handle
	XN_VALIDATE_ALIGNED_CALLOC(*pEPHandlePtr, xnUSBEPHandle, 1, XN_DEFAULT_MEM_ALIGN);
	pEPHandle = *pEPHandlePtr;

	// Read the config descriptor
	bResult = DeviceIoControl(pDevHandle->hUSBDevHandle, IOCTL_PSDRV_GET_CONFIG_DESCRIPTOR, pConfigDescBuf, sizeof(pConfigDescBuf), pConfigDescBuf, sizeof(pConfigDescBuf), (PULONG)&nRetBytes, NULL);
	if (bResult)
	{
		pBuf = pConfigDescBuf;

		pUSBConfigDesc = (PUSB_CONFIGURATION_DESCRIPTOR)pBuf;

		pBuf += pUSBConfigDesc->bLength;

		// Scan all the interfaces
		do {
			pUSBInterfaceDesc = (PUSB_INTERFACE_DESCRIPTOR)pBuf;

			pBuf += pUSBInterfaceDesc->bLength;

			// Scan all the endpoints
			for (nEPIdx = 0; nEPIdx < pUSBInterfaceDesc->bNumEndpoints; nEPIdx++)
			{
				pUSBEndPointDesc = (PUSB_ENDPOINT_DESCRIPTOR)pBuf;

				// Is this the EP we're looking for?
				if ((pUSBEndPointDesc->bEndpointAddress == nEndPointID) && (pDevHandle->nAltInterface == nCurrIF))
				{
					// Get the EP type
					nUBBEPType = pUSBEndPointDesc->bmAttributes & USB_ENDPOINT_TYPE_MASK;

					// Verify that the EP type matches the requested EP
					if (nEPType == XN_USB_EP_BULK)
					{
						if (nUBBEPType != USB_ENDPOINT_TYPE_BULK)
						{
							XN_ALIGNED_FREE_AND_NULL(pEPHandle);
							return (XN_STATUS_USB_WRONG_ENDPOINT_TYPE);
						}
					}
					else if (nEPType == XN_USB_EP_INTERRUPT)
					{
						if (nUBBEPType != USB_ENDPOINT_TYPE_INTERRUPT)
						{
							XN_ALIGNED_FREE_AND_NULL(pEPHandle);
							return (XN_STATUS_USB_WRONG_ENDPOINT_TYPE);
						}
					}
					else if (nEPType == XN_USB_EP_ISOCHRONOUS)
					{
						if (nUBBEPType != USB_ENDPOINT_TYPE_ISOCHRONOUS)
						{
							XN_ALIGNED_FREE_AND_NULL(pEPHandle);
							return (XN_STATUS_USB_WRONG_ENDPOINT_TYPE);
						}
					}
					else
					{
						XN_ALIGNED_FREE_AND_NULL(pEPHandle);
						return (XN_STATUS_USB_UNKNOWN_ENDPOINT_TYPE);
					}

					// Verify that the EP direction matches the requested direction
					if (nDirType == XN_USB_DIRECTION_IN)
					{
						if (USB_ENDPOINT_DIRECTION_IN(pUSBEndPointDesc->bEndpointAddress) == FALSE)
						{
							XN_ALIGNED_FREE_AND_NULL(pEPHandle);
							return (XN_STATUS_USB_WRONG_ENDPOINT_DIRECTION);
						}
					}
					else if (nDirType == XN_USB_DIRECTION_OUT)
					{
						if (USB_ENDPOINT_DIRECTION_OUT(pUSBEndPointDesc->bEndpointAddress) == FALSE)
						{
							XN_ALIGNED_FREE_AND_NULL(pEPHandle);
							return (XN_STATUS_USB_WRONG_ENDPOINT_DIRECTION);
						}
					}
					else
					{
						XN_ALIGNED_FREE_AND_NULL(pEPHandle);
						return (XN_STATUS_USB_UNKNOWN_ENDPOINT_DIRECTION);
					}

					// Construct the pipe file name
					pEPHandle->cpPipeName[0] = 0;

					cpPipeID[0] = '0';
					cpPipeID[1] = '0' + nEPIdx;
					cpPipeID[2] = 0;
			
					StringCchCopy(pEPHandle->cpPipeName, MAX_DEVICE_STR_LENGTH, pDevHandle->cpDeviceName);
					StringCchCat(pEPHandle->cpPipeName, MAX_DEVICE_STR_LENGTH, PSDRV_PIPE_PREFIX);
					StringCchCat(pEPHandle->cpPipeName, MAX_DEVICE_STR_LENGTH, cpPipeID);

					// Open the regular pipe handle
					pEPHandle->hEPHandle = CreateFile(pEPHandle->cpPipeName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
					if (pEPHandle->hEPHandle == INVALID_HANDLE_VALUE)
					{
						XN_ALIGNED_FREE_AND_NULL(pEPHandle);
						return (XN_STATUS_USB_OPEN_ENDPOINT_FAILED);
					}

					// Init the overlapped I/O structs
					nRetVal = xnUSBInitOvlp(pEPHandle);
					if (nRetVal != XN_STATUS_OK)
					{
						XN_ALIGNED_FREE_AND_NULL(pEPHandle);
						return (XN_STATUS_USB_OPEN_ENDPOINT_FAILED);						
					}

					// Init the ThreadData variables
					xnOSMemSet(&pEPHandle->ThreadData, 0, sizeof(xnUSBReadThreadData));
					pEPHandle->ThreadData.bInUse = FALSE;

					// Init the default endpoint properties
					pEPHandle->nTimeOut = XN_USB_DEFAULT_EP_TIMEOUT;
					pEPHandle->nEPType = nEPType;
					pEPHandle->nEPDir = nDirType;
					pEPHandle->nEndPointID = nEndPointID;

					// Set the default endpoint timeout
					nRetVal = xnUSBSetPipeProperty(pEPHandle, PSUSBDRV_PIPE_PROPERTY_TIMEOUT, XN_USB_DEFAULT_EP_TIMEOUT);
					if (nRetVal != XN_STATUS_OK)
					{
						XN_ALIGNED_FREE_AND_NULL(pEPHandle);
						return (nRetVal);
					}

					if (nUBBEPType == USB_ENDPOINT_TYPE_ISOCHRONOUS)
					{
						// bits 11 and 12 mark the number of additional transactions, bits 0-10 mark the size
						XnUInt32 nAdditionalTransactions = pUSBEndPointDesc->wMaxPacketSize >> 11;
						XnUInt32 nPacketSize = pUSBEndPointDesc->wMaxPacketSize & 0x7FF;
						pEPHandle->nMaxPacketSize = (nAdditionalTransactions + 1) * (nPacketSize);
					}
					else
					{
						pEPHandle->nMaxPacketSize = pUSBEndPointDesc->wMaxPacketSize;
					}

					// Mark the endpoint as valid
					pEPHandle->bValid = TRUE;

					// The end... (Happy)
					return (XN_STATUS_OK);
				}

				pBuf += pUSBEndPointDesc->bLength;
			}
예제 #5
0
파일: SfxCA.cpp 프로젝트: 925coder/wix3
/// <summary>
/// Invokes a managed custom action from native code by
/// extracting the package to a temporary working directory
/// then hosting the CLR and locating and calling the entrypoint.
/// </summary>
/// <param name="hSession">Handle to the installation session.
/// Passed to custom action entrypoints by the installer engine.</param>
/// <param name="szWorkingDir">Directory containing the CA binaries
/// and the CustomAction.config file defining the entrypoints.
/// This may be NULL, in which case the current module must have
/// a concatenated cabinet containing those files, which will be
/// extracted to a temporary directory.</param>
/// <param name="szEntryPoint">Name of the CA entrypoint to be invoked.
/// This must be either an explicit &quot;AssemblyName!Namespace.Class.Method&quot;
/// string, or a simple name that maps to a full entrypoint definition
/// in CustomAction.config.</param>
/// <returns>The value returned by the managed custom action method,
/// or ERROR_INSTALL_FAILURE if the CA could not be invoked.</returns>
int InvokeCustomAction(MSIHANDLE hSession,
        const wchar_t* szWorkingDir, const wchar_t* szEntryPoint)
{
#ifdef MANAGED_CAs_OUT_OF_PROC
        if (!g_fRunningOutOfProc && szWorkingDir == NULL)
        {
                return InvokeOutOfProcManagedCustomAction(hSession, szEntryPoint);
        }
#endif

        wchar_t szTempDir[MAX_PATH];
        bool fDeleteTemp = false;
        if (szWorkingDir == NULL)
        {
                if (!ExtractToTempDirectory(hSession, g_hModule, szTempDir, MAX_PATH))
                {
                        return ERROR_INSTALL_FAILURE;
                }
                szWorkingDir = szTempDir;
                fDeleteTemp = true;
        }

        wchar_t szConfigFilePath[MAX_PATH + 20];
        StringCchCopy(szConfigFilePath, MAX_PATH + 20, szWorkingDir);
        StringCchCat(szConfigFilePath, MAX_PATH + 20, L"\\CustomAction.config");

        const wchar_t* szConfigFile = szConfigFilePath;
        if (!::PathFileExists(szConfigFilePath))
        {
                szConfigFile = NULL;
        }

        wchar_t szWIAssembly[MAX_PATH + 50];
        StringCchCopy(szWIAssembly, MAX_PATH + 50, szWorkingDir);
        StringCchCat(szWIAssembly, MAX_PATH + 50, L"\\Microsoft.Deployment.WindowsInstaller.dll");

        int iResult = ERROR_INSTALL_FAILURE;
        ICorRuntimeHost* pHost;
        if (LoadCLR(hSession, NULL, szConfigFile, szWIAssembly, &pHost))
        {
                _AppDomain* pAppDomain;
                if (CreateAppDomain(hSession, pHost, L"CustomAction", szWorkingDir,
                        szConfigFile, &pAppDomain))
                {
                        if (!InvokeManagedCustomAction(hSession, pAppDomain, szEntryPoint, &iResult))
                        {
                                iResult = ERROR_INSTALL_FAILURE;
                        }
                        HRESULT hr = pHost->UnloadDomain(pAppDomain);
                        if (FAILED(hr))
                        {
                                Log(hSession, L"Failed to unload app domain. Error code 0x%X", hr);
                        }
                        pAppDomain->Release();
                }

                pHost->Stop();
                pHost->Release();
        }

        if (fDeleteTemp)
        {
                DeleteDirectory(szTempDir);
        }
        return iResult;
}
예제 #6
0
UINT __stdcall InitializeEmbeddedUI(MSIHANDLE hSession, LPCWSTR szResourcePath, LPDWORD pdwInternalUILevel)
{
	// If the managed initialize method cannot be called, continue the installation in BASIC UI mode.
	UINT uiResult = INSTALLUILEVEL_BASIC;

	const wchar_t* szClassName = L"InitializeEmbeddedUI_FullClassName" NULLSPACE;

	g_szWorkingDir = szResourcePath;

	wchar_t szModule[MAX_PATH];
	DWORD cchCopied = GetModuleFileName(g_hModule, szModule, MAX_PATH - 1);
	if (cchCopied == 0)
	{
		Log(hSession, L"Failed to get module path. Error code %d.", GetLastError());
		return uiResult;
	}
	else if (cchCopied == MAX_PATH - 1)
	{
		Log(hSession, L"Failed to get module path -- path is too long.");
		return uiResult;
	}

	Log(hSession, L"Extracting embedded UI to temporary directory: %s", g_szWorkingDir);
	int err = ExtractCabinet(szModule, g_szWorkingDir);
	if (err != 0)
	{
		Log(hSession, L"Failed to extract to temporary directory. Cabinet error code %d.", err);
		Log(hSession, L"Ensure that no MsiEmbeddedUI.FileName values are the same as "
					  L"any file contained in the embedded UI package.");
		return uiResult;
	}

	wchar_t szConfigFilePath[MAX_PATH + 20];
	StringCchCopy(szConfigFilePath, MAX_PATH + 20, g_szWorkingDir);
	StringCchCat(szConfigFilePath, MAX_PATH + 20, L"\\EmbeddedUI.config");

	const wchar_t* szConfigFile = szConfigFilePath;
	if (!PathFileExists(szConfigFilePath))
	{
		szConfigFile = NULL;
	}

	wchar_t szWIAssembly[MAX_PATH + 50];
	StringCchCopy(szWIAssembly, MAX_PATH + 50, g_szWorkingDir);
	StringCchCat(szWIAssembly, MAX_PATH + 50, L"\\Microsoft.Deployment.WindowsInstaller.dll");

	if (LoadCLR(hSession, NULL, szConfigFile, szWIAssembly, &g_pClrHost))
	{
		if (CreateAppDomain(hSession, g_pClrHost, L"EmbeddedUI", g_szWorkingDir,
			szConfigFile, &g_pAppDomain))
		{
			const wchar_t* szMsiAssemblyName  = L"Microsoft.Deployment.WindowsInstaller";
			const wchar_t* szProxyClass = L"Microsoft.Deployment.WindowsInstaller.EmbeddedUIProxy";
			const wchar_t* szInitMethod = L"Initialize";
			const wchar_t* szProcessMessageMethod = L"ProcessMessage";
			const wchar_t* szShutdownMethod = L"Shutdown";
	
			if (GetMethod(hSession, g_pAppDomain, szMsiAssemblyName,
					  szProxyClass, szProcessMessageMethod, &g_pProcessMessageMethod) &&
				GetMethod(hSession, g_pAppDomain, szMsiAssemblyName,
					  szProxyClass, szShutdownMethod, &g_pShutdownMethod))
			{
				_MethodInfo* pInitMethod;
				if (GetMethod(hSession, g_pAppDomain, szMsiAssemblyName,
							  szProxyClass, szInitMethod, &pInitMethod))
				{
					bool invokeSuccess = InvokeInitializeMethod(pInitMethod, hSession, szClassName, pdwInternalUILevel, &uiResult);
					pInitMethod->Release();
					if (invokeSuccess)
					{
						if (uiResult == 0)
						{
							return ERROR_SUCCESS;
						}
						else if (uiResult == ERROR_INSTALL_USEREXIT)
						{
							// InitializeEmbeddedUI is not allowed to return ERROR_INSTALL_USEREXIT.
							// So return success here and then IDCANCEL on the next progress message.
							uiResult = 0;
							*pdwInternalUILevel = INSTALLUILEVEL_NONE;
							Log(hSession, L"Initialization canceled by user.");
						}
					}
				}
			}

			g_pProcessMessageMethod->Release();
			g_pProcessMessageMethod = NULL;
			g_pShutdownMethod->Release();
			g_pShutdownMethod = NULL;

			g_pClrHost->UnloadDomain(g_pAppDomain);
			g_pAppDomain->Release();
			g_pAppDomain = NULL;
		}
		g_pClrHost->Stop();
		g_pClrHost->Release();
		g_pClrHost = NULL;
	}

	return uiResult;
}
예제 #7
0
BOOL Credential::SetMacDefaultBoot()
{
    // get the filesystem location of %ProgramFiles%
    // http://msdn.microsoft.com/en-us/library/bb762188.aspx
    wchar_t* pathProgramFiles = 0;
    SHGetKnownFolderPath(FOLDERID_ProgramFiles, 0, NULL, &pathProgramFiles);

    // build the path to bootcamp.exe
    // http://msdn.microsoft.com/en-us/library/ms647527.aspx
    std::wstring pathBootCamp(pathProgramFiles);
    pathBootCamp += L"\\Boot Camp\\BootCamp.exe";

    // free the memory like the docs tell us
    CoTaskMemFree(static_cast<void*>(pathProgramFiles));

    // Make sure the executable exists
    DWORD attr = GetFileAttributes(pathBootCamp.c_str());
    if (attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY))
    {
        debug << "BootCamp.exe not found at " << pathBootCamp.c_str() << std::endl;
        return FALSE;
    }

    // Finish building the complete command line to set the Mac startup volume
    // http://support.apple.com/kb/HT3802
    // "%ProgramFiles%\Boot Camp\BootCamp.exe" -StartupDisk
    std::wstring fullCmd(L"\"" + pathBootCamp + L"\" -StartupDisk");

    debug << fullCmd.c_str() << std::endl;

    // CreateProcess
    //http://msdn.microsoft.com/en-us/library/ms682425.aspx
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    wchar_t * pwszCmd = new wchar_t[fullCmd.length() + 1];
    StringCchCopy(pwszCmd, fullCmd.length() + 1, fullCmd.c_str());

    if (!CreateProcessW(NULL,   // No module name (use command line)
                        pwszCmd,        // Command line
                        NULL,           // Process handle not inheritable
                        NULL,           // Thread handle not inheritable
                        FALSE,          // Set handle inheritance to FALSE
                        0,              // No creation flags
                        NULL,           // Use parent's environment block
                        NULL,           // Use parent's starting directory
                        &si,            // Pointer to STARTUPINFO structure
                        &pi )           // Pointer to PROCESS_INFORMATION structure
       )
    {
        debug << L"CreateProcess failed with error " << GetLastError() << std::endl;
        /* Free memory */
        delete[]pwszCmd;
        pwszCmd = 0;
        return FALSE;
    }

    // Wait until child process exits.
    WaitForSingleObject( pi.hProcess, 5000 );

    debug << L"BootCamp.exe finished or timeout elapsed" << std::endl;

    // Close process and thread handles.
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );

    /* Free memory */
    delete[]pwszCmd;
    pwszCmd = 0;

    return TRUE;
}
예제 #8
0
//
//  Parse the command line and set options based on those arguments.
//
bool ParseCommandLine(int argc, wchar_t *argv[], const CommandLineSwitch Switches[], size_t SwitchCount)
{
    //
    //  Iterate over the command line arguments
    for (int i = 1 ; i < argc ; i += 1)
    {
        if (argv[i][0] == L'-' || argv[i][0] == L'/')
        {
            size_t switchIndex;
            for (switchIndex = 0 ; switchIndex < SwitchCount ; switchIndex += 1)
            {
                size_t switchNameLength = wcslen(Switches[switchIndex].SwitchName);
                if (_wcsnicmp(&argv[i][1], Switches[switchIndex].SwitchName, switchNameLength) == 0 && 
                    (argv[i][switchNameLength+1]==L':' || argv[i][switchNameLength+1] == '\0'))
                {
                    wchar_t *switchValue = NULL;

                    if (Switches[switchIndex].SwitchType != CommandLineSwitch::SwitchTypeNone)
                    {
                        //
                        //  This is a switch value that expects an argument.
                        //
                        //  Check to see if the last character of the argument is a ":".
                        //
                        //  If it is, then the user specified an argument, so we should use the value after the ":"
                        //  as the argument.
                        //
                        if (argv[i][switchNameLength+1] == L':')
                        {
                            switchValue = &argv[i][switchNameLength+2];
                        }
                        else if (i < argc)
                        {
                            //
                            //  If the switch value isn't optional, the next argument
                            //  must be the value.
                            //
                            if (!Switches[switchIndex].SwitchValueOptional)
                            {
                                switchValue = argv[i+1];
                                i += 1; // Skip the argument.
                            }
                            //
                            //  Otherwise the switch value is optional, so check the next parameter.
                            //
                            //  If it's a switch, the user didn't specify a value, if it's not a switch
                            //  the user DID specify a value.
                            //
                            else if (argv[i+1][0] != L'-' && argv[i+1][0] != L'/')
                            {
                                switchValue = argv[i+1];
                                i += 1; // Skip the argument.
                            }
                        }
                        else if (!Switches[switchIndex].SwitchValueOptional)
                        {
                            printf("Invalid command line argument parsing option %S\n", Switches[switchIndex].SwitchName);
                            return false;
                        }
                    }
                    switch (Switches[switchIndex].SwitchType)
                    {
                        //
                        //  SwitchTypeNone switches take a boolean parameter indiating whether or not the parameter was present.
                        //
                    case CommandLineSwitch::SwitchTypeNone:
                        *reinterpret_cast<bool *>(Switches[switchIndex].SwitchValue) = true;
                        break;
                        //
                        //  SwitchTypeInteger switches take an integer parameter.
                        //
                    case CommandLineSwitch::SwitchTypeInteger:
                        {
                            wchar_t *endValue;
                            long value = wcstoul(switchValue, &endValue, 0);
                            if (value == ULONG_MAX || value == 0 || (*endValue != L'\0' && !iswspace(*endValue)))
                            {
                                printf("Command line switch %S expected an integer value, received %S", Switches[switchIndex].SwitchName, switchValue);
                                return false;
                            }
                            *reinterpret_cast<long *>(Switches[switchIndex].SwitchValue) = value;
                            break;
                        }
                        //
                        //  SwitchTypeString switches take a string parameter - allocate a buffer for the string using operator new[].
                        //
                    case CommandLineSwitch::SwitchTypeString:
                        {
                            wchar_t ** switchLocation = reinterpret_cast<wchar_t **>(Switches[switchIndex].SwitchValue);
                            //
                            //  If the user didn't specify a value, set the location to NULL.
                            //
                            if (switchValue == NULL || *switchValue == '\0')
                            {
                                *switchLocation = NULL;
                            }
                            else
                            {
                                size_t switchLength = wcslen(switchValue)+1;
                                *switchLocation = new (std::nothrow) wchar_t[switchLength];
                                if (*switchLocation == NULL)
                                {
                                    printf("Unable to allocate memory for switch %S", Switches[switchIndex].SwitchName);
                                    return false;
                                }

                                HRESULT hr = StringCchCopy(*switchLocation, switchLength, switchValue);
                                if (FAILED(hr))
                                {
                                    printf("Unable to copy command line string %S to buffer\n", switchValue);
                                    return false;
                                }
                            }
                            break;
                        }
                    default:
                        break;
                    }
                    //  We've processed this command line switch, we can move to the next argument.
                    //
                    break;
                }
            }
            if (switchIndex == SwitchCount)
            {
                printf("unrecognized switch: %S", argv[i]);
                return false;
            }
        }
    }
    return true;
}
예제 #9
0
static INT_PTR CALLBACK
cfgui_dlgproc(HWND hwnd,
              UINT uMsg,
              WPARAM wParam,
              LPARAM lParam) {

    khui_config_node node;
    cfgui_wnd_data * d;

    switch(uMsg) {
    case WM_INITDIALOG:
        node = (khui_config_node) lParam;

        khui_cfg_clear_params();

        khui_cfg_set_configui_handle(hwnd);

        d = PMALLOC(sizeof(*d));
        ZeroMemory(d, sizeof(*d));

        d->hbr_white = CreateSolidBrush(RGB(255,255,255));

        d->hw_generic_pane =
            CreateDialogParam(khm_hInstance,
                              MAKEINTRESOURCE(IDD_CFG_GENERIC),
                              hwnd,
                              cfgui_dlgproc_generic,
                              (LPARAM) d);

        khui_bitmap_from_hbmp(&d->kbmp_logo,
                              LoadImage(
                                        khm_hInstance,
                                        MAKEINTRESOURCE(IDB_LOGO_OPAQUE),
                                        IMAGE_BITMAP,
                                        0,
                                        0,
                                        LR_DEFAULTCOLOR));

        cfgui_set_wnd_data(hwnd, d);

        cfgui_initialize_dialog(hwnd);

        cfgui_activate_node(hwnd, node);

        cfgui_hwnd = hwnd;

        khm_enter_modal(hwnd);

        return TRUE;

    case WM_DESTROY:

        cfgui_hwnd = NULL;

        khui_cfg_set_configui_handle(NULL);

        cfgui_uninitialize_dialog(hwnd);

        d = cfgui_get_wnd_data(hwnd);
        if (d == NULL)
            break;

        khui_delete_bitmap(&d->kbmp_logo);
        DeleteObject(d->hbr_white);

        cfgui_set_wnd_data(hwnd, NULL);

        SetForegroundWindow(khm_hwnd_main);

        PFREE(d);

        return FALSE;

    case WM_NOTIFY:
        {
            LPNMHDR lpnm;
            LPNMTREEVIEW lptv;
            LPNMTVGETINFOTIP lpgi;
            khui_config_node node;

            lpnm = (LPNMHDR) lParam;

            switch (lpnm->code) {
            case TVN_SELCHANGED:
                lptv = (LPNMTREEVIEW) lParam;
                cfgui_activate_node(hwnd,
                                    (khui_config_node)
                                    lptv->itemNew.lParam);
                return TRUE;

            case TVN_GETINFOTIP:
                lpgi = (LPNMTVGETINFOTIP) lParam;
                node = (khui_config_node) lpgi->lParam;

                if (node) {
                    khm_int32 flags = 0;

                    flags = khui_cfg_get_flags(node);

                    if (flags & KHUI_CNFLAG_MODIFIED) {
                        LoadString(khm_hInstance, IDS_CFG_IT_MOD,
                                   lpgi->pszText, lpgi->cchTextMax);
                    } else if (flags & KHUI_CNFLAG_APPLIED) {
                        LoadString(khm_hInstance, IDS_CFG_IT_APP,
                                   lpgi->pszText, lpgi->cchTextMax);
                    } else {
                        LoadString(khm_hInstance, IDS_CFG_IT_NONE,
                                   lpgi->pszText, lpgi->cchTextMax);
                    }
                } else {
                    StringCchCopy(lpgi->pszText, lpgi->cchTextMax, L"");
                }

                return TRUE;
            }
        }
        return TRUE;

    case WM_CTLCOLORSTATIC:
        {
            d = cfgui_get_wnd_data(hwnd);
            if (d == NULL)
                break;

            return (BOOL)(DWORD_PTR) d->hbr_white;
        }
        /* implicit break */

    case WM_COMMAND:
        switch(wParam) {
        case MAKEWPARAM(IDCANCEL, BN_CLICKED):
            khm_leave_modal();
            EndDialog(hwnd, 0);
            break;

        case MAKEWPARAM(IDAPPLY, BN_CLICKED):
            cfgui_apply_settings(NULL);
            break;

        case MAKEWPARAM(IDOK, BN_CLICKED):
            cfgui_apply_settings(NULL);
            khm_leave_modal();
            EndDialog(hwnd, 0);
            break;
        }
        return TRUE;

    case KHUI_WM_CFG_NOTIFY:
        switch(HIWORD(wParam)) {
        case WMCFG_SHOW_NODE:
            cfgui_activate_node(hwnd, (khui_config_node) lParam);
            break;

        case WMCFG_UPDATE_STATE:
            cfgui_update_state(hwnd, LOWORD(wParam),
                               (khui_config_node) lParam);
            break;

        case WMCFG_SYNC_NODE_LIST:
            d = cfgui_get_wnd_data(hwnd);
            if (d == NULL)
                break;

            cfgui_sync_node_list(d, hwnd);
            break;
        }

        return TRUE;
    }

    return FALSE;
}
예제 #10
0
BOOL CALLBACK CQuickLaunch::QuickLaunchProc(HWND hwndDlg, UINT message, WPARAM wParam, LPARAM lParam) 
{
	static HWND hwndList;
	static HKEY g_hKey = NULL;
	static list<LaunchItem*> launchItems;

	TEXTMETRIC tm;

	static CDlgAnchor g_dlgAnchor;

    switch (message) 
    { 
		case WM_SIZE :
		{
			g_dlgAnchor.OnSize();
		}
		break;
		case WM_MEASUREITEM :
			{
				LPMEASUREITEMSTRUCT lpmis;
				lpmis = (MEASUREITEMSTRUCT FAR*) lParam;
				if (GetTextMetricsW(GetDC(hwndDlg), &tm))
				{
					lpmis->itemHeight = (UINT)(tm.tmHeight * 2.5);
				}
				else
				{
					lpmis->itemHeight = 50;
				}
			}
			break;
		case WM_DRAWITEM :
			{
				WCHAR tchBuffer[256] = {0};
				int y = 0;
				LPDRAWITEMSTRUCT lpdis = (DRAWITEMSTRUCT FAR*) lParam;

				LaunchItem* pRecord = (LaunchItem*)lpdis->itemData;
				GetTextMetrics(lpdis->hDC, &tm);

				HBRUSH hBrush = NULL;
				SetBkMode(lpdis->hDC, TRANSPARENT);
				if ((lpdis->itemAction & (ODA_SELECT | ODA_DRAWENTIRE)))
				{
					if ((lpdis->itemState & ODS_SELECTED))
					{
						hBrush = GetSysColorBrush(COLOR_HIGHLIGHT);
						SetTextColor(lpdis->hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
					}
					else
					{
						hBrush = GetSysColorBrush(COLOR_WINDOW);
						SetTextColor(lpdis->hDC, GetSysColor(COLOR_WINDOWTEXT));
					}
				}
				if (hBrush)
				{
					int desiredHeight = (lpdis->rcItem.bottom - lpdis->rcItem.top) - 2;

					RECT rect;
					memcpy(&rect, &(lpdis->rcItem), sizeof(RECT));
					rect.top += 1;
					rect.bottom -= 1;
					rect.left += 1;
					rect.right -= 1;
					rect.left += desiredHeight;

					FillRect(lpdis->hDC, &rect, hBrush);

					rect.left += 5;
					rect.right -= 5;
					rect.bottom -= 5;
					rect.top += 5;

					WCHAR wzFullPath[MAX_PATH];
					WCHAR wzName[MAX_PATH];
					StringCchCopy(wzFullPath, ARRAYSIZE(wzFullPath), pRecord->wzPath);
					StringCchCopy(wzName, ARRAYSIZE(wzName), pRecord->wzPath);

					WCHAR* wzFile = wcsrchr(wzName, L'\\');

					if (!wzFile)
					{
						wzFile = wzName;
					}
					else
					{
						wzFile++;
					}
					WCHAR* wzExt = wcsrchr(wzFile, L'.');
					if (wzExt)
					{
						wzExt[0] = 0;
					}

					WCHAR* wzDir = wcsrchr(wzFullPath, L'\\');
					if (wzDir)
					{
						wzDir[0] = 0;
					}

					// todo - trim of .lnk
					DrawText(lpdis->hDC, wzFile, wcslen(wzFile), &rect, DT_TOP);
					
					LOGFONT lf;
					ZeroMemory(&lf, sizeof(lf));
					lf.lfHeight = -((rect.bottom - rect.top) / 4);
					lf.lfWeight = FW_BOLD;
					lf.lfCharSet = DEFAULT_CHARSET;
					HFONT hFont = CreateFontIndirect(&lf);
					HGDIOBJ hOldFont = SelectObject(lpdis->hDC, hFont);
					DrawText(lpdis->hDC, wzFullPath, wcslen(wzFullPath), &rect, DT_BOTTOM);
					SelectObject(lpdis->hDC, hOldFont);

					if (pRecord->hIcon)
					{
						DrawIcon(lpdis->hDC, 0, rect.top, pRecord->hIcon);
					}
				}
			}
			break;
        case WM_INITDIALOG:
        {
			g_dlgAnchor.Init(hwndDlg);
			g_dlgAnchor.Add(IDC_LIST_SPEEDDIAL, ANCHOR_ALL);
			g_dlgAnchor.Add(IDC_BUTTON_ADD, ANCHOR_RIGHT | ANCHOR_BOTTOM);
			g_dlgAnchor.Add(IDC_BUTTON_REMOVE, ANCHOR_RIGHT | ANCHOR_TOP);
			g_dlgAnchor.Add(IDC_BUTTON_MOVEDOWN, ANCHOR_RIGHT | ANCHOR_TOP);
			g_dlgAnchor.Add(IDC_BUTTON_MOVEUP, ANCHOR_RIGHT | ANCHOR_TOP);

			hwndList = GetDlgItem(hwndDlg, IDC_LIST_SPEEDDIAL);

            SHINITDLGINFO shidi;
            // Create a Done button and size it.
            shidi.dwMask = SHIDIM_FLAGS;
            shidi.dwFlags = SHIDIF_DONEBUTTON | SHIDIF_SIPDOWN | SHIDIF_SIZEDLGFULLSCREEN;
            shidi.hDlg = hwndDlg;
            SHInitDialog(&shidi);

            SHMENUBARINFO mbi;
            memset(&mbi, 0, sizeof(SHMENUBARINFO));
            mbi.cbSize = sizeof(SHMENUBARINFO);
            mbi.hwndParent = hwndDlg;
            mbi.nToolBarId = IDR_Flipper_SET_MENUBAR;
			mbi.hInstRes = CQuickLaunch::g_hInstance;
            mbi.nBmpId = 0;
            mbi.cBmpImages = 0;    

            SHCreateMenuBar(&mbi);

			RECT rect;
			GetWindowRect(hwndList, &rect);
			
			LV_COLUMN lvC;
			lvC.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM;
			lvC.fmt = LVCFMT_LEFT;  // left-align column
			lvC.cx = rect.right - rect.left - 2;
			lvC.pszText = L"Name";

			HKEY hKey = (HKEY)lParam;
			g_hKey = hKey;

			CQuickLaunch::LoadLaunchItems(hKey, &launchItems);

			list<LaunchItem*>::iterator iter = launchItems.begin();

			while (iter != launchItems.end())
			{
				LaunchItem* pRecord = *iter;
				int index = ListBox_InsertString(hwndList, -1, pRecord->wzPath);
				ListBox_SetItemData(hwndList, index, pRecord);
				iter++;
			}
			SetFocus(hwndList);

            return 0;
        }
        break;
        case WM_COMMAND: 
			{
				if (HIWORD(wParam) == LBN_SELCHANGE)
				{
					int index = ListBox_GetCurSel(hwndList);
					int count = ListBox_GetCount(hwndList);

					bool bMoveUp = (index > 0);
					bool bMoveDown = (index < (count - 1));

					if (index < 0)
					{
						bMoveUp = bMoveDown = false;
					}

					EnableWindow(GetDlgItem(hwndDlg, IDC_BUTTON_REMOVE), index >= 0);
					EnableWindow(GetDlgItem(hwndDlg, IDC_BUTTON_MOVEUP), bMoveUp);
					EnableWindow(GetDlgItem(hwndDlg, IDC_BUTTON_MOVEDOWN), bMoveDown);
				}
				else if (HIWORD(wParam) == BN_CLICKED)
				{
					switch (LOWORD(wParam)) 
					{
						case IDC_BUTTON_ADD :
						{
							LaunchItem* pRecord = new LaunchItem();
							SetCursor(LoadCursor(NULL, IDC_WAIT));

							CApplicationSelector* appSelector = new CApplicationSelector();
							// TODO
							if (appSelector->ShowDialog(CQuickLaunch::g_hInstance, hwndDlg, pRecord->wzPath, false))
							{
								pRecord->hIcon = GetApplicationIcon(pRecord->wzPath, false, NULL, NULL, NULL);
								int index = ListBox_InsertString(hwndList, -1, pRecord->wzPath);
								ListBox_SetItemData(hwndList, index, pRecord);
								ListBox_SetCurSel(hwndList, index);
								PostMessage(hwndDlg, WM_COMMAND, MAKELONG(0, LBN_SELCHANGE), 0);
							}
							else
							{
								delete pRecord;
							}
							delete appSelector;
							SetCursor(NULL);
						}
						break;
						case IDC_BUTTON_REMOVE :
						{
							int index = ListBox_GetCurSel(hwndList);

							if (index >= 0)
							{
								LaunchItem* pRecord = (LaunchItem*)ListBox_GetItemData(hwndList, index);
								ListBox_DeleteString(hwndList, index);
								delete pRecord;
							}
							int count = ListBox_GetCount(hwndList);
							ListBox_SetCurSel(hwndList, min(count-1, index));
							PostMessage(hwndDlg, WM_COMMAND, MAKELONG(0, LBN_SELCHANGE), 0);
						}
						break;
						case IDC_BUTTON_MOVEUP :
						{
							int index = ListBox_GetCurSel(hwndList);
							if (index > 0)
							{
								LaunchItem* pRecord = (LaunchItem*)ListBox_GetItemData(hwndList, index);
								ListBox_DeleteString(hwndList, index);
								ListBox_InsertString(hwndList, index-1, pRecord->wzPath);
								ListBox_SetItemData(hwndList, index-1, pRecord);
								ListBox_SetCurSel(hwndList, index-1);
								PostMessage(hwndDlg, WM_COMMAND, MAKELONG(0, LBN_SELCHANGE), 0);
							}
						}
						break;
						case IDC_BUTTON_MOVEDOWN :
						{
							int index = ListBox_GetCurSel(hwndList);
							int count = ListBox_GetCount(hwndList);
							if (index < count - 1)
							{
								LaunchItem* pRecord = (LaunchItem*)ListBox_GetItemData(hwndList, index);
								ListBox_DeleteString(hwndList, index);
								ListBox_InsertString(hwndList, index+1, pRecord->wzPath);
								ListBox_SetItemData(hwndList, index+1, pRecord);
								ListBox_SetCurSel(hwndList, index+1);
								PostMessage(hwndDlg, WM_COMMAND, MAKELONG(0, LBN_SELCHANGE), 0);
							}
						}
						break;
					}
				}
				switch (LOWORD(wParam))
				{
					case IDM_Flipper_SET_ACCEPT :
					case IDOK:
						{
							int index = 0;

							list<LaunchItem*> launchItems;
							int count = ListBox_GetCount(hwndList);

							for (int i = 0; i < count; ++i)
							{
								WCHAR wzPath[10], wzCount[5];
								DWORD dwSize = 0;
								_itow(i, wzCount, 10);

								StringCchCopy(wzPath, ARRAYSIZE(wzPath), wzCount);
								StringCchCat(wzPath, ARRAYSIZE(wzPath), L"_Path");

								LaunchItem* pRecord = (LaunchItem*)ListBox_GetItemData(hwndList, i);
								launchItems.push_back(pRecord);
							}

							CQuickLaunch::SaveLaunchItems(g_hKey, &launchItems);

							EndDialog(hwndDlg, IDOK);
						}
						break;
					case IDM_Flipper_SET_CANCEL:
						{
							EndDialog(hwndDlg, IDOK);
						}
						break;
				}
            }
            break;
        case WM_DESTROY:
            {
				CQuickLaunch::DestroyLaunchItems(&launchItems);
                Sleep(0);
            }
            break;
    } 
    return FALSE; 
}
예제 #11
0
/*!
	ウインドウを作成
	@param[in]	iNowPage	プレビュりたい頁番号
	@param[in]	bForeg		非0なら再プレビューのときにフォアグランドにする・0ならしない・プレビュー開いてないなら何もしない
	@return	HRESULT	終了状態コード
*/
HRESULT PreviewVisibalise( INT iNowPage, BOOLEAN bForeg )
{
	HWND	hWnd;
	TCHAR	atBuffer[MAX_STRING];
//	UINT	iIndex;
	RECT	rect;
	RECT	tbRect;

	HRESULT	hRslt;

	CComPtr<IUnknown>	comPunkIE;	
	CComPtr<IDispatch>	pDispatch;
	CComVariant	vEmpty;
	CComVariant	vUrl( TEXT("about:blank") );

#ifdef REDRAW_ATSCROLL
	LONG	height, offhei, scrtop;
//	CComQIPtr<IHTMLWindow2>		pWindow2;
	CComQIPtr<IHTMLElement>		pElement;
	CComQIPtr<IHTMLElement2>	pElement2;
#endif

	if( ghPrevWnd )	//	已にPreview窓有ったら
	{
	//	SendMessage( ghToolWnd, TB_CHECKBUTTON, IDM_PVW_ALLVW, FALSE );

#pragma message ("全プレ書換時に、スクロールバーの位置覚えておいて、そこまでScrollさせる?")

#ifdef REDRAW_ATSCROLL
		gpWebBrowser2->get_Height( &height );	//	多分コンポーネントの高さ

		gpDocument2->get_body( &pElement );
		pElement.QueryInterface( &pElement2 );
		pElement.Release(  );

		pElement2->get_scrollHeight( &offhei );	//	全体の高さ
		pElement2->get_scrollTop( &scrtop );	//	表示位置のスクロール量
		pElement2.Release(  );

#endif

		//	内容書き換え
		if( 0 > giViewMode ){	PreviewPageWrite(  -1 );	}
		else{	PreviewPageWrite( iNowPage );	}

		gpWebBrowser2->Refresh(  );

#ifdef REDRAW_ATSCROLL
		gpDocument2->get_body( &pElement );
		pElement.QueryInterface( &pElement2 );
		pElement.Release(  );

		pElement2->get_scrollHeight( &offhei );	//	全体の高さ

		pElement2->put_scrollTop(  scrtop );	//	表示位置のスクロール量
		pElement2.Release(  );
#endif

		InvalidateRect( ghPrevWnd, NULL, TRUE );

		if( bForeg )	SetForegroundWindow( ghPrevWnd );

		return S_FALSE;
	}

	//	プレビュー開いてないときに、非フォアグランドなら何もしない
	if( !(bForeg) ){	return  E_ABORT;	}


	InitWindowPos( INIT_LOAD, WDP_PREVIEW, &rect );
	if( 0 >= rect.right || 0 >= rect.bottom )	//	幅高さが0はデータ無し
	{
		hWnd = GetDesktopWindow( );
		GetWindowRect( hWnd, &rect );
		rect.left   = ( rect.right  - PVW_WIDTH ) / 2;
		rect.top    = ( rect.bottom - PVW_HEIGHT ) / 2;
		rect.right  = PVW_WIDTH;
		rect.bottom = PVW_HEIGHT;
		InitWindowPos( INIT_SAVE , WDP_PREVIEW, &rect );	//	起動時保存
	}


	ghPrevWnd = CreateWindowEx( WS_EX_TOOLWINDOW, DOC_PREVIEW_CLASS, TEXT("IEコンポーネントによるプレビュー"),
		WS_POPUP | WS_THICKFRAME | WS_CAPTION | WS_VISIBLE | WS_SYSMENU,
		rect.left, rect.top, rect.right, rect.bottom, NULL, NULL, ghInst, NULL );

	//ツールバー作る
	ghToolWnd = CreateWindowEx( 0, TOOLBARCLASSNAME, TEXT("toolbar"),
		WS_CHILD | WS_VISIBLE | TBSTYLE_FLAT | TBSTYLE_LIST | TBSTYLE_TOOLTIPS | CCS_NODIVIDER,
		0, 0, 0, 0, ghPrevWnd, (HMENU)IDW_PVW_TOOL_BAR, ghInst, NULL );

	//	自動ツールチップスタイルを追加
	SendMessage( ghToolWnd, TB_SETEXTENDEDSTYLE, 0, TBSTYLE_EX_MIXEDBUTTONS );

	SendMessage( ghToolWnd, TB_SETIMAGELIST, 0, (LPARAM)ghPrevwImgLst );

	SendMessage( ghToolWnd, TB_SETBUTTONSIZE, 0, MAKELPARAM(16,16) );

	SendMessage( ghToolWnd, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0 );
	//	ツールチップ文字列を設定・ボタンテキストがツールチップになる
	StringCchCopy( atBuffer, MAX_STRING, TEXT("全プレビュースタイル") );	gstTBInfo[0].iString = SendMessage( ghToolWnd, TB_ADDSTRING, 0, (LPARAM)atBuffer );

	SendMessage( ghToolWnd , TB_ADDBUTTONS, (WPARAM)TB_ITEMS, (LPARAM)&gstTBInfo );	//	ツールバーにボタンを挿入

	SendMessage( ghToolWnd , TB_AUTOSIZE, 0, 0 );	//	ボタンのサイズに合わせてツールバーをリサイズ
	InvalidateRect( ghToolWnd , NULL, TRUE );		//	クライアント全体を再描画する命令

	//	ツールバーサブクラス化が必要

	GetWindowRect( ghToolWnd, &tbRect );
	tbRect.right  -= tbRect.left;
	tbRect.bottom -= tbRect.top;
	tbRect.left = 0;
	tbRect.top  = 0;

	GetClientRect( ghPrevWnd, &rect );
	rect.top     = tbRect.bottom;
	rect.bottom -= tbRect.bottom;

	AtlAxWinInit(  );

	ghIEwnd = CreateWindowEx( 0, ATL_AX_WIN, TEXT("Shell.Explorer.2"),
		WS_CHILD | WS_VISIBLE, rect.left, rect.top, rect.right, rect.bottom,
		ghPrevWnd, (HMENU)IDW_PVW_VIEW_WNDW, ghInst, NULL );

	//	ActiveXコントロールのインターフェースを要求
	if( SUCCEEDED( AtlAxGetControl( ghIEwnd, &comPunkIE ) ) )
	{
		gpWebBrowser2 = comPunkIE;	//	ポインタに格納

		if( gpWebBrowser2 )
		{
			gpWebBrowser2->Navigate2( &vUrl, &vEmpty, &vEmpty, &vEmpty, &vEmpty );

			while( 1 )
			{
				hRslt = gpWebBrowser2->get_Document( &pDispatch );
				if( SUCCEEDED(hRslt) && pDispatch )
				{
					gpDocument2 = pDispatch;
					if( gpDocument2 ){	hRslt = S_OK;	break;	}
				}
				Sleep(100);
			}
		}
		else
		{
			NotifyBalloonExist( TEXT("IEコンポーネントを初期化出来なかったよ・・・"), TEXT("お燐からのお知らせ"), NIIF_ERROR );
			hRslt = E_ACCESSDENIED;
		}
	}

	if( SUCCEEDED(hRslt)  ){	PreviewPageWrite( iNowPage );	}

	UpdateWindow( ghPrevWnd );

	return hRslt;
}
예제 #12
0
node* CQuickLaunch::BuildLaunchList(int* piNodeLen, int thumbWidth, int thumbHeight)
{
	if (g_iThumbHeight != thumbHeight || g_iThumbWidth != thumbWidth)
	{
		DestroyPhoneNodes(NULL);
	}
	if (!g_pHeadNode)
	{
		node* pHead = NULL;
		node* pPrev = NULL;

		list<LaunchItem*> pPhoneList = g_launchList;
		list<LaunchItem*>::iterator iter = pPhoneList.begin();

		int iPhoneNodeListCount = 0;

		while (iter != pPhoneList.end())
		{
			LaunchItem* pRecord = *iter;
			node* pCurr = new node();
			if (!pHead)
			{
				pHead = pCurr;
				pCurr = pHead;
			}
			else
			{
				pPrev->next = pCurr;
			}
			pRecord->hIcon = GetApplicationIcon(pRecord->wzPath, false, NULL, NULL, NULL);
			pCurr->prev = pPrev;
			pCurr->hIcon = pRecord->hIcon;
			pCurr->iIndex = iPhoneNodeListCount;
			pCurr->bCenter = true;
			pCurr->hBmp = NULL;

			Sleep(5);

			WCHAR* wzName = wcsrchr(pRecord->wzPath, L'\\');
			if (!wzName)
			{
				wzName = pRecord->wzPath;
			}
			else
			{
				wzName++;
			}

			StringCchCopy(pCurr->wzText, ARRAYSIZE(pCurr->wzText), wzName);
			WCHAR* wzExt = wcsrchr(pCurr->wzText, '.');
			if (wzExt)
			{
				wzExt[0] = 0;
			}

			StringCchCopy(pCurr->wzDetails, ARRAYSIZE(pCurr->wzDetails), L"Select to Launch");
			/*
			StringCchCopy(pCurr->wzDetails, ARRAYSIZE(pCurr->wzDetails), pRecord->wzPath);
			wzName = wcsrchr(pCurr->wzDetails, L'\\');
			if (wzName)
			{
				wzName[0] = 0;
			}
			*/

			pCurr->pData = pRecord;

			pPrev = pCurr;
			iter++;
			iPhoneNodeListCount++;
		}
		g_iNodeLen = iPhoneNodeListCount;
		g_pHeadNode = pHead;
	}
	g_iThumbHeight = thumbHeight;
	g_iThumbWidth = thumbWidth;

	*piNodeLen = g_iNodeLen;
	return g_pHeadNode;
}
예제 #13
0
bool install(const std::wstring& inf, const std::wstring& hardware_id, bool& reboot_required)
{
	TCHAR inf_path[MAX_PATH];

	if (GetFullPathName(inf.c_str(), MAX_PATH, inf_path, NULL) >= MAX_PATH)
	{
		return false;
	}

	std::wcerr << "INF file full path: " << inf_path << std::endl;

	bool result = false;

	TCHAR hardware_id_list[LINE_LEN + 4];
	ZeroMemory(hardware_id_list, sizeof(hardware_id_list));

	if (SUCCEEDED(StringCchCopy(hardware_id_list, LINE_LEN, hardware_id.c_str())))
	{
		std::wcerr << "Hardware identifier list: " << hardware_id_list << std::endl;

		GUID class_guid;
		TCHAR class_name[MAX_CLASS_NAME_LEN];

		if (SetupDiGetINFClass(inf_path, &class_guid, class_name, sizeof(class_name) / sizeof(class_name[0]), 0))
		{
			std::wcerr << "Class name: " << class_name << std::endl;

			HDEVINFO device_info_set = INVALID_HANDLE_VALUE;

			device_info_set = SetupDiCreateDeviceInfoList(&class_guid, 0);

			if (device_info_set != INVALID_HANDLE_VALUE)
			{
				std::wcerr << "Device information set created." << std::endl;

				SP_DEVINFO_DATA device_info_data;
				device_info_data.cbSize = sizeof(SP_DEVINFO_DATA);

				if (SetupDiCreateDeviceInfo(device_info_set,
							class_name,
							&class_guid,
							NULL,
							0,
							DICD_GENERATE_ID,
							&device_info_data))
				{
					std::wcerr << "Device information element created." << std::endl;

					if (SetupDiSetDeviceRegistryProperty(device_info_set,
								&device_info_data,
								SPDRP_HARDWAREID,
								(LPBYTE)hardware_id_list,
								(lstrlen(hardware_id_list) + 1 + 1) * sizeof(TCHAR)))
					{
						std::wcerr << "Hardware id set." << std::endl;

						if (SetupDiCallClassInstaller(DIF_REGISTERDEVICE, device_info_set, &device_info_data))
						{
							std::wcerr << "Device registered." << std::endl;

							result = update(inf, hardware_id, reboot_required);
						}
					}
				}

				SetupDiDestroyDeviceInfoList(device_info_set);
			}
		}
	}

	return result;
}
예제 #14
0
LRESULT CALLBACK MainWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	static PCSpotify spotify(nullptr);
	if (spotify == nullptr)
	{
		if ((spotify = new CSpotify) == nullptr)
		{
			return -1;
		}
		spotify->initalize();
	}

	switch (message)
	{
	case WMAPP_NOTIFYCALLBACK:
		switch (lParam)
		{
		case WM_LBUTTONDBLCLK:
			if (spotify != nullptr)
				spotify->pasteSong();
			break;
		case WM_RBUTTONDOWN:
		case WM_CONTEXTMENU:
		{
			POINT pt{};
			GetCursorPos(&pt);
			HMENU hMenu = CreatePopupMenu();
			if (hMenu)
			{
				InsertMenu(hMenu, static_cast<UINT>(-1), MF_BYPOSITION, WMAPP_PASTESONG, _T("Paste song."));
				InsertMenu(hMenu, static_cast<UINT>(-1), MF_BYPOSITION, WMAPP_SETTINGS, _T("Settings"));
				InsertMenu(hMenu, static_cast<UINT>(-1), MF_BYPOSITION, WMAPP_EXIT, _T("Exit"));
				SetForegroundWindow(hWnd);
				TrackPopupMenu(hMenu, TPM_BOTTOMALIGN, pt.x, pt.y, 0, hWnd, NULL);
				DestroyMenu(hMenu);
			}
		}
		default:
			break;
		}
	case WM_CREATE:
	{
		NOTIFYICONDATA nid = { sizeof(nid) };
		nid.hWnd = hWnd;
		nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE | NIF_SHOWTIP;
		nid.uCallbackMessage = WMAPP_NOTIFYCALLBACK;
		nid.hIcon = g_hIcon;
		StringCchCopy(nid.szTip, ARRAYSIZE(nid.szTip), _T("Spotify2PuTTY"));
		Shell_NotifyIcon(NIM_ADD, &nid);
		nid.uVersion = NOTIFYICON_VERSION_4;
		Shell_NotifyIcon(NIM_SETVERSION, &nid);
		RegisterHotKey(hWnd, 0x337, SR_MODIFIERS, SR_KEYS);
		break;
	}
	case WM_HOTKEY:
		if (LOWORD(lParam) == (SR_MODIFIERS) && HIWORD(lParam) == SR_KEYS && spotify != nullptr)
		{
			spotify->pasteSong();
		}
		break;
	case WM_COMMAND:
	{
		int wmId = LOWORD(wParam);
		switch (wmId)
		{
		case WMAPP_PASTESONG:
		{
			if (spotify != nullptr)
				spotify->pasteSong();
			break;
		}
		case WMAPP_SETTINGS:
			// show settings dialog
			DialogBoxParam(g_hInst, MAKEINTRESOURCE(IDD_SETTINGS), hWnd, SettingsWndProc, reinterpret_cast<LPARAM>(spotify));
			break;
		case WMAPP_EXIT:
			PostQuitMessage(0);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
	}
	break;
	case WM_CLOSE:
	case WM_DESTROY:
	{
		if (spotify != nullptr)
			spotify->finalize();
		EndDialog(hWnd, 0);
		break;
	}
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
예제 #15
0
// process image
void Viewer::Update(Png *png1)
{
    struct p2d_globals_struct *p2dg = NULL;
    P2D *p2d = NULL;
    int rv;
    int dens_x, dens_y, dens_units;
    unsigned char tmpr,tmpg,tmpb;
    HCURSOR hcur=NULL;
    int cursor_flag=0;
    struct viewer_read_ctx read_ctx;

    m_errorflag=0;
    FreeImage();

    if(!png1) goto abort;

    if(png1->m_imgtype==IMG_MNG) {
        m_errorflag=1;
        StringCchCopy(m_errormsg,200,_T("Viewer doesn") SYM_RSQUO _T("t support MNG files."));
        goto abort;
    }
    else if(png1->m_imgtype==IMG_JNG) {
        m_errorflag=1;
        StringCchCopy(m_errormsg,200,_T("Viewer doesn") SYM_RSQUO _T("t support JNG files."));
        goto abort;
    }

    hcur=SetCursor(LoadCursor(NULL,IDC_WAIT));
    cursor_flag=1;

    if(!globals.viewer_p2d_globals) {
        globals.viewer_p2d_globals = (void*)p2d_create_globals();
    }
    p2d = p2d_init((p2d_globals_struct*)globals.viewer_p2d_globals);

    png1->stream_file_start();
    p2d_set_png_read_fn(p2d,my_read_fn);

    read_ctx.png = png1;
    p2d_set_userdata(p2d,(void*)&read_ctx);

    p2d_enable_color_correction(p2d, globals.use_gamma?1:0);

    p2d_set_use_file_bg(p2d,globals.use_imagebg?1:0);
    if(globals.use_custombg) {
        p2d_set_custom_bg(p2d,GetRValue(globals.custombgcolor),
                          GetGValue(globals.custombgcolor),GetBValue(globals.custombgcolor));
    }

    rv=p2d_run(p2d);
    if(rv!=PNGD_E_SUCCESS) {
        lstrcpyn(m_errormsg,p2d_get_error_msg(p2d),200);
        m_errorflag=1;
        goto abort;
    }
    rv=p2d_get_dib(p2d,&m_dib);
    m_dib_size = p2d_get_dib_size(p2d);
    rv=p2d_get_dibbits(p2d, &m_bits);

    m_adjwidth = m_dib->biWidth;
    m_adjheight = m_dib->biHeight;

    if(globals.viewer_correct_nonsquare)
        rv=p2d_get_density(p2d, &dens_x, &dens_y, &dens_units);
    else
        rv=0;

    if(rv) {
        if(dens_x!=dens_y && dens_x>0 && dens_y>0 &&
                10*dens_x>dens_y && 10*dens_y>dens_x)
        {
            if(dens_x>dens_y) {
                m_adjheight = (int) (0.5+ (double)m_adjheight * ((double)dens_x/(double)dens_y) );
            }
            else {
                m_adjwidth = (int) (0.5+ (double)m_adjwidth * ((double)dens_y/(double)dens_x) );
            }
        }
    }

    CalcStretchedSize();

    m_imghasbgcolor=0;
    if(p2d_get_bgcolor(p2d,&tmpr,&tmpg,&tmpb)) {
        m_imghasbgcolor=1;
        m_imgbgcolor = RGB(tmpr,tmpg,tmpb);
    }

abort:
    if(p2d) p2d_done(p2d);

    if(m_hwndViewer) {
        InvalidateRect(m_hwndViewer,NULL,TRUE);
    }

    if(cursor_flag) SetCursor(hcur);
}
예제 #16
0
void CAddTracksDialog::OnInitDialog()
{
    if (NULL == m_pModPlaylist)
    {
        PostMessage(m_hwndDlg, WM_COMMAND, IDCANCEL, 0);

        return;
    }

    m_hwndTitle     = GetDlgItem(m_hwndDlg, IDC_ADD_TRACKS);
    m_hwndTrackList = GetDlgItem(m_hwndDlg, IDC_TRACK_LIST);

    //
    // Check to see if the screen is small
    //
    if (g_bSmallScreen)
    {
        RECT rcWorkArea;
        RECT rcWnd, rcList;

        GetWindowRect(m_hwndDlg,       &rcWnd);
        GetWindowRect(m_hwndTrackList, &rcList);

        if (!SystemParametersInfo(SPI_GETWORKAREA, 0, &rcWorkArea, 0))
        {
            HDC hdc = ::GetDC(NULL);

            rcWorkArea.left = 0;
            rcWorkArea.top  = 0;

            rcWorkArea.right  = GetDeviceCaps(hdc, HORZRES);
            rcWorkArea.bottom = GetDeviceCaps(hdc, VERTRES) - GetSystemMetrics(SM_CYMENU);

            ::ReleaseDC(NULL, hdc);
        }

        MoveWindow(m_hwndDlg,
                   rcWorkArea.left,
                   rcWorkArea.top,
                   rcWorkArea.right,
                   rcWorkArea.bottom,
                   TRUE);

        rcWorkArea.left   += rcList.left - rcWnd.left;
        rcWorkArea.right  -= rcList.left - rcWnd.left;
        rcWorkArea.right  += rcList.right - rcWnd.right - 2*GetSystemMetrics(SM_CXDLGFRAME);

        rcWorkArea.top    += rcList.top  - rcWnd.top - GetSystemMetrics(SM_CYCAPTION);
        rcWorkArea.bottom -= rcList.top  - rcWnd.top;
        rcWorkArea.bottom += rcList.bottom - rcWnd.bottom;

        MoveWindow(m_hwndTrackList,
                   rcWorkArea.left,
                   rcWorkArea.top,
                   rcWorkArea.right,
                   rcWorkArea.bottom,
                   TRUE);
    }

    ListView_SetExtendedListViewStyle(m_hwndTrackList, LVS_EX_CHECKBOXES);

    HRESULT hr;

    hr = CreateBars();

    if (FAILED(hr))
    {
        return;
    }

    if (m_himgLocationList)
    {
        ListView_SetImageList(m_hwndTrackList, m_himgLocationList, LVSIL_SMALL);
    }

    TCHAR szTitle[MAX_PATH];

    ULONG cchTitleLength = SendMessage(m_hwndTitle, WM_GETTEXT, MAX_PATH, (LPARAM)szTitle);

    LPCTSTR pszShortName = NULL;

    if (NULL != m_pModPlaylist)
    {
        pszShortName = m_pModPlaylist->GetName();
    }

    if (SUCCEEDED(hr) && NULL != pszShortName)
    {
        // cchTitleLength is the length of the string retrieved by WM_GETTEXT
        // to avoid overrunning szTitle, we limit the copy to the remaining room in the array 
        StringCchCopy(&szTitle[cchTitleLength], MAX_PATH - cchTitleLength, pszShortName);
        szTitle[MAX_PATH - 1] = TEXT('\0');
    }

    SendMessage(m_hwndTitle, WM_SETTEXT, 0, (LPARAM)szTitle);

    LVCOLUMN lvc;

    memset(&lvc, 0, sizeof (lvc));

    lvc.mask = LVCF_FMT;
    lvc.fmt  = LVCFMT_LEFT;

    ListView_InsertColumn(m_hwndTrackList, 0, &lvc);

    lvc.mask     = LVCF_WIDTH | LVCF_FMT | LVCF_SUBITEM;
    lvc.fmt      = LVCFMT_LEFT;
    lvc.iSubItem = 1;
    lvc.cx       = FILENAME_WIDTH;
    ListView_SetColumn(m_hwndTrackList, 0, &lvc);

    UpdateInfo();

    SetFocus(m_hwndTrackList);
}
예제 #17
0
BOOL WiiMouse_DrvUtil_GetDeviceHandle(GUID guidDeviceInterface, PHANDLE hDeviceHandle)
{
    if (guidDeviceInterface==GUID_NULL)
    {
        return TRUE;
    }

    BOOL retval = FALSE;
    BOOL bResult = TRUE;
    HDEVINFO hDeviceInfo;
    SP_DEVINFO_DATA DeviceInfoData;

    SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA pInterfaceDetailData = NULL;

    ULONG requiredLength=0;

    LPTSTR lpDevicePath = NULL;

    DWORD index = 0;

    // Get information about all the installed devices for the specified
    // device interface class.
    hDeviceInfo = SetupDiGetClassDevs( 
        &guidDeviceInterface,
        NULL, 
        NULL,
        DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

    if (hDeviceInfo == INVALID_HANDLE_VALUE) 
    { 
        // ERROR 
        WiiMouse_AddMsg(DERR, "Error SetupDiGetClassDevs: %d\n", GetLastError());
        retval = TRUE;
        goto done;
    }

    //Enumerate all the device interfaces in the device information set.
    DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

    for (index = 0; SetupDiEnumDeviceInfo(hDeviceInfo, index, &DeviceInfoData); index++)
    {
        //Reset for this iteration
        if (lpDevicePath)
        {
            LocalFree(lpDevicePath);
        }
        if (pInterfaceDetailData)
        {
            LocalFree(pInterfaceDetailData);
        }

        deviceInterfaceData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);

        //Get information about the device interface.
        bResult = SetupDiEnumDeviceInterfaces( 
           hDeviceInfo,
           &DeviceInfoData,
           &guidDeviceInterface,
           index, 
           &deviceInterfaceData);

        // Check if last item
        if (GetLastError () == ERROR_NO_MORE_ITEMS)
        {
            break;
        }

        //Check for some other error
        if (!bResult) 
        {
            WiiMouse_AddMsg(DERR,"Error SetupDiEnumDeviceInterfaces: %d\n", GetLastError());
            retval = TRUE;
            goto done;
        }

        //Interface data is returned in SP_DEVICE_INTERFACE_DETAIL_DATA
        //which we need to allocate, so we have to call this function twice.
        //First to get the size so that we know how much to allocate
        //Second, the actual call with the allocated buffer
        
        bResult = SetupDiGetDeviceInterfaceDetail(
            hDeviceInfo,
            &deviceInterfaceData,
            NULL, 0,
            &requiredLength,
            NULL);


        //Check for some other error
        if (!bResult) 
        {
            if ((ERROR_INSUFFICIENT_BUFFER==GetLastError()) && (requiredLength>0))
            {
                //we got the size, allocate buffer
                pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, requiredLength);
                
                if (!pInterfaceDetailData) 
                { 
                    // ERROR 
                    WiiMouse_AddMsg(DERR, "Error allocating memory for the device detail buffer\n");
                    retval = TRUE;
                    goto done;
                }
            }
            else
            {
                WiiMouse_AddMsg(DERR, "Error SetupDiEnumDeviceInterfaces: %d\n", GetLastError());
                retval = TRUE;
                goto done;
            }
        }

        //get the interface detailed data
        pInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

        //Now call it with the correct size and allocated buffer
        bResult = SetupDiGetDeviceInterfaceDetail(
                hDeviceInfo,
                &deviceInterfaceData,
                pInterfaceDetailData,
                requiredLength,
                NULL,
                &DeviceInfoData);
        
        //Check for some other error
        if (!bResult) 
        {
            WiiMouse_AddMsg(DERR, "Error SetupDiGetDeviceInterfaceDetail: %d.\n", GetLastError());
            retval = TRUE;
            goto done;
        }

        //copy device path
                
        size_t nLength = wcslen (pInterfaceDetailData->DevicePath) + 1;  
        lpDevicePath = (TCHAR *) LocalAlloc (LPTR, nLength * sizeof(TCHAR));
        StringCchCopy(lpDevicePath, nLength, pInterfaceDetailData->DevicePath);
        lpDevicePath[nLength-1] = 0;
                        
        WiiMouse_AddMsg(DINFO, "Device path:  %S\n", lpDevicePath);

    }

    if (!lpDevicePath)
    {
        //Error.
        WiiMouse_AddMsg(DERR, "Error, null device file path: %d\n", GetLastError());
        retval = TRUE;
        goto done;
    }

    //Open the device
    *hDeviceHandle = CreateFile (
        lpDevicePath,
        GENERIC_READ | GENERIC_WRITE,
        FILE_SHARE_READ | FILE_SHARE_WRITE,
        NULL,
        OPEN_EXISTING,
        FILE_FLAG_OVERLAPPED,
        NULL);

    if (*hDeviceHandle == INVALID_HANDLE_VALUE)
    {
        //Error.
        WiiMouse_AddMsg(DERR, "CreateFile: INVALID_HANDLE_VALUE Error %d\n", GetLastError());
        retval = TRUE;
        goto done;
    }



done:
    LocalFree(lpDevicePath);
    LocalFree(pInterfaceDetailData);    
    
    if( !SetupDiDestroyDeviceInfoList(hDeviceInfo) )
    {
        WiiMouse_AddMsg(DERR, "SetupDiDestroyDeviceInfoList failed\n");
        retval = TRUE;
    }
    
    return retval;
}
CWildcardSelectDialogPersistentSettings::CWildcardSelectDialogPersistentSettings() :
CDialogSettings(SETTINGS_KEY)
{
	StringCchCopy(m_szPattern,SIZEOF_ARRAY(m_szPattern),EMPTY_STRING);
}
예제 #19
0
int _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA ffd;
   LARGE_INTEGER filesize;
   FILETIME ftWrite;

   TCHAR szDir[MAX_PATH];
   size_t length_of_arg;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;
   //
   /*
   FILETIME ftCreate, ftAccess, ftWrite;
   SYSTEMTIME stUTC, stLocal;
   DWORD dwRet;

    // Convert the last-write time to local time.
    FileTimeToSystemTime(&ftWrite, &stUTC);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);

    // Build a string showing the date and time.
    dwRet = StringCchPrintf(lpszString, dwSize, 
        TEXT("%02d/%02d/%d  %02d:%02d"),
        stLocal.wMonth, stLocal.wDay, stLocal.wYear,
        stLocal.wHour, stLocal.wMinute);
	*/
   
   // If the directory is not specified as a command-line argument,
   // print usage.

   if(argc != 2)
   {
      _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
      return (-1);
   }

   // Check that the input path plus 2 is not longer than MAX_PATH.

   StringCchLength(argv[1], MAX_PATH, &length_of_arg);

   if (length_of_arg > (MAX_PATH - 2))
   {
      _tprintf(TEXT("\nDirectory path is too long.\n"));
      return (-1);
   }

   _tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);

   // Prepare string for use with FindFile functions.  First, copy the
   // string to a buffer, then append '\*' to the directory name.

   StringCchCopy(szDir, MAX_PATH, argv[1]);
   StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

   // Find the first file in the directory.

   hFind = FindFirstFile(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
      return dwError;
   } 
   
   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
		// List all dirs inside the directory
         _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
      }
      else
      {
         // List all files inside the directory
		 filesize.LowPart = ffd.nFileSizeLow;
         filesize.HighPart = ffd.nFileSizeHigh;
		 ftWrite = ffd.ftLastWriteTime;
		 //
         _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);
 
   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
   }

   FindClose(hFind);
   return dwError;
}
예제 #20
0
void
NamedPipeServer::run()
{
   DWORD i, dwWait, cbRet, dwErr;
   BOOL fSuccess;
   QByteArray response;

   std::string s;
   DWORD r = scrobSubPipeName( &s );
   if (r != 0) throw std::runtime_error( formatWin32Error( r ) );
   QString const name = QString::fromStdString( s );

// The initial loop creates several instances of a named pipe
// along with an event object for each instance.  An
// overlapped ConnectNamedPipe operation is started for
// each instance.

   for (i = 0; i < INSTANCES; i++)
   {

   // Create an event object for this instance.

      hEvents[i] = CreateEvent(
         NULL,    // default security attribute
         TRUE,    // manual-reset event
         TRUE,    // initial state = signaled
         NULL);   // unnamed event object

      if (hEvents[i] == NULL)
      {
         printf("CreateEvent failed with %d.\n", GetLastError());
         return;
      }

      Pipe[i].oOverlap.hEvent = hEvents[i];

      Pipe[i].hPipeInst = CreateNamedPipe(
         (const wchar_t *)name.utf16(),            // pipe name
         PIPE_ACCESS_DUPLEX |     // read/write access
         FILE_FLAG_OVERLAPPED,    // overlapped mode
         PIPE_TYPE_MESSAGE |      // message-type pipe
         PIPE_READMODE_MESSAGE |  // message-read mode
         PIPE_WAIT,               // blocking mode
         INSTANCES,               // number of instances
         BUFSIZE*sizeof(TCHAR),   // output buffer size
         BUFSIZE*sizeof(TCHAR),   // input buffer size
         PIPE_TIMEOUT,            // client time-out
         NULL);                   // default security attributes

      if (Pipe[i].hPipeInst == INVALID_HANDLE_VALUE)
      {
         printf("CreateNamedPipe failed with %d.\n", GetLastError());
         return;
      }

   // Call the subroutine to connect to the new client

      Pipe[i].fPendingIO = ConnectToNewClient(
         Pipe[i].hPipeInst,
         &Pipe[i].oOverlap);

      Pipe[i].dwState = Pipe[i].fPendingIO ?
         CONNECTING_STATE : // still connecting
         READING_STATE;     // ready to read
   }

   while (1)
   {
   // Wait for the event object to be signaled, indicating
   // completion of an overlapped read, write, or
   // connect operation.

      dwWait = WaitForMultipleObjects(
         INSTANCES,    // number of event objects
         hEvents,      // array of event objects
         FALSE,        // does not wait for all
         INFINITE);    // waits indefinitely

   // dwWait shows which pipe completed the operation.

      i = dwWait - WAIT_OBJECT_0;  // determines which pipe
      if (i < 0 || i > (INSTANCES - 1))
      {
         printf("Index out of range.\n");
         return;
      }

   // Get the result if the operation was pending.

      if (Pipe[i].fPendingIO)
      {
         fSuccess = GetOverlappedResult(
            Pipe[i].hPipeInst, // handle to pipe
            &Pipe[i].oOverlap, // OVERLAPPED structure
            &cbRet,            // bytes transferred
            FALSE);            // do not wait

         switch (Pipe[i].dwState)
         {
         // Pending connect operation
            case CONNECTING_STATE:
               if (! fSuccess)
               {
                   printf("Error %d.\n", GetLastError());
                   return;
               }
               Pipe[i].dwState = READING_STATE;
               break;

         // Pending read operation
            case READING_STATE:
               if (! fSuccess || cbRet == 0)
               {
                  DisconnectAndReconnect(i);
                  continue;
               }
               Pipe[i].cbRead = cbRet;
               Pipe[i].dwState = WRITING_STATE;
               break;

         // Pending write operation
            case WRITING_STATE:
               if (! fSuccess || cbRet != Pipe[i].cbToWrite)
               {
                  DisconnectAndReconnect(i);
                  continue;
               }
               Pipe[i].dwState = READING_STATE;
               break;

            default:
            {
               printf("Invalid pipe state.\n");
               return;
            }
         }
      }

   // The pipe state determines which operation to do next.

      switch (Pipe[i].dwState)
      {
      // READING_STATE:
      // The pipe instance is connected to the client
      // and is ready to read a request from the client.

         case READING_STATE:
            fSuccess = ReadFile(
               Pipe[i].hPipeInst,
               Pipe[i].chRequest,
               BUFSIZE*sizeof(TCHAR),
               &Pipe[i].cbRead,
               &Pipe[i].oOverlap);

         // The read operation completed successfully.

            if (fSuccess && Pipe[i].cbRead != 0)
            {
               Pipe[i].fPendingIO = FALSE;
               Pipe[i].dwState = WRITING_STATE;
               continue;
            }

         // The read operation is still pending.

            dwErr = GetLastError();
            if (! fSuccess && (dwErr == ERROR_IO_PENDING))
            {
               Pipe[i].fPendingIO = TRUE;
               continue;
            }

         // An error occurred; disconnect from the client.

            DisconnectAndReconnect(i);
            break;

      // WRITING_STATE:
      // The request was successfully read from the client.
      // Get the reply data and write it to the client.

         case WRITING_STATE:
            response = emit lineReady( QString::fromUtf8( (char*)Pipe[i].chRequest, Pipe[i].cbRead ) ).toUtf8();
            StringCchCopy( Pipe[i].chReply, BUFSIZE, (LPCTSTR)response.data() );
            Pipe[i].cbToWrite = response.size();

            fSuccess = WriteFile(
               Pipe[i].hPipeInst,
               Pipe[i].chReply,
               Pipe[i].cbToWrite,
               &cbRet,
               &Pipe[i].oOverlap);

         // The write operation completed successfully.

            if (fSuccess && cbRet == Pipe[i].cbToWrite)
            {
               Pipe[i].fPendingIO = FALSE;
               Pipe[i].dwState = READING_STATE;
               continue;
            }

         // The write operation is still pending.

            dwErr = GetLastError();
            if (! fSuccess && (dwErr == ERROR_IO_PENDING))
            {
               Pipe[i].fPendingIO = TRUE;
               continue;
            }

         // An error occurred; disconnect from the client.

            DisconnectAndReconnect(i);
            break;

         default:
         {
            printf("Invalid pipe state.\n");
            return;
         }
      }
  }
}
예제 #21
0
XN_C_API XnStatus xnUSBEnumerateDevices(XnUInt16 nVendorID, XnUInt16 nProductID, const XnUSBConnectionString** pastrDevicePaths, XnUInt32* pnCount)
{
	// Local variables
	XnStatus nRetVal = XN_STATUS_OK;

	// support up to 30 devices
	XnUSBConnectionString cpUSBID;
	XnUSBConnectionString cpUSBPathCmp;
	XnUSBConnectionString aNames[MAX_POTENTIAL_DEVICES];
	HDEVINFO hDevInfo = NULL;
	ULONG nDevices = 0;
	XnUInt32 nFoundDevices = 0;
	SP_DEVICE_INTERFACE_DATA devInterfaceData;
	XnBool bReachedEnd = FALSE;

	// Validate xnUSB
	XN_VALIDATE_USB_INIT();

	LPCGUID pInterfaceGuid = &GUID_CLASS_PSDRV_USB;

	// See if the driver is installed
	hDevInfo = SetupDiGetClassDevs (pInterfaceGuid, NULL, NULL, (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
	if (hDevInfo == INVALID_HANDLE_VALUE)
	{
		// No devices are present...
		return (XN_STATUS_USB_DRIVER_NOT_FOUND);
	}

	// Scan the hardware for any devices that are attached to our driver.
	devInterfaceData.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);

	while (nDevices < MAX_POTENTIAL_DEVICES)
	{
		// Get information about the device
		if (SetupDiEnumDeviceInterfaces(hDevInfo, 0, pInterfaceGuid, nDevices, &devInterfaceData))
		{
			PSP_DEVICE_INTERFACE_DETAIL_DATA pDevInterfaceDetailData = NULL;
			ULONG nPredictedLength = 0;
			ULONG nRequiredLength = 0;

			// Probe how much memory is needed to read the device info
			SetupDiGetDeviceInterfaceDetail(hDevInfo, &devInterfaceData, NULL, 0, &nRequiredLength, NULL);

			// Allocate memory for the device info
			nPredictedLength = nRequiredLength;

			pDevInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(nPredictedLength);
			if(pDevInterfaceDetailData == NULL)
			{
				// Not enough memory...
				return XN_STATUS_ALLOC_FAILED;
			}

			// Read the device info
			pDevInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
			if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, &devInterfaceData, pDevInterfaceDetailData, nPredictedLength, &nRequiredLength, NULL))
			{
				// Something bad has happened...
				free(pDevInterfaceDetailData);
				return XN_STATUS_ERROR;
			}

			// Make sure we have the right VID/PID
			cpUSBID[0] = 0;
			sprintf_s (cpUSBID, "vid_%04x&pid_%04x", nVendorID, nProductID);
			
			cpUSBPathCmp[0] = 0;
			StringCchCopy(cpUSBPathCmp, MAX_DEVICE_STR_LENGTH, pDevInterfaceDetailData->DevicePath);

			if (strstr(_strlwr(cpUSBPathCmp), cpUSBID) != 0)
			{
				StringCchCopy(aNames[nFoundDevices], MAX_DEVICE_STR_LENGTH, pDevInterfaceDetailData->DevicePath);

				++nFoundDevices;
			}

			++nDevices;
		}
		else if (ERROR_NO_MORE_ITEMS == GetLastError())
		{
			// no more devices
			bReachedEnd = TRUE;
			break;
		}
	}

	SetupDiDestroyDeviceInfoList(hDevInfo);

	if (!bReachedEnd)
	{
		// we probably passed our limit
		XN_LOG_ERROR_RETURN(XN_STATUS_ERROR, XN_MASK_USB, "Found more than %d devices! This is not supported.", MAX_POTENTIAL_DEVICES);
	}

	XnUSBConnectionString* pNames;
	XN_VALIDATE_CALLOC(pNames, XnUSBConnectionString, nFoundDevices);
	xnOSMemCopy(pNames, aNames, sizeof(XnUSBConnectionString) * nFoundDevices);

	*pastrDevicePaths = pNames;
	*pnCount = nFoundDevices;

	// All is good...
	return (XN_STATUS_OK);
}
예제 #22
0
파일: neo_files.c 프로젝트: aruiz14/hhvm
NEOERR *ne_listdir_fmatch(const char *path, ULIST **files, MATCH_FUNC fmatch,
                          void *rock)
{
  NEOERR *err = STATUS_OK;
  ULIST *myfiles = NULL;

  if (files == NULL)
    return nerr_raise(NERR_ASSERT, "Invalid call to ne_listdir_fmatch");

  if (*files == NULL)
  {
    err = uListInit(&myfiles, 10, 0);
    if (err) return nerr_pass(err);
  }
  else
  {
    myfiles = *files;
  }

#ifdef _MSC_VER
  HANDLE hFind = INVALID_HANDLE_VALUE;
  WIN32_FIND_DATA ffd;
  CHAR rootDir[MAX_PATH];

  StringCchCopy(rootDir, MAX_PATH, path);
  StringCchCat(rootDir, MAX_PATH, TEXT("\\*"));
  hFind = FindFirstFile(rootDir, &ffd);
  if (hFind == INVALID_HANDLE_VALUE)
    return nerr_raise_errno(NERR_IO, "Unable to opendir %s", path);

  do {
    if (!strcmp(ffd.cFileName, ".") || !strcmp(ffd.cFileName, ".."))
      continue;

    if (fmatch != NULL && !fmatch(rock, ffd.cFileName))
      continue;

    err = uListAppend(myfiles, strdup(ffd.cFileName));
    if (err) break;
  } while (FindNextFile(hFind, &ffd) != 0);

  FindClose(hFind);
#else
  DIR *dp;
  struct dirent *de;
  if ((dp = opendir (path)) == NULL)
  {
    return nerr_raise_errno(NERR_IO, "Unable to opendir %s", path);
  }
  while ((de = readdir (dp)) != NULL)
  {
    if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
      continue;

    if (fmatch != NULL && !fmatch(rock, de->d_name))
      continue;

    err = uListAppend(myfiles, strdup(de->d_name));
    if (err) break;
  }
  closedir(dp);
#endif
  if (err && *files == NULL)
  {
    uListDestroy(&myfiles, ULIST_FREE);
  }
  else if (*files == NULL)
  {
    *files = myfiles;
  }
  return nerr_pass(err);
}
예제 #23
0
int opzoekingWG(HWND hW, HANDLE heap_van_proces, LPCTSTR gemeente, LPCTSTR straat, LPCTSTR huisnr, ADRES **adressen, CHAR debug)
{
	/*opkuis gevraagd?*/
	if(gemeente[0] == TEXT('\0'))
	{
		if(debug)
			fprintf(stderr, "-> ZWG: opkuisaanvraag ontvangen\n");
		DeleteFile(TEXT("wittegids.be.html"));
		return 0;
	}
	/*EINDE opkuis gevraagd?*/

	/* html-bestand van wittegids.be downloaden */	//normaal wordt op de URL '%'-encodering toegepast, maar na tests blijkt dit niet noodzakelijk te zijn	(getest op http://wittegids.be/q/name/address/where/Heist-op-den-Berg/street/Livinus Carr象at/nr/22)
	int aantal=0, i;
	StringCchLength(gemeente, STRSAFE_MAX_CCH, (unsigned int *)&i);
	aantal += i;
	StringCchLength(straat, STRSAFE_MAX_CCH, (unsigned int *)&i);
	aantal += i;
	StringCchLength(huisnr, STRSAFE_MAX_CCH, (unsigned int *)&i);
	aantal += i;
	TCHAR url[57+aantal+1];
	#if (defined UNICODE)||(defined _UNICODE)
	if(FAILED(StringCchPrintf(url, 57+aantal+1+1, L"http://www.wittegids.be/q/name/address/where/%ls/street/%ls/nr/%ls", gemeente, straat, huisnr)))	//URL samenstellen //++ om een onbekende reden mist StringCchPrintf het overzetten van het laatste karakter (zonder fout te geven), dit in tegenstelling tot sprintf_s onder dezelfde omstandigheden
	#else
	if(FAILED(StringCchPrintf(url, 57+aantal+1+1, "http://www.wittegids.be/q/name/address/where/%s/street/%s/nr/%s", gemeente, straat, huisnr)))
	#endif
	{
		*adressen = NULL;
		return ZWG_BUG_1;
	}

	HANDLE *hhtml;
	do
	{
		if((URLDownloadToFile(NULL, url, TEXT("wittegids.be.html"), 0, NULL) != S_OK)||(hhtml = CreateFile(TEXT("wittegids.be.html"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), hhtml == INVALID_HANDLE_VALUE))
		{
			aantal = 0;
			StringCchLength(gemeente, STRSAFE_MAX_CCH, (unsigned int *)&i);
			aantal += i;
			StringCchLength(straat, STRSAFE_MAX_CCH, (unsigned int *)&i);
			aantal += i;
			StringCchLength(huisnr, STRSAFE_MAX_CCH, (unsigned int *)&i);
			aantal += i;
			StringCchLength(url, STRSAFE_MAX_CCH, (unsigned int *)&i);
			aantal += i;
			TCHAR temp[231+aantal+1];
			#if (defined UNICODE)||(defined _UNICODE)
			StringCchPrintf(temp, 231+aantal+1, L"De gegevens %ls, %ls en %ls werden omgevormd tot %ls.\n\nEr deed zich een probleem voor met het verkrijgen van deze pagina.\nMogelijke oorzaken zijn:\n- Geen internetverbinding\n- Fout gespeld adres\n\nOpnieuw proberen of dit adres overslaan?", gemeente, straat, huisnr, url);
			#else
			StringCchPrintf(temp, 231+aantal+1, "De gegevens %s, %s en %s werden omgevormd tot %s.\n\nEr deed zich een probleem voor met het verkrijgen van deze pagina.\nMogelijke oorzaken zijn:\n- Geen internetverbinding\n- Fout gespeld adres\n\nOpnieuw proberen of dit adres overslaan?", gemeente, straat, huisnr, url);
			#endif
			aantal = MessageBox(hW, temp, TEXT("opzoekingWG - Fout"), MB_RETRYCANCEL | MB_ICONWARNING | MB_SETFOREGROUND);
		}
		else
			break;
		if(aantal == IDCANCEL)
		{
			*adressen = NULL;
			if(hhtml != INVALID_HANDLE_VALUE)
				CloseHandle(hhtml);
			return ZWG_NOT_DOWNLOADED;
		}
	} while(aantal == IDRETRY);
	/* EINDE download html-bestand */

	LARGE_INTEGER startdata, eindedata;
	eindedata.QuadPart = 150;
	/*bestaat adres in Witte Gids?*/
	if(!SetFPByStr(hhtml, TEXT("503 Service Temporarily Unavailable"), &eindedata, NULL))	//controleer op 503-serverfout
	{
		*adressen = NULL;
		CloseHandle(hhtml);
		return ZWG_SERVER_UNAVAILABLE;
	}
	if(!SetFPByStr(hhtml, TEXT("Er werden geen resultaten gevonden voor "), NULL, NULL))	//controleer of resultaten zijn gevonden volgens de Witte Gids
	{
		*adressen = NULL;
		CloseHandle(hhtml);
		if(debug)
			fprintf(stderr, "-> ZWG: wittegids.be.html geeft \'Er werden geen resultaten gevonden voor \'.\n");
		return ZWG_ADDRESS_NOT_IN_WG;
	}
	if(!SetFPByStr(hhtml, TEXT("Uw zoekopdracht voor het adres "), NULL, NULL))	//controleer of resultaten zijn gevonden volgens de Witte Gids
	{
		*adressen = NULL;
		CloseHandle(hhtml);
		if(debug)
			fprintf(stderr, "-> ZWG: wittegids.be.html geeft \'Uw zoekopdracht voor het adres \'.\n");
		return ZWG_ADDRESS_NOT_IN_WG;
	}
	if(SetFPByStr(hhtml, TEXT("truvo.data['raw']="), NULL, &startdata))	//zet in startdata het begin van de data
	{
		if(debug)
			fprintf(stderr, "-> ZWG: \'truvo.data['raw']=\' niet gevonden in wittegids.be.html.\n");
		*adressen = NULL;
		CloseHandle(hhtml);
		return ZWG_ADDRESS_NOT_IN_WG;
	}
	/*EINDE bestaanscontrole*/

	/*alle relevante gegevens opnemen in geheugen*/
	SetFPByStr(hhtml, TEXT(";truvo.data"), NULL, &eindedata);	//zet in eindedata waar de data stopt
	CHAR *data = HeapAlloc(heap_van_proces, 0, eindedata.QuadPart);
	CHAR *data_begin = data;
	if(data == NULL)
	{
		*adressen = NULL;
		return ZWG_MEMORY_ERROR;
	}
	DWORD b;
	SetFilePointerEx(hhtml, startdata, NULL, FILE_BEGIN);
	ReadFile(hhtml, data, eindedata.QuadPart, &b, NULL);
	CloseHandle(hhtml);
	if(b == 0)
	{
		*adressen = NULL;
		HeapFree(heap_van_proces, 0, data_begin);
		return ZWG_READ_ERROR;
	}
	data[b-1] = '\0';
	/*EINDE gegevens opnemen*/
	if(debug)
		fprintf(stderr, "-> ZWG: data = \'%s\'.\n", data);
	/*aantal telefoonnummers bepalen*/
	{
	CHAR *temp = data;
	for(aantal=0; temp = StrStrA(temp, "phone\":"), temp != NULL; ++aantal, ++temp);	//bepaal het aantal telefoonnummers
	if(aantal == 0)	//geen telefoonnummers
	{
		*adressen = NULL;
		HeapFree(heap_van_proces, 0, data_begin);
		return ZWG_TELEPHONE_NOT_IN_WG;
	}
	}
	/*EINDE bepaal aantal telefoonnummers*/

	/*maak array van door te geven ADRES*/
	ADRES *Padressen = HeapAlloc(heap_van_proces, 0, aantal*sizeof(ADRES));
	if(Padressen == NULL)
	{
		*adressen = NULL;
		HeapFree(heap_van_proces, 0, data_begin);
		return ZWG_MEMORY_ERROR;
	}
	/*EINDE array maken*/

	CHAR dummy[ZWG_MAX_ALL];
	/*GEMEENTENAAM OPNEMEN*/
	if(StrStrA(data, "city\":\"") == NULL)
	{
		*adressen = NULL;
		HeapFree(heap_van_proces, 0, data_begin);
		HeapFree(heap_van_proces, 0, Padressen);
		return ZWG_ADDRESS_NOT_IN_WG;
	}
	{
	CHAR *temp = StrStrA(data, "city\":\"") + sizeof("city\":\"") - 1;
	for(i=0; dummy[i] = temp[i], (dummy[i] != '\"')&&(i < ZWG_MAX_GEMEENTE-1); ++i);
	}
	if(i == ZWG_MAX_GEMEENTE-1)
		dummy[i-1] = '_';
	dummy[i] = '\0';
//	UnicodeStr4CodeToUTF8Str(dummy); //getest op http://www.wittegids.be/q/name/address/where/bierbeek/street/oude%20baan/nr/157
	#if (defined UNICODE)||(defined _UNICODE)
	MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, dummy, -1, Padressen[0].gemeente, ZWG_MAX_GEMEENTE);
	#else
	StringCchCopy(Padressen[aantal].gemeente, ZWG_MAX_GEMEENTE, dummy);
	#endif
	
	/*STRAATNAAM OPNEMEN*/
	if(StrStrA(data, "street\":\"") == NULL)
	{
		*adressen = NULL;
		HeapFree(heap_van_proces, 0, data_begin);
		HeapFree(heap_van_proces, 0, Padressen);
		return ZWG_ADDRESS_NOT_IN_WG;
	}
	{
	CHAR *temp = StrStrA(data, "street\":\"") + sizeof("street\":\"") - 1;
	for(i=0; dummy[i] = temp[i], ((dummy[i] < '0')||(dummy[i] > '9'))&&(dummy[i] != '\"')&&(i < ZWG_MAX_STRAAT-1); ++i);
	}
	if(i == ZWG_MAX_STRAAT-1)
		dummy[i-2] = '_';
	dummy[i-1] = '\0';
//	UnicodeStr4CodeToUTF8Str(dummy); //getest op http://www.wittegids.be/q/name/address/where/bierbeek/street/oude%20baan/nr/157
	#if (defined UNICODE)||(defined _UNICODE)
	MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, dummy, -1, Padressen[0].straat, ZWG_MAX_STRAAT);
	#else
	StringCchCopy(Padressen[aantal].straat, ZWG_MAX_STRAAT, dummy);
	#endif

	for(aantal=0; data = StrStrA(data, "phone\":\"") + sizeof("phone\":\"") - 1, (unsigned int)data != sizeof("phone\":\"") - 1; ++aantal)
	{
		/*TELEFOONNUMMER OPNEMEN*/
		for(i=0; dummy[i] = data[i], (dummy[i] != '\"')&&(i < ZWG_MAX_TELEFOON-1); ++i);
		if((i == 0)&&(StrStrA(data, "mobile\":\"") != NULL))	//als er geen telefoonnummer is: mobiel telefoonnummer
		{
			data = StrStrA(data, "mobile\":\"") + sizeof("mobile\":\"") - 1;
			for(i=0; dummy[i] = data[i], (dummy[i] != '\"')&&(i < ZWG_MAX_TELEFOON-1); ++i);
		}
		if((i == 0)||((i == ZWG_MAX_TELEFOON-1)&&(dummy[i] != '\"')))	//geen of ongeldig telefoonnummer
			goto NEGEREN;
		dummy[i] = '\0';
		#if (defined UNICODE)||(defined _UNICODE)
		MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, dummy, -1, Padressen[aantal].telefoonnr, ZWG_MAX_TELEFOON);
		#else
		StringCchCopy(Padressen[aantal].telefoonnr, ZWG_MAX_TELEFOON, dummy);
		#endif

		/*NAAM OPNEMEN*/
		if(StrStrA(data, "name\":\"") == NULL)
			goto NEGEREN;
		data = StrStrA(data, "name\":\"") + sizeof("name\":\"") - 1;
		for(i=0; dummy[i] = data[i], (dummy[i] != '\"')&&(i < ZWG_MAX_NAAM-1); ++i);
		if((i == ZWG_MAX_NAAM-1)&&(dummy[i] != '\"'))
			dummy[i-1] = '_';
		dummy[i] = '\0';
//		UnicodeStr4CodeToUTF8Str(dummy); //getest op http://www.wittegids.be/q/name/address/where/bierbeek/street/oude%20baan/nr/157
		#if (defined UNICODE)||(defined _UNICODE)
		MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, dummy, -1, Padressen[aantal].naam, ZWG_MAX_NAAM);
		#else
		StringCchCopy(Padressen[aantal].naam, ZWG_MAX_NAAM, dummy);
		#endif

		/*STRAATNAAM OVERSLAAN*/
		if(StrStrA(data, "street\":\"") == NULL)
			goto NEGEREN;
		data = StrStrA(data, "street\":\"") + sizeof("street\":\"") - 1;
		for(++data; ((data[0] < '0')||(data[0] > '9'))&&(data[0] != '\"'); ++data);
		if(data[0] == '\"')	//adres zonder huisnummer
			goto NEGEREN;

		/*HUISNUMMER OPNEMEN*/
		for(i=0; dummy[i] = data[i], (dummy[i] != '\"')&&(i < ZWG_MAX_HUISNUMMER-1); ++i);
		dummy[i] = '\0';
		#if (defined UNICODE)||(defined _UNICODE)
		MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, dummy, -1, Padressen[aantal].huisnr, ZWG_MAX_HUISNUMMER);
		#else
		StringCchCopy(Padressen[aantal].huisnr, ZWG_MAX_HUISNUMMER, dummy);
		#endif

		/*CONTROLE of huisnummer van het adres overeenkomt met dat in de Witte Gids*/
		for(i=0; (Padressen[aantal].huisnr[i] != TEXT(' '))&&(Padressen[aantal].huisnr[i] != TEXT('\0')); ++i)
		{
			if(Padressen[aantal].huisnr[i] != huisnr[i])
				break;
		}
		if(((Padressen[aantal].huisnr[i] != TEXT(' '))&&(Padressen[aantal].huisnr[i] != TEXT('\0')))||(huisnr[i] != TEXT('\0')))
			goto NEGEREN;

		/*CONTROLE of combinatie telefoonnummer en naam al gevonden is*/
		for(i=0; i < aantal; ++i)
		{
			if((!StrCmp(Padressen[i].telefoonnr, Padressen[aantal].telefoonnr))&&(!StrCmp(Padressen[i].naam, Padressen[aantal].naam)))
				goto NEGEREN;
		}
		StringCchCopy(Padressen[aantal].gemeente, ZWG_MAX_GEMEENTE, Padressen[0].gemeente);
		StringCchCopy(Padressen[aantal].straat, ZWG_MAX_STRAAT, Padressen[0].straat);
		goto AANNEMEN;

		NEGEREN:
		aantal--;
		AANNEMEN:;
	}
	HeapFree(heap_van_proces, 0, data_begin);
	if(aantal == 0)
	{
		*adressen = NULL;
		HeapFree(heap_van_proces, 0, Padressen);
		return ZWG_TELEPHONE_NOT_IN_WG;
	}
	Padressen = HeapReAlloc(heap_van_proces, 0, Padressen, aantal*sizeof(ADRES));	//verkleint het nodige geheugen in geval van niet-opgenomen elementen
	*adressen = Padressen;
	return aantal;
}
예제 #24
0
static const blissbox_pad_type_t* input_autoconfigure_get_blissbox_pad_type_win32(int vid, int pid)
{
   /* TODO: Remove the check for !defined(_MSC_VER) after making sure this builds on MSVC */

   /* HID API is available since Windows 2000 */
#if defined(_WIN32) && !defined(_XBOX) && !defined(_MSC_VER) && _WIN32_WINNT >= 0x0500
   HDEVINFO hDeviceInfo;
   SP_DEVINFO_DATA DeviceInfoData;
   SP_DEVICE_INTERFACE_DATA deviceInterfaceData;
   HANDLE hDeviceHandle                 = INVALID_HANDLE_VALUE;
   BOOL bResult                         = TRUE;
   BOOL success                         = FALSE;
   GUID guidDeviceInterface             = {0};
   PSP_DEVICE_INTERFACE_DETAIL_DATA
      pInterfaceDetailData              = NULL;
   ULONG requiredLength                 = 0;
   LPTSTR lpDevicePath                  = NULL;
   char *devicePath                     = NULL;
   DWORD index                          = 0;
   DWORD intIndex                       = 0;
   size_t nLength                       = 0;
   unsigned len                         = 0;
   unsigned i                           = 0;
   char vidPidString[32]                = {0};
   char vidString[5]                    = {0};
   char pidString[5]                    = {0};
   char report[USB_PACKET_CTRL_LEN + 1] = {0};

   snprintf(vidString, sizeof(vidString), "%04x", vid);
   snprintf(pidString, sizeof(pidString), "%04x", pid);

   strlcat(vidPidString, "vid_", sizeof(vidPidString));
   strlcat(vidPidString, vidString, sizeof(vidPidString));
   strlcat(vidPidString, "&pid_", sizeof(vidPidString));
   strlcat(vidPidString, pidString, sizeof(vidPidString));

   HidD_GetHidGuid(&guidDeviceInterface);

   if (!memcmp(&guidDeviceInterface, &GUID_NULL, sizeof(GUID_NULL)))
   {
     RARCH_ERR("[Autoconf]: null guid\n");
     return NULL;
   }

   /* Get information about all the installed devices for the specified
    * device interface class.
    */
   hDeviceInfo = SetupDiGetClassDevs(
    &guidDeviceInterface,
    NULL,
    NULL,
    DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);

   if (hDeviceInfo == INVALID_HANDLE_VALUE)
   {
      RARCH_ERR("[Autoconf]: Error in SetupDiGetClassDevs: %d.\n",
            GetLastError());
      goto done;
   }

   /* Enumerate all the device interfaces in the device information set. */
   DeviceInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

   while (!success)
   {
      success = SetupDiEnumDeviceInfo(hDeviceInfo, index, &DeviceInfoData);

      /* Reset for this iteration */
      if (lpDevicePath)
      {
         LocalFree(lpDevicePath);
         lpDevicePath = NULL;
      }

      if (pInterfaceDetailData)
      {
         LocalFree(pInterfaceDetailData);
         pInterfaceDetailData = NULL;
      }

      /* Check if this is the last item */
      if (GetLastError() == ERROR_NO_MORE_ITEMS)
         break;

      deviceInterfaceData.cbSize = sizeof(SP_INTERFACE_DEVICE_DATA);

      /* Get information about the device interface. */
      for (intIndex = 0; (bResult = SetupDiEnumDeviceInterfaces(
         hDeviceInfo,
         &DeviceInfoData,
         &guidDeviceInterface,
         intIndex,
         &deviceInterfaceData)); intIndex++)
      {
         /* Check if this is the last item */
         if (GetLastError() == ERROR_NO_MORE_ITEMS)
            break;

         /* Check for some other error */
         if (!bResult)
         {
            RARCH_ERR("[Autoconf]: Error in SetupDiEnumDeviceInterfaces: %d.\n", GetLastError());
            goto done;
         }

         /* Interface data is returned in SP_DEVICE_INTERFACE_DETAIL_DATA
          * which we need to allocate, so we have to call this function twice.
          * First to get the size so that we know how much to allocate, and
          * second to do the actual call with the allocated buffer.
          */

         bResult = SetupDiGetDeviceInterfaceDetail(
            hDeviceInfo,
            &deviceInterfaceData,
            NULL, 0,
            &requiredLength,
            NULL);

         /* Check for some other error */
         if (!bResult)
         {
            if ((ERROR_INSUFFICIENT_BUFFER == GetLastError()) && (requiredLength > 0))
            {
               /* we got the size, now allocate buffer */
               pInterfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)LocalAlloc(LPTR, requiredLength);

               if (!pInterfaceDetailData)
               {
                  RARCH_ERR("[Autoconf]: Error allocating memory for the device detail buffer.\n");
                  goto done;
               }
            }
            else
            {
               RARCH_ERR("[Autoconf]: Other error: %d.\n", GetLastError());
               goto done;
            }
         }

         /* get the interface detailed data */
         pInterfaceDetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

         /* Now call it with the correct size and allocated buffer */
         bResult = SetupDiGetDeviceInterfaceDetail(
            hDeviceInfo,
            &deviceInterfaceData,
            pInterfaceDetailData,
            requiredLength,
            NULL,
            &DeviceInfoData);

         /* Check for some other error */
         if (!bResult)
         {
           RARCH_LOG("[Autoconf]: Error in SetupDiGetDeviceInterfaceDetail: %d.\n", GetLastError());
           goto done;
         }

         /* copy device path */
         nLength      = _tcslen(pInterfaceDetailData->DevicePath) + 1;
         lpDevicePath = (TCHAR*)LocalAlloc(LPTR, nLength * sizeof(TCHAR));

         StringCchCopy(lpDevicePath, nLength, pInterfaceDetailData->DevicePath);

         devicePath   = (char*)malloc(nLength);

         for (len = 0; len < nLength; len++)
            devicePath[len] = lpDevicePath[len];

         lpDevicePath[nLength - 1] = 0;

         if (strstr(devicePath, vidPidString))
            goto found;
      }

      success = FALSE;
      index++;
   }

   if (!lpDevicePath)
   {
      RARCH_ERR("[Autoconf]: No devicepath. Error %d.", GetLastError());
      goto done;
   }

found:
   /* Open the device */
   hDeviceHandle = CreateFileA(
      devicePath,
      GENERIC_READ,  /* | GENERIC_WRITE,*/
      FILE_SHARE_READ,  /* | FILE_SHARE_WRITE,*/
      NULL,
      OPEN_EXISTING,
      0,  /*FILE_FLAG_OVERLAPPED,*/
      NULL);

   if (hDeviceHandle == INVALID_HANDLE_VALUE)
   {
      /* Windows sometimes erroneously fails to open with a sharing violation:
       * https://github.com/signal11/hidapi/issues/231
       * If this happens, trying again with read + write usually works for some reason.
       */

      /* Open the device */
      hDeviceHandle = CreateFileA(
         devicePath,
         GENERIC_READ | GENERIC_WRITE,
         FILE_SHARE_READ | FILE_SHARE_WRITE,
         NULL,
         OPEN_EXISTING,
         0,  /*FILE_FLAG_OVERLAPPED,*/
         NULL);

      if (hDeviceHandle == INVALID_HANDLE_VALUE)
      {
         RARCH_ERR("[Autoconf]: Can't open device for reading and writing: %d.", GetLastError());
         runloop_msg_queue_push("Bliss-Box already in use. Please make sure other programs are not using it.", 2, 300, false, NULL, MESSAGE_QUEUE_ICON_DEFAULT, MESSAGE_QUEUE_CATEGORY_INFO);
         goto done;
      }
   }

done:
   free(devicePath);
   LocalFree(lpDevicePath);
   LocalFree(pInterfaceDetailData);
   bResult              = SetupDiDestroyDeviceInfoList(hDeviceInfo);

   devicePath           = NULL;
   lpDevicePath         = NULL;
   pInterfaceDetailData = NULL;

   if (!bResult)
      RARCH_ERR("[Autoconf]: Could not destroy device info list.\n");

   if (!hDeviceHandle || hDeviceHandle == INVALID_HANDLE_VALUE)
   {
      /* device is not connected */
      return NULL;
   }

   report[0] = BLISSBOX_USB_FEATURE_REPORT_ID;

   HidD_GetFeature(hDeviceHandle, report, sizeof(report));

   CloseHandle(hDeviceHandle);

   for (i = 0; i < sizeof(blissbox_pad_types) / sizeof(blissbox_pad_types[0]); i++)
   {
      const blissbox_pad_type_t *pad = &blissbox_pad_types[i];

      if (!pad || string_is_empty(pad->name))
         continue;

      if (pad->index == report[0])
         return pad;
   }

   RARCH_LOG("[Autoconf]: Could not find connected pad in Bliss-Box port#%d.\n", pid - BLISSBOX_PID);
#endif

   return NULL;
}
예제 #25
0
bool wcePutFile(const char *host_file, const char *wce_file)
{
	TCHAR tszSrcFile[MAX_PATH];
	WCHAR wszDestFile[MAX_PATH];
	BYTE  buffer[5120];
    WIN32_FIND_DATA wfd;
	HRESULT hr;
	DWORD dwAttr, dwNumRead, dwNumWritten;
	HANDLE hSrc, hDest, hFind;
	int nResult;

#ifdef UNICODE
	nResult = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED,
									host_file, strlen(host_file)+1,
									tszSrcFile, ARRAYSIZE(tszSrcFile));
	if(0 == nResult)
		return false;
#else
	hr = StringCchCopy(tszSrcFile, ARRAYSIZE(tszSrcFile), argv[1]);
	if(FAILED(hr))
		return false;
#endif
	nResult = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED,
									wce_file, strlen(wce_file)+1,
									wszDestFile, ARRAYSIZE(wszDestFile));
    if(0 == nResult)
        return false;

    hFind = FindFirstFile( tszSrcFile, &wfd);
    if (INVALID_HANDLE_VALUE == hFind) {
        _tprintf(TEXT("Host file does not exist\n"));
        return false;
    }
    FindClose( hFind);
	if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
        _tprintf( TEXT("Host file specifies a directory\n"));
        return false;
    }
	
	if (wceConnect()) {
		dwAttr = CeGetFileAttributes( wszDestFile);
		if (dwAttr & FILE_ATTRIBUTE_DIRECTORY) {
            hr = StringCchCatW(wszDestFile, ARRAYSIZE(wszDestFile), L"\\");
            if(FAILED(hr)) return false;
#ifdef UNICODE
            hr = StringCchCatW(wszDestFile, ARRAYSIZE(wszDestFile), wfd.cFileName);
            if(FAILED(hr)) return false;
#else
            nResult = MultiByteToWideChar(
                        CP_ACP,    
                        MB_PRECOMPOSED,
                        wfd.cFileName,
                        strlen(wfd.cFileName)+1,
                        wszDestFile+wcslen(wszDestFile),
                        ARRAYSIZE(wszDestFile)-wcslen(wszDestFile));
            if(0 == nResult)
            {
                return 1;
            }
#endif
		}
		hSrc = CreateFile(tszSrcFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		if (INVALID_HANDLE_VALUE == hSrc) {
			_tprintf( TEXT("Unable to open host file\n"));
			return false;
		}

		hDest = CeCreateFile(wszDestFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (INVALID_HANDLE_VALUE == hDest ) {
			_tprintf( TEXT("Unable to open target WinCE file\n"));
			return false;
		}

		//copy file
		do {
			if(ReadFile(hSrc, &buffer, sizeof(buffer), &dwNumRead, NULL)) {
				if (!CeWriteFile(hDest, &buffer, dwNumRead, &dwNumWritten, NULL)) {
					_tprintf( TEXT("Error !!! Writing WinCE file\n"));
					goto FatalError;
				}
			} else {
				_tprintf( TEXT("Error !!! Reading host file\n"));
				goto FatalError;
			}
			_tprintf( TEXT("."));                                        
		} while (dwNumRead);
		//_tprintf( TEXT("\n"));

		CeCloseHandle( hDest);
		CloseHandle (hSrc);
	}
	wceDisconnect();
	return true;

FatalError:
	CeCloseHandle( hDest);
	CloseHandle (hSrc);
	wceDisconnect();
	return false;
}
예제 #26
0
파일: filter.c 프로젝트: John-Chan/dprobe
ULONG
BtrCreateFilter(
	IN PWSTR FilterFullPath,
	OUT PBTR_FILTER *Result
	)
{
	HMODULE DllHandle;
	PBTR_FILTER FilterObject;
	MODULEINFO ModuleInfo = {0};
	BTR_FLT_GETOBJECT ExportRoutine;
	PVOID Buffer;

	*Result = NULL;

	DllHandle = LoadLibrary(FilterFullPath);
	if (!DllHandle) {
		return BTR_E_FAILED_LOAD_FILTER;
	}

	//
	// Once the filter dll is loaded, ensure that it's unloaded
	// whenever there's error occured during the whole operation
	//

	ExportRoutine = (BTR_FLT_GETOBJECT)GetProcAddress(DllHandle,"BtrFltGetObject");
	if (!ExportRoutine) {
		FreeLibrary(DllHandle);
		return BTR_E_FAILED_GET_FILTER_API;
	}

	__try {
		
		FilterObject = (*ExportRoutine)(FILTER_MODE_CAPTURE);	

	} __except (EXCEPTION_EXECUTE_HANDLER) {
		FreeLibrary(DllHandle);
		return BTR_E_UNEXPECTED;
	}

	if (!FilterObject) {
		FreeLibrary(DllHandle);
		return BTR_E_FILTER_REGISTRATION;
	}

	Buffer = BtrMalloc(MAX_FILTER_PROBE / 8);
	BtrInitializeBitMap(&FilterObject->BitMap, Buffer, MAX_FILTER_PROBE);

	StringCchCopy(FilterObject->FilterName, MAX_PATH, FilterFullPath);

	//
	// Query filter dll base and its size, this is reserved for unload operation which
	// require to check whether any thread is executing any filter dll
	//

	(*BtrGetModuleInformation)(GetCurrentProcess(), DllHandle, 
		                       &ModuleInfo, sizeof(ModuleInfo));

	FilterObject->BaseOfDll = ModuleInfo.lpBaseOfDll;
	FilterObject->SizeOfImage = ModuleInfo.SizeOfImage;

	//
	// Chain the new filter object into global filter list
	//

	InsertHeadList(&BtrFilterList, &FilterObject->ListEntry);

	*Result = FilterObject;
	return S_OK;
}
예제 #27
0
// slightly modified sample from MSDN
BOOL GetOSDisplayString(LPTSTR pszOS, int BUFSIZE)
{
	OSVERSIONINFOEX osvi = { 0 };
	osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
	BOOL bOsVersionInfoEx = GetVersionEx((OSVERSIONINFO *)&osvi);
	if (!bOsVersionInfoEx) {
		osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
		if (!GetVersionEx((OSVERSIONINFO*)&osvi))
			return FALSE;
	}

	SYSTEM_INFO si = { 0 };
	GetNativeSystemInfo(&si);

	// Some code from Crash Dumper Plugin :-)
	if (VER_PLATFORM_WIN32_NT == osvi.dwPlatformId && osvi.dwMajorVersion > 4) {
		StringCchCopy(pszOS, BUFSIZE, TEXT("Microsoft "));

		// Test for the specific product.
		if (osvi.dwMajorVersion == 6) {
			switch (osvi.dwMinorVersion) {
			case 0:
				if (osvi.wProductType == VER_NT_WORKSTATION)
					StringCchCat(pszOS, BUFSIZE, TEXT("Windows Vista "));
				else
					StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2008 "));
				break;

			case 1:
				if (osvi.wProductType == VER_NT_WORKSTATION)
					StringCchCat(pszOS, BUFSIZE, TEXT("Windows 7 "));
				else
					StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2008 R2 "));
				break;

			case 2:
				if (osvi.wProductType == VER_NT_WORKSTATION)
					StringCchCat(pszOS, BUFSIZE, TEXT("Windows 8 "));
				else
					StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2012 "));
				break;

			case 3:
				if (osvi.wProductType == VER_NT_WORKSTATION)
					StringCchCat(pszOS, BUFSIZE, TEXT("Windows 8.1 "));
				else
					StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2012 R2 "));
				break;
			}

			DWORD dwType = 0;
			HMODULE hKernel = GetModuleHandle(TEXT("kernel32.dll"));
			PGPI pGPI = (PGPI)GetProcAddress(hKernel, "GetProductInfo");
			if (pGPI != NULL)
				pGPI(osvi.dwMajorVersion, osvi.dwMinorVersion, 0, 0, &dwType);

			switch (dwType) {
			case PRODUCT_ULTIMATE:
				StringCchCat(pszOS, BUFSIZE, TEXT("Ultimate Edition"));
				break;
			case PRODUCT_PROFESSIONAL:
				StringCchCat(pszOS, BUFSIZE, TEXT("Professional Edition"));
				break;
			case PRODUCT_PROFESSIONAL_WMC:
				StringCchCat(pszOS, BUFSIZE, TEXT("Professional Edition with Media Center"));
				break;
			case PRODUCT_HOME_PREMIUM:
				StringCchCat(pszOS, BUFSIZE, TEXT("Home Premium Edition"));
				break;
			case PRODUCT_HOME_BASIC:
				StringCchCat(pszOS, BUFSIZE, TEXT("Home Basic Edition"));
				break;
			case PRODUCT_ENTERPRISE:
				StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition"));
				break;
			case PRODUCT_BUSINESS:
				StringCchCat(pszOS, BUFSIZE, TEXT("Business Edition"));
				break;
			case PRODUCT_STARTER:
				StringCchCat(pszOS, BUFSIZE, TEXT("Starter Edition"));
				break;
			case PRODUCT_CLUSTER_SERVER:
				StringCchCat(pszOS, BUFSIZE, TEXT("Cluster Server Edition"));
				break;
			case PRODUCT_DATACENTER_SERVER:
				StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition"));
				break;
			case PRODUCT_DATACENTER_SERVER_CORE:
				StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition (core installation)"));
				break;
			case PRODUCT_ENTERPRISE_SERVER:
				StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition"));
				break;
			case PRODUCT_ENTERPRISE_SERVER_CORE:
				StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition (core installation)"));
				break;
			case PRODUCT_ENTERPRISE_SERVER_IA64:
				StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition for Itanium-based Systems"));
				break;
			case PRODUCT_SMALLBUSINESS_SERVER:
				StringCchCat(pszOS, BUFSIZE, TEXT("Small Business Server"));
				break;
			case PRODUCT_SMALLBUSINESS_SERVER_PREMIUM:
				StringCchCat(pszOS, BUFSIZE, TEXT("Small Business Server Premium Edition"));
				break;
			case PRODUCT_STANDARD_SERVER:
				StringCchCat(pszOS, BUFSIZE, TEXT("Standard Edition"));
				break;
			case PRODUCT_STANDARD_SERVER_CORE:
				StringCchCat(pszOS, BUFSIZE, TEXT("Standard Edition (core installation)"));
				break;
			case PRODUCT_WEB_SERVER:
				StringCchCat(pszOS, BUFSIZE, TEXT("Web Server Edition"));
				break;
			}
			if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
				StringCchCat(pszOS, BUFSIZE, TEXT(", 64-bit"));
			else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_INTEL)
				StringCchCat(pszOS, BUFSIZE, TEXT(", 32-bit"));
		}

		if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 2) {
			if (GetSystemMetrics(SM_SERVERR2))
				StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2003 R2, "));
			else if (osvi.wSuiteMask == VER_SUITE_STORAGE_SERVER)
				StringCchCat(pszOS, BUFSIZE, TEXT("Windows Storage Server 2003"));
			else if (osvi.wSuiteMask == VER_SUITE_WH_SERVER)
				StringCchCat(pszOS, BUFSIZE, TEXT("Windows Home Server"));
			else if (osvi.wProductType == VER_NT_WORKSTATION && si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)
				StringCchCat(pszOS, BUFSIZE, TEXT("Windows XP Professional x64 Edition"));
			else
				StringCchCat(pszOS, BUFSIZE, TEXT("Windows Server 2003, "));

			// Test for the server type.
			if (osvi.wProductType != VER_NT_WORKSTATION) {
				if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) {
					if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
						StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition for Itanium-based Systems"));
					else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
						StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition for Itanium-based Systems"));
				}
				else if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64) {
					if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
						StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter x64 Edition"));
					else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
						StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise x64 Edition"));
					else StringCchCat(pszOS, BUFSIZE, TEXT("Standard x64 Edition"));
				}
				else {
					if (osvi.wSuiteMask & VER_SUITE_COMPUTE_SERVER)
						StringCchCat(pszOS, BUFSIZE, TEXT("Compute Cluster Edition"));
					else if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
						StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Edition"));
					else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
						StringCchCat(pszOS, BUFSIZE, TEXT("Enterprise Edition"));
					else if (osvi.wSuiteMask & VER_SUITE_BLADE)
						StringCchCat(pszOS, BUFSIZE, TEXT("Web Edition"));
					else StringCchCat(pszOS, BUFSIZE, TEXT("Standard Edition"));
				}
			}
		}

		if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 1) {
			StringCchCat(pszOS, BUFSIZE, TEXT("Windows XP "));
			if (osvi.wSuiteMask & VER_SUITE_PERSONAL)
				StringCchCat(pszOS, BUFSIZE, TEXT("Home Edition"));
			else StringCchCat(pszOS, BUFSIZE, TEXT("Professional"));
		}

		if (osvi.dwMajorVersion == 5 && osvi.dwMinorVersion == 0) {
			StringCchCat(pszOS, BUFSIZE, TEXT("Windows 2000 "));

			if (osvi.wProductType == VER_NT_WORKSTATION)
				StringCchCat(pszOS, BUFSIZE, TEXT("Professional"));
			else {
				if (osvi.wSuiteMask & VER_SUITE_DATACENTER)
					StringCchCat(pszOS, BUFSIZE, TEXT("Datacenter Server"));
				else if (osvi.wSuiteMask & VER_SUITE_ENTERPRISE)
					StringCchCat(pszOS, BUFSIZE, TEXT("Advanced Server"));
				else StringCchCat(pszOS, BUFSIZE, TEXT("Server"));
			}
		}

		// Include service pack (if any) and build number.

		if (mir_tstrlen(osvi.szCSDVersion) > 0) {
			StringCchCat(pszOS, BUFSIZE, TEXT(" "));
			StringCchCat(pszOS, BUFSIZE, osvi.szCSDVersion);
		}

		TCHAR buf[80];
		mir_sntprintf(buf, TEXT(" (build %d)"), osvi.dwBuildNumber);
		StringCchCat(pszOS, BUFSIZE, buf);
		return TRUE;
	}

	return FALSE;
}
예제 #28
0
파일: main.cpp 프로젝트: henrypp/timevertor
INT_PTR CALLBACK DlgProc (HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
	switch (msg)
	{
		case WM_INITDIALOG:
		{
#ifndef _APP_NO_DARKTHEME
			_r_wnd_setdarktheme (hwnd);
#endif // _APP_NO_DARKTHEME

			// configure listview
			_r_listview_setstyle (hwnd, IDC_LISTVIEW, LVS_EX_DOUBLEBUFFER | LVS_EX_FULLROWSELECT | LVS_EX_INFOTIP | LVS_EX_LABELTIP);

			_r_listview_addcolumn (hwnd, IDC_LISTVIEW, 1, nullptr, 39, LVCFMT_LEFT);
			_r_listview_addcolumn (hwnd, IDC_LISTVIEW, 2, nullptr, 61, LVCFMT_RIGHT);

			for (UINT i = 0; i < TypeMax; i++)
				_r_listview_additem (hwnd, IDC_LISTVIEW, i, 0, nullptr);

			// configure datetime format
			{
				WCHAR date_format[MAX_PATH] = {0};
				WCHAR time_format[MAX_PATH] = {0};

				if (
					GetLocaleInfo (LOCALE_SYSTEM_DEFAULT, LOCALE_SLONGDATE, date_format, _countof (date_format)) &&
					GetLocaleInfo (LOCALE_SYSTEM_DEFAULT, LOCALE_STIMEFORMAT, time_format, _countof (time_format))
					)
				{
					WCHAR buffer[MAX_PATH] = {0};
					StringCchPrintf (buffer, _countof (buffer), L"%s %s", date_format, time_format);

					SendDlgItemMessage (hwnd, IDC_INPUT, DTM_SETFORMAT, 0, (LPARAM)buffer);
				}
			}

			// print latest timestamp
			{
				SYSTEMTIME st = {0};

				current_timestamp_utc = app.ConfigGet (L"LatestTimestamp", _r_unixtime_now ()).AsLonglong ();

				//_app_gettime (current_timestamp_utc, 0, &st);
				//_app_printdate (hwnd, &st);
			}

			_r_ctrl_settip (hwnd, IDC_CURRENT, LPSTR_TEXTCALLBACK);

			break;
		}

		case WM_DESTROY:
		{
			// save latest timestamp
			{
				SYSTEMTIME st = {0};
				//SendDlgItemMessage (hwnd, IDC_INPUT, DTM_GETSYSTEMTIME, 0, (LPARAM)&st);

				_app_gettime (current_timestamp_utc, 0, &st);

				app.ConfigSet (L"LatestTimestamp", _r_unixtime_from_systemtime (&st));
			}

			PostQuitMessage (0);

			break;
		}

		case RM_INITIALIZE:
		{
			// configure menu
			CheckMenuItem (GetMenu (hwnd), IDM_ALWAYSONTOP_CHK, MF_BYCOMMAND | (app.ConfigGet (L"AlwaysOnTop", false).AsBool () ? MF_CHECKED : MF_UNCHECKED));
			CheckMenuItem (GetMenu (hwnd), IDM_CHECKUPDATES_CHK, MF_BYCOMMAND | (app.ConfigGet (L"CheckUpdates", true).AsBool () ? MF_CHECKED : MF_UNCHECKED));
			CheckMenuItem (GetMenu (hwnd), IDM_CLASSICUI_CHK, MF_BYCOMMAND | (app.ConfigGet (L"ClassicUI", _APP_CLASSICUI).AsBool () ? MF_CHECKED : MF_UNCHECKED));

			// configure timezone
			{
				const HMENU submenu_timezone = GetSubMenu (GetSubMenu (GetMenu (hwnd), 1), TIMEZONE_MENU);

				// clear menu
				for (UINT i = 0;; i++)
				{
					if (!DeleteMenu (submenu_timezone, TIMEZONE_MENU + i, MF_BYCOMMAND))
					{
						DeleteMenu (submenu_timezone, 0, MF_BYPOSITION); // delete separator
						break;
					}
				}

				const LONG current_bias = _app_getcurrentbias ();
				const LONG default_bias = _app_getdefaultbias ();

				for (size_t i = 0; i < _countof (int_timezones); i++)
				{
					const LONG bias = int_timezones[i];

					MENUITEMINFO mii = {0};

					WCHAR menu_title[32] = {0};
					StringCchPrintf (menu_title, _countof (menu_title), L"GMT %s", _app_timezone2string (bias, true, L"+00:00 (UTC)").GetString ());

					if (bias == default_bias)
						StringCchCat (menu_title, _countof (menu_title), SYSTEM_BIAS);

					mii.cbSize = sizeof (mii);
					mii.fMask = MIIM_ID | MIIM_STRING;
					mii.fType = MFT_STRING;
					mii.fState = MFS_DEFAULT;
					mii.dwTypeData = menu_title;
					mii.wID = IDX_TIMEZONE + UINT (i);

					InsertMenuItem (submenu_timezone, mii.wID, FALSE, &mii);

					if (bias == current_bias)
					{
						current_bias_idx = i;

						CheckMenuRadioItem (submenu_timezone, IDX_TIMEZONE, IDX_TIMEZONE + UINT (_countof (int_timezones) - 1), mii.wID, MF_BYCOMMAND);
					}
				}

				SYSTEMTIME st = {0};

				_app_gettime (current_timestamp_utc, current_bias, &st);
				_app_printdate (hwnd, &st);
			}

			break;
		}

		case RM_LOCALIZE:
		{
			// configure menu
			const HMENU menu = GetMenu (hwnd);

			app.LocaleMenu (menu, IDS_FILE, 0, true, nullptr);
			app.LocaleMenu (menu, IDS_EXIT, IDM_EXIT, false, L"\tEsc");
			app.LocaleMenu (menu, IDS_SETTINGS, 1, true, nullptr);
			app.LocaleMenu (menu, IDS_ALWAYSONTOP_CHK, IDM_ALWAYSONTOP_CHK, false, nullptr);
			app.LocaleMenu (menu, IDS_CHECKUPDATES_CHK, IDM_CHECKUPDATES_CHK, false, nullptr);
			app.LocaleMenu (menu, IDS_CLASSICUI_CHK, IDM_CLASSICUI_CHK, false, nullptr);
			app.LocaleMenu (GetSubMenu (menu, 1), IDS_TIMEZONE, TIMEZONE_MENU, true, nullptr);
			app.LocaleMenu (GetSubMenu (menu, 1), IDS_LANGUAGE, LANG_MENU, true, L" (Language)");
			app.LocaleMenu (menu, IDS_HELP, 2, true, nullptr);
			app.LocaleMenu (menu, IDS_WEBSITE, IDM_WEBSITE, false, nullptr);
			app.LocaleMenu (menu, IDS_CHECKUPDATES, IDM_CHECKUPDATES, false, nullptr);
			app.LocaleMenu (menu, IDS_ABOUT, IDM_ABOUT, false, L"\tF1");

			app.LocaleEnum ((HWND)GetSubMenu (menu, 1), LANG_MENU, true, IDX_LANGUAGE); // enum localizations

			// configure listview
			for (UINT i = 0; i < TypeMax; i++)
				_r_listview_setitem (hwnd, IDC_LISTVIEW, i, 0, _app_gettimedescription ((EnumDateType)i, false));

			_r_wnd_addstyle (hwnd, IDC_CURRENT, app.IsClassicUI () ? WS_EX_STATICEDGE : 0, WS_EX_STATICEDGE, GWL_EXSTYLE);

			RedrawWindow (hwnd, nullptr, nullptr, RDW_ERASENOW | RDW_INVALIDATE);

			break;
		}

		case WM_CONTEXTMENU:
		{
			if (GetDlgCtrlID ((HWND)wparam) == IDC_LISTVIEW)
			{
				const HMENU menu = LoadMenu (nullptr, MAKEINTRESOURCE (IDM_LISTVIEW));
				const HMENU submenu = GetSubMenu (menu, 0);

				// localize
				app.LocaleMenu (submenu, IDS_COPY, IDM_COPY, false, L"\tCtrl+C");

				if (!SendDlgItemMessage (hwnd, IDC_LISTVIEW, LVM_GETSELECTEDCOUNT, 0, 0))
					EnableMenuItem (submenu, IDM_COPY, MF_BYCOMMAND | MF_DISABLED);

				POINT pt = {0};
				GetCursorPos (&pt);

				TrackPopupMenuEx (submenu, TPM_RIGHTBUTTON | TPM_LEFTBUTTON, pt.x, pt.y, hwnd, nullptr);

				DestroyMenu (menu);
			}

			break;
		}

		case WM_NOTIFY:
		{
			switch (LPNMHDR (lparam)->code)
			{
				case DTN_USERSTRING:
				{
					LPNMDATETIMESTRING lpds = (LPNMDATETIMESTRING)lparam;

					if (lpds)
					{
						const rstring datetime = lpds->pszUserString;

						if (datetime.IsNumeric ())
							_r_unixtime_to_systemtime (datetime.AsLonglong (), &lpds->st);
					}

					break;
				}

				case DTN_DATETIMECHANGE:
				{
					LPNMDATETIMECHANGE lpnmdtc = (LPNMDATETIMECHANGE)lparam;

					current_timestamp_utc = _r_unixtime_from_systemtime (&lpnmdtc->st); // store position of current time (utc)

					_app_printdate (hwnd, &lpnmdtc->st);

					break;
				}

				case LVN_GETINFOTIP:
				{
					LPNMLVGETINFOTIP lpnmlv = (LPNMLVGETINFOTIP)lparam;

					StringCchCopy (lpnmlv->pszText, lpnmlv->cchTextMax, _app_gettimedescription ((EnumDateType)lpnmlv->iItem, true));

					break;
				}

				case TTN_GETDISPINFO:
				{
					LPNMTTDISPINFO lpnmdi = (LPNMTTDISPINFO)lparam;

					if ((lpnmdi->uFlags & TTF_IDISHWND) != 0)
					{
						WCHAR buffer[1024] = {0};
						const UINT ctrl_id = GetDlgCtrlID ((HWND)lpnmdi->hdr.idFrom);

						if (ctrl_id == IDC_CURRENT)
							StringCchCopy (buffer, _countof (buffer), app.LocaleString (IDS_CURRENT, nullptr));

						if (buffer[0])
							lpnmdi->lpszText = buffer;
					}

					break;
				}
			}

			break;
		}

		case WM_COMMAND:
		{
			if (HIWORD (wparam) == 0 && LOWORD (wparam) >= IDX_LANGUAGE && LOWORD (wparam) <= IDX_LANGUAGE + app.LocaleGetCount ())
			{
				app.LocaleApplyFromMenu (GetSubMenu (GetSubMenu (GetMenu (hwnd), 1), LANG_MENU), LOWORD (wparam), IDX_LANGUAGE);

				return FALSE;
			}
			else if ((LOWORD (wparam) >= IDX_TIMEZONE && LOWORD (wparam) <= IDX_TIMEZONE + (_countof (int_timezones) - 1)))
			{
				const UINT idx = LOWORD (wparam) - IDX_TIMEZONE;
				const LONG bias = int_timezones[idx];

				current_bias_idx = idx;
				app.ConfigSet (L"TimezoneBias", bias);

				const HMENU submenu_timezone = GetSubMenu (GetSubMenu (GetMenu (hwnd), 1), TIMEZONE_MENU);
				CheckMenuRadioItem (submenu_timezone, IDX_TIMEZONE, IDX_TIMEZONE + UINT (_countof (int_timezones) - 1), LOWORD (wparam), MF_BYCOMMAND);

				SYSTEMTIME st = {0};

				_app_gettime (current_timestamp_utc, bias, &st);
				_app_printdate (hwnd, &st);

				return FALSE;
			}

			switch (LOWORD (wparam))
			{
				case IDCANCEL: // process Esc key
				case IDM_EXIT:
				{
					DestroyWindow (hwnd);
					break;
				}

				case IDM_ALWAYSONTOP_CHK:
				{
					const bool new_val = !app.ConfigGet (L"AlwaysOnTop", false).AsBool ();

					CheckMenuItem (GetMenu (hwnd), LOWORD (wparam), MF_BYCOMMAND | (new_val ? MF_CHECKED : MF_UNCHECKED));
					app.ConfigSet (L"AlwaysOnTop", new_val);

					_r_wnd_top (hwnd, new_val);

					break;
				}

				case IDM_CHECKUPDATES_CHK:
				{
					const bool new_val = !app.ConfigGet (L"CheckUpdates", true).AsBool ();

					CheckMenuItem (GetMenu (hwnd), LOWORD (wparam), MF_BYCOMMAND | (new_val ? MF_CHECKED : MF_UNCHECKED));
					app.ConfigSet (L"CheckUpdates", new_val);

					break;
				}

				case IDM_CLASSICUI_CHK:
				{
					const bool new_val = !app.ConfigGet (L"ClassicUI", _APP_CLASSICUI).AsBool ();

					CheckMenuItem (GetMenu (hwnd), LOWORD (wparam), MF_BYCOMMAND | (new_val ? MF_CHECKED : MF_UNCHECKED));
					app.ConfigSet (L"ClassicUI", new_val);

					break;
				}

				case IDM_WEBSITE:
				{
					ShellExecute (hwnd, nullptr, _APP_WEBSITE_URL, nullptr, nullptr, SW_SHOWDEFAULT);
					break;
				}

				case IDM_CHECKUPDATES:
				{
					app.UpdateCheck (true);
					break;
				}

				case IDM_ABOUT:
				{
					app.CreateAboutWindow (hwnd);
					break;
				}

				case IDM_COPY:
				{
					rstring buffer;

					size_t item = LAST_VALUE;

					while ((item = (size_t)SendDlgItemMessage (hwnd, IDC_LISTVIEW, LVM_GETNEXTITEM, item, LVNI_SELECTED)) != LAST_VALUE)
					{
						buffer.AppendFormat (L"%s\r\n", _r_listview_getitemtext (hwnd, IDC_LISTVIEW, item, 1).GetString ());
					}

					if (!buffer.IsEmpty ())
					{
						buffer.Trim (L"\r\n");

						_r_clipboard_set (hwnd, buffer, buffer.GetLength ());
					}

					break;
				}

				case IDC_CURRENT:
				{
					SYSTEMTIME st = {0};

					_app_gettime (_r_unixtime_now (), _app_getcurrentbias (), &st);
					_app_printdate (hwnd, &st);

					break;
				}

				case IDM_SELECT_ALL:
				{
					ListView_SetItemState (GetDlgItem (hwnd, IDC_LISTVIEW), -1, LVIS_SELECTED, LVIS_SELECTED);
					break;
				}

				case IDM_TIMEZONE_NEXT:
				case IDM_TIMEZONE_PREV:
				{
					if (LOWORD (wparam) == IDM_TIMEZONE_NEXT)
						current_bias_idx = ((current_bias_idx == (_countof (int_timezones) - 1)) ? 0 : ++current_bias_idx);

					else
						current_bias_idx = (!current_bias_idx ? (_countof (int_timezones) - 1) : --current_bias_idx);

					SendMessage (hwnd, WM_COMMAND, MAKEWPARAM (IDX_TIMEZONE + current_bias_idx, 0), 0);

					break;
				}
			}
		}
	}

	return FALSE;
}
예제 #29
0
/*!
	メインのCOMMANDメッセージの受け取り。ボタン押されたとかで発生
	@param[in]	hWnd		親ウインドウのハンドル
	@param[in]	id			メッセージを発生させた子ウインドウの識別子	LOWORD(wParam)
	@param[in]	hwndCtl		メッセージを発生させた子ウインドウのハンドル	lParam
	@param[in]	codeNotify	通知メッセージ	HIWORD(wParam)
	@return		なし
*/
VOID Cls_OnCommand( HWND hWnd, INT id, HWND hwndCtl, UINT codeNotify )
{
	TCHAR	atPath[MAX_PATH], atBuff[MAX_PATH];
	INT		iRslt, iTgt;

	UINT	bActOn;
	BOOL	bHotRslt;

	LRESULT	lRslt;
	UINT	bMod, bVkey;

	switch( id )
	{
		case IDM_EXIT:	DestroyWindow( hWnd );	break;


		case IDM_CLIPSTEAL_OPTION:
			ShowWindow( hWnd, SW_SHOW );
			UnregisterHotKey( hWnd, IDHK_CLIPSTEAL_FILECHANGE );	//	キーバインド取得のために一時的に解除
			break;

		case IDM_CLIPSTEAL_TOGGLE:
			gbClipSteal = !(gbClipSteal);
			TaskTrayIconCaptionChange( hWnd );
			break;

		case IDB_CLIPSTEAL_REF:	//	ファイル開くダイヤログ呼出
			if( SelectFileDlg( hWnd, atPath, MAX_PATH ) )
			{
				Edit_SetText( GetDlgItem(hWnd,IDE_CLIPSTEAL_FILE), atPath );
			}
			break;

		case IDB_CLIPSTEAL_FILEADD:
			Edit_GetText( GetDlgItem(hWnd,IDE_CLIPSTEAL_FILE), atPath, MAX_PATH );
			iRslt = FileListViewAdd( hWnd, atPath );
			if( 1 == iRslt )	//	1発目なら
			{
				StringCchCopy( gatClipFile, MAX_PATH, atPath );
				FileTypeCheck( gatClipFile );
			}	//	取り込みファイルとして登録する
			break;

		case IDB_CLIPSTEAL_FILEDEL:
			FileListViewDelete( hWnd );
			break;

		case IDB_CLIP_SAVE_AND_EXIT:
			//	ホットキー設定を確保
			lRslt = SendDlgItemMessage( hWnd, IDHK_CLIP_POPUP_KEYBIND, HKM_GETHOTKEY, 0, 0 );
			bVkey = LOBYTE( lRslt );
			bMod  = RegHotModExchange( HIBYTE( lRslt ), 0 );
			//	もしレジスト失敗したら閉じない・成功で非0もどる
			bHotRslt = RegisterHotKey( hWnd, IDHK_CLIPSTEAL_FILECHANGE, bMod, bVkey );
			if( bHotRslt )
			{
				gbHotVkey = bVkey;
				gbHotMod  = bMod;
			}
			else
			{
				MessageBox( hWnd, TEXT("ホットキーが登録出来なかったよ。\r\n已に使われてるみたい。\r\n他の組み合わせを試してみて!"), TEXT("お燐からのお知らせ"), MB_OK | MB_ICONERROR );
				break;
			}

			if( BST_CHECKED == IsDlgButtonChecked( hWnd, IDB_CLIP_USE_BALLOON ) ){	gGetMsgOn = TRUE;	}
			else{	gGetMsgOn = FALSE;	}

			if( BST_CHECKED == IsDlgButtonChecked( hWnd, IDB_CLIP_UNIRADIX_HEX ) ){	gbUniRadixHex = TRUE;	}
			else{	gbUniRadixHex = FALSE;	}

			bActOn = IsDlgButtonChecked( hWnd, IDB_CLIP_STEAL_ACT_ON );

			InitSettingSave( hWnd, bActOn );

			ShowWindow( hWnd, SW_HIDE );
			break;

		default:	break;
	}

	if( IDM_CLIPSTEAL_SELECT <= id )	//	メニュー選んだ
	{
		iTgt = id - IDM_CLIPSTEAL_SELECT;	//	リスト上の位置
		FileListViewGet( hWnd, iTgt, atPath );
		StringCchCopy( gatClipFile, MAX_PATH, atPath );
		FileTypeCheck( gatClipFile );
		//	取り込みファイルとして登録する
		PathStripPath( atPath );
		StringCchPrintf( atBuff, MAX_PATH, TEXT("%s に保存していくのです。あぅあぅ。"), atPath );
		TaskTrayIconBalloon( hWnd, atBuff, TEXT("保存先を変更したのです。"), NIIF_INFO );
	}

	return;
}
/// <summary>
/// Sets the status message for the frame.
/// </summary>
/// <param name="szMessage">The status message.</param>
void KinectFusionProcessorFrame::SetStatusMessage(const WCHAR* szMessage)
{
    StringCchCopy(m_statusMessage, ARRAYSIZE(m_statusMessage), szMessage);
}