Пример #1
0
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
    LPTSTR app_dir, config_dir, exe, library_dir, too_long;

    app_dir = get_app_dir();
    config_dir = (LPTSTR)calloc(BUFSIZE, sizeof(TCHAR));
    library_dir = (LPTSTR)calloc(BUFSIZE, sizeof(TCHAR));
    exe = (LPTSTR)calloc(BUFSIZE, sizeof(TCHAR));

    _sntprintf_s(config_dir, BUFSIZE, _TRUNCATE, _T("%sCalibre Settings"), app_dir);
    _sntprintf_s(exe, BUFSIZE, _TRUNCATE, _T("%sCalibre\\calibre.exe"), app_dir);
    _sntprintf_s(library_dir, BUFSIZE, _TRUNCATE, _T("%sCalibre Library"), app_dir);

    if ( _tcscnlen(library_dir, BUFSIZE) <= 74 ) {
        launch_calibre(exe, config_dir, library_dir);
    } else {
        too_long = (LPTSTR)calloc(BUFSIZE+300, sizeof(TCHAR));
        _sntprintf_s(too_long, BUFSIZE+300, _TRUNCATE, 
                _T("Path to Calibre Portable (%s) too long. Must be less than 59 characters."), app_dir);

        show_error(too_long);
    }

    free(app_dir); free(config_dir); free(exe); free(library_dir);

    return 0;
}
Пример #2
0
//不包括扩展名
const std::wstring GenerateNewFilePath(DWORD dwPID)
{
	TCHAR szPath[_MAX_PATH] = {0};
	

	TCHAR szDir[_MAX_PATH] = {0};
	_tcscpy_s(szDir, crash::GetCrashPath());

	TCHAR szDate[128] = {0};
	time_t curTime = time(NULL);
	_tcsftime(szDate, _countof(szDate) - 1, _T("%Y-%m-%d"), localtime(&curTime));

	int i = 0;
	for (;;)
	{
		TCHAR szTemp[_MAX_PATH] = {0};
		_sntprintf_s(szTemp, _countof(szTemp), _TRUNCATE, _T("%s%s crash %u_%u.*"), szDir, szDate, dwPID, i);
		
		WIN32_FIND_DATA findFileData = {0};
		HANDLE hFind = ::FindFirstFile(szTemp, &findFileData);
		if (hFind == INVALID_HANDLE_VALUE) 
		{
			_sntprintf_s(szPath, _countof(szPath), _TRUNCATE, _T("%s%s crash %u_%u"), szDir, szDate, dwPID, i);
			break;
		} 
		::FindClose(hFind);
		++i;
	}

	return szPath;
}
Пример #3
0
void CCoordFrame::DrawRulerText(TCHAR * wszText, size_t len, float Y, float y)
{
	_sntprintf_s(wszText, len, _TRUNCATE, L"%.02f", Y);
		D2D1_RECT_F textRect = D2D1::RectF(
			static_cast<float>(0) / CDxFactorys::GetInstance()->m_dpiScaleX,
			static_cast<float>(y - _ruler_width.top * .5) / CDxFactorys::GetInstance()->m_dpiScaleY,
			static_cast<float>(_ruler_width.left) / CDxFactorys::GetInstance()->m_dpiScaleX,
			static_cast<float>(y + _ruler_width.bottom * .5) / CDxFactorys::GetInstance()->m_dpiScaleY);

		_artist->DrawText(wszText, textRect);

		//Right, percent text
		if (_referframe->_real_world.y0 == 0) {
			if (Y - _referframe->_real_world.y0 < 0)
				_sntprintf_s(wszText, len, _TRUNCATE, L"%.02f%%",  (Y - _referframe->_real_world.y0)/(_referframe->_real_world.maxy - _referframe->_real_world.y0) * 100);
			else
				_sntprintf_s(wszText, len, _TRUNCATE, L"+%.02f%%", (Y - _referframe->_real_world.y0)/(_referframe->_real_world.maxy - _referframe->_real_world.y0) * 100);
		} else {
			if (Y - _referframe->_real_world.y0 < 0)
				_sntprintf_s(wszText, len, _TRUNCATE, L"%.02f%%",  (Y - _referframe->_real_world.y0)/_referframe->_real_world.y0 * 100);
			else
				_sntprintf_s(wszText, len, _TRUNCATE, L"+%.02f%%", (Y - _referframe->_real_world.y0)/_referframe->_real_world.y0 * 100);
		}

		textRect = D2D1::RectF(
			static_cast<float>(_rect_calc.right - _ruler_width.right) / CDxFactorys::GetInstance()->m_dpiScaleX,
			static_cast<float>(y - _ruler_width.top * .5) / CDxFactorys::GetInstance()->m_dpiScaleY,
			static_cast<float>(_rect_calc.right) / CDxFactorys::GetInstance()->m_dpiScaleX,
			static_cast<float>(y + _ruler_width.bottom * .5) / CDxFactorys::GetInstance()->m_dpiScaleY);
		_artist->DrawText(wszText, textRect);
}
Пример #4
0
static int setting_set_exit_action(const TCHAR *service_name, void *param, const TCHAR *name, void *default_value, value_t *value, const TCHAR *additional) {
  unsigned long exitcode;
  TCHAR *code;
  TCHAR action_string[ACTION_LEN];

  if (additional) {
    /* Default action? */
    if (is_default(additional)) code = 0;
    else {
      if (str_number(additional, &exitcode)) return -1;
      code = (TCHAR *) additional;
    }
  }

  HKEY key = open_registry(service_name, name, KEY_WRITE);
  if (! key) return -1;

  long error;
  int ret = 1;

  /* Resetting to default? */
  if (value && value->string) _sntprintf_s(action_string, _countof(action_string), _TRUNCATE, _T("%s"), value->string);
  else {
    if (code) {
      /* Delete explicit action. */
      error = RegDeleteValue(key, code);
      RegCloseKey(key);
      if (error == ERROR_SUCCESS || error == ERROR_FILE_NOT_FOUND) return 0;
      print_message(stderr, NSSM_MESSAGE_REGDELETEVALUE_FAILED, code, service_name, error_string(error));
      return -1;
    }
    else {
      /* Explicitly keep the default action. */
      if (default_value) _sntprintf_s(action_string, _countof(action_string), _TRUNCATE, _T("%s"), (TCHAR *) default_value);
      ret = 0;
    }
  }

  /* Validate the string. */
  for (int i = 0; exit_action_strings[i]; i++) {
    if (! _tcsnicmp((const TCHAR *) action_string, exit_action_strings[i], ACTION_LEN)) {
      if (default_value && str_equiv(action_string, (TCHAR *) default_value)) ret = 0;
      if (RegSetValueEx(key, code, 0, REG_SZ, (const unsigned char *) exit_action_strings[i], (unsigned long) (_tcslen(action_string) + 1) * sizeof(TCHAR)) != ERROR_SUCCESS) {
        print_message(stderr, NSSM_MESSAGE_SETVALUE_FAILED, code, service_name, error_string(GetLastError()));
        RegCloseKey(key);
        return -1;
      }

      RegCloseKey(key);
      return ret;
    }
  }

  print_message(stderr, NSSM_MESSAGE_INVALID_EXIT_ACTION, action_string);
  for (int i = 0; exit_action_strings[i]; i++) _ftprintf(stderr, _T("%s\n"), exit_action_strings[i]);

  return -1;
}
Пример #5
0
static int service_registry_path(const TCHAR *service_name, bool parameters, const TCHAR *sub, TCHAR *buffer, unsigned long buflen) {
  int ret;

  if (parameters) {
    if (sub) ret = _sntprintf_s(buffer, buflen, _TRUNCATE, NSSM_REGISTRY _T("\\") NSSM_REG_PARAMETERS _T("\\%s"), service_name, sub);
    else ret = _sntprintf_s(buffer, buflen, _TRUNCATE, NSSM_REGISTRY _T("\\") NSSM_REG_PARAMETERS, service_name);
  }
  else ret = _sntprintf_s(buffer, buflen, _TRUNCATE, NSSM_REGISTRY, service_name);

  return ret;
}
void U2MultiTextureEffect::Configure()
{
	if(m_uTextureCnt == 1)
	{
		m_vsArray.SetElem(0, U2_NEW U2VertexShader(_T("v_Texture.dx9.wmsp")));
		m_psArray.SetElem(0, U2_NEW U2PixelShader(_T("p_Texture.dx9.wmsp")));
		m_psArray.GetElem(0)->SetTexture(0, *m_ppTextureNameArray[0]);
		return;
	}

	const size_t uNumberSize= 4;
	TCHAR szNumber[uNumberSize];

	// In a single-effect drawing pass, texture 0 is a source to be blended
	// with a nonexistent destination.  As such, we think of the source mode
	// as SBF_ONE and the destination mode as SDF_ZERO.
	U2DynString vShaderName(_T("v_T0d2"));	
	U2DynString pShaderName(_T("p_T0s1d0"));
	int i;
	for (i = 1; i < m_uTextureCnt; i++)
	{
		vShaderName.Concatenate(_T("T"));		
		pShaderName.Concatenate(_T("T"));		
		_sntprintf_s(szNumber,uNumberSize,_T("%d"),i);				
		vShaderName.Concatenate(szNumber);
		vShaderName.Concatenate(_T("d2"));
		pShaderName.Concatenate(U2DynString(szNumber));

		U2AlphaState* pkAS = m_alphaStateArray.GetElem(i);

		// Source blending mode.
		pShaderName.Concatenate(_T("s"));
		_sntprintf_s(szNumber,uNumberSize,_T("%d"),(int)pkAS->GetSrcBlendMode());
		pShaderName.Concatenate(U2DynString(szNumber));

		// Destination blending mode.
		pShaderName.Concatenate(_T("d"));
		_sntprintf_s(szNumber,uNumberSize,_T("%d"),(int)pkAS->GetDestBlendMode());
		pShaderName.Concatenate(U2DynString(szNumber));
	}
	vShaderName.Concatenate(U2DynString(_T("PassThrough.dx9.wmsp")));
	pShaderName.Concatenate(U2DynString(_T(".dx9.wmsp")));

	m_vsArray.SetElem(0, U2_NEW U2VertexShader(vShaderName));
	m_psArray.SetElem(0, U2_NEW U2PixelShader(pShaderName));
	for(i=0; i < m_uTextureCnt; ++i)
	{
		m_psArray.GetElem(0)->SetTexture(i, *m_ppTextureNameArray[i]);
	}


}
Пример #7
0
void PrintMessage(char *file, int lineno, int errorLvl, char *fmt, ...)
{
    char str[256];
    char output[256];

    LPVOID lpMsgBuf = NULL;
    DWORD dwError = GetLastError();

    va_list args;
    va_start(args, fmt);
    vsprintf_s(str, sizeof(str), fmt, args);
    va_end(args);
    // TODO MUST, On error, need to call GetLastError and print error message
    _sntprintf_s(output, sizeof(output), _TRUNCATE, _TEXT("%s[%s:%d] %s"),
                 (errorLvl == ERROR_LEVEL) ? _TEXT("ERROR ") : _TEXT(""),
                 file, lineno, str);

#ifdef _DEBUG
    OutputDebugString(output);
#endif

    if (errorLvl == ERROR_LEVEL)
    {
        // TODO MUST print the error to a log file
        //printf("%s\n", output);

        // Decode error code
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER |
            FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS,
            NULL,
            dwError,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
            (LPTSTR) &lpMsgBuf,
            0, NULL );

        _sntprintf_s(output, sizeof(output), _TRUNCATE, _TEXT("Last Error (%d): %s"), dwError, lpMsgBuf);
#ifdef _DEBUG
        OutputDebugString(output);
#endif
        // TODO MUST print the error to a log file
        // printf("%s\n", output);
    }

    // Clean-up
    if (lpMsgBuf != NULL)
    {
        LocalFree(lpMsgBuf);
    }
}
Пример #8
0
LPTSTR get_app_dir() {
    LPTSTR buf, buf2, buf3;
    DWORD sz;
    TCHAR drive[4] = _T("\0\0\0");
    errno_t err;

    buf = (LPTSTR)calloc(BUFSIZE, sizeof(TCHAR));
    buf2 = (LPTSTR)calloc(BUFSIZE, sizeof(TCHAR));
    buf3 = (LPTSTR)calloc(BUFSIZE, sizeof(TCHAR));

    sz = GetModuleFileName(NULL, buf, BUFSIZE);

    if (sz == 0 || sz > BUFSIZE-1) {
        show_error(_T("Failed to get path to calibre-portable.exe"));
        ExitProcess(1);
    }

    err = _tsplitpath_s(buf, drive, 4, buf2, BUFSIZE, NULL, 0, NULL, 0);

    if (err != 0) {
        show_last_error_crt(_T("Failed to split path to calibre-portable.exe"));
        ExitProcess(1);
    }

    _sntprintf_s(buf3, BUFSIZE-1, _TRUNCATE, _T("%s%s"), drive, buf2);
    free(buf); free(buf2);
    return buf3;
}
Пример #9
0
	// インストールコミット時に動作する処理
	void __stdcall InstallerCommit( MSIHANDLE hInstall )
	{
		TCHAR w_aDirPathBuff[DEF_DIR_PATH]		= { 0 };
		TCHAR w_aDirPath[DEF_DIR_PATH]			= { 0 };
		TCHAR w_aCommandStr[DEF_COMMANDO_LEN]	= { 0 };
		DWORD w_dDirPathSize					= DEF_DIR_PATH;
		SHELLEXECUTEINFO w_ShellExecInfo		= { 0 };

		// インストーラからインストール先ディレクトリのパス取得
		MsiGetProperty( hInstall, _T( "CustomActionData" ), w_aDirPathBuff, &w_dDirPathSize );
		// 末尾の\削除
		_tcsncpy_s( w_aDirPath, DEF_DIR_PATH, w_aDirPathBuff, _tcslen( w_aDirPathBuff ) -1 );

		// コマンドプロンプト実行時のパラメータ設定
		w_ShellExecInfo.cbSize	= sizeof( SHELLEXECUTEINFO );
		w_ShellExecInfo.nShow	= SW_HIDE;
		w_ShellExecInfo.fMask	= SEE_MASK_NOCLOSEPROCESS;
		w_ShellExecInfo.lpFile	= _T( "cmd.exe" );
		// インストール先ディレクトリ配下にフルコントロールのアクセス権限付与
		_sntprintf_s( w_aCommandStr, DEF_COMMANDO_LEN, _TRUNCATE,
			_T( "/c cacls \"%s\" /t /e /g users:f" ), w_aDirPath );
		w_ShellExecInfo.lpParameters = w_aCommandStr;

		// 実行
		ShellExecuteEx( &w_ShellExecInfo );
		// 終了待ち
		WaitForSingleObject( w_ShellExecInfo.hProcess, INFINITE );
	}
Пример #10
0
MPIPTVSOURCE_API int GetIpAddress(const TCHAR *serverName, WORD port, ADDRINFOT **address, const ADDRINFOT *pHints)
{
  ADDRINFOT hints;
  ADDRINFOT *result = NULL;

  TCHAR service[6];
  _sntprintf_s(service, 6 * sizeof(TCHAR), 6, _T("%d"), port);

  // setup the hints address info structure
  // which is passed to the getaddrinfo() function
  ZeroMemory(&hints, sizeof(hints));
  if (pHints != NULL)
  {
    const int safe_flags =
      AI_PASSIVE |
      AI_CANONNAME |
      AI_NUMERICHOST |
      AI_NUMERICSERV |
#ifdef AI_ALL
      AI_ALL |
#endif
#ifdef AI_ADDRCONFIG
      AI_ADDRCONFIG |
#endif
#ifdef AI_V4MAPPED
      AI_V4MAPPED |
#endif
      0;

    hints.ai_family = pHints->ai_family;
    hints.ai_socktype = pHints->ai_socktype;
    hints.ai_protocol = pHints->ai_protocol;

    // unfortunately, some flags change the layout of struct addrinfo, so
    // they cannot be copied blindly from p_hints to &hints. Therefore, we
    // only copy flags that we know for sure are "safe".
    hints.ai_flags = pHints->ai_flags & safe_flags;
  }

  // we only ever use port *numbers*
  hints.ai_flags |= AI_NUMERICSERV;

  int retval = 0;
  if ((hints.ai_flags & AI_NUMERICHOST) == 0)
  {
    hints.ai_flags |= AI_NUMERICHOST;
    retval = GetAddrInfo(serverName, service, &hints, &result);
    if (retval != 0)
    {
      hints.ai_flags &= ~AI_NUMERICHOST;
    }
  } 

  retval = GetAddrInfo(serverName, service, &hints, &result);
  if (retval == 0)
  {
    *address = result;
  }
  return retval;
}
Пример #11
0
void CWindowTreeDlg::GetWindowString(HWND hwnd, TCHAR * buf, int bufsize)
{
    TCHAR tmpbuf[4096] = {0};
    TCHAR szClassName[100] = {0};
    TCHAR szProcName[MAX_PATH] = {0};
    TCHAR * pProcName = szProcName;

    GetWindowText(hwnd, tmpbuf, _countof(tmpbuf));
    if (GetClassName(hwnd, szClassName, _countof(szClassName))==0)
        szClassName[0] = 0;
    DWORD pid = 0;
    GetWindowThreadProcessId(hwnd, &pid);
    if (pid)
    {
        HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
        if (hProc)
        {
            if (GetProcessImageFileName(hProc, szProcName, _countof(szProcName)))
            {
                pProcName = _tcsrchr(szProcName, '\\');
                if (pProcName)
                    pProcName++;
                else
                    pProcName = szProcName;
            }
            CloseHandle(hProc);
        }
    }
    _sntprintf_s(buf, bufsize, _TRUNCATE, _T("Window 0x%p : Process \"%s\" : class \"%s\" : title \"%s\""), hwnd, pProcName, szClassName, tmpbuf);
}
Пример #12
0
void
vMBPortLog( eMBPortLogLevel eLevel, const TCHAR * szModule, const TCHAR * szFmt, ... )
{
    TCHAR    szBuf[512];
    int      i;
    va_list         args;
    static const LPTSTR arszLevel2Str[] =
    { _T( "DEBUG" ), _T( "INFO" ), _T( "WARN" ), _T( "ERROR" ) };

    i = _sntprintf_s( szBuf, _countof(szBuf) , _TRUNCATE, _T( "%s: %s: " ),
                      arszLevel2Str[eLevel], szModule );

    if( i != 0 )
    {
        va_start( args, szFmt );
        i += _vsntprintf_s( &szBuf[i], _countof(szBuf) - i, _TRUNCATE, szFmt, args );
        va_end( args );
    }

    if( i != 0 )
    {
        if( eLevel == MB_LOG_DEBUG )
        {
            OutputDebugString( szBuf );
        }
        else
        {
            _fputts( szBuf, stderr );
        }
    }

}
Пример #13
0
static HINSTANCE _AfxLoadLangDLL(LPCTSTR pszFormat, LPCTSTR pszPath, LCID lcid)
{
	TCHAR szLangDLL[_MAX_PATH+14];
	TCHAR szLangCode[4];
	HINSTANCE hInstance;

	if (lcid == LOCALE_SYSTEM_DEFAULT)
	{
		Checked::tcscpy_s(szLangCode, _countof(szLangCode), _T("LOC"));
	}
	else
	{
		int nResult;

		nResult = ::GetLocaleInfo(lcid, LOCALE_SABBREVLANGNAME, szLangCode, 4);
		if (nResult == 0)
			return NULL;
		ASSERT( nResult == 4 );
	}

	int ret;
	ATL_CRT_ERRORCHECK_SPRINTF(ret = _sntprintf_s(szLangDLL,_countof(szLangDLL),_countof(szLangDLL)-1,pszFormat,pszPath,szLangCode));
	if(ret == -1 || ret >= _countof(szLangDLL))
	{
		ASSERT(FALSE);
		return NULL;
	}

	hInstance = ::LoadLibrary(szLangDLL);

	return hInstance;
}
Пример #14
0
/*
  Sets the string for the exit action corresponding to the exit code.

  ret is a pointer to an unsigned long containing the exit code.
  If ret is NULL, we retrieve the default exit action unconditionally.

  action is a buffer which receives the string.

  default_action is a pointer to a bool which is set to false if there
  was an explicit string for the given exit code, or true if we are
  returning the default action.

  Returns: 0 on success.
           1 on error.
*/
int get_exit_action(const TCHAR *service_name, unsigned long *ret, TCHAR *action, bool *default_action) {
  /* Are we returning the default action or a status-specific one? */
  *default_action = ! ret;

  /* Try to open the registry */
  HKEY key = open_registry(service_name, NSSM_REG_EXIT, KEY_READ);
  if (! key) return 1;

  unsigned long type = REG_SZ;
  unsigned long action_len = ACTION_LEN;

  TCHAR code[16];
  if (! ret) code[0] = _T('\0');
  else if (_sntprintf_s(code, _countof(code), _TRUNCATE, _T("%lu"), *ret) < 0) {
    RegCloseKey(key);
    return get_exit_action(service_name, 0, action, default_action);
  }
  if (RegQueryValueEx(key, code, 0, &type, (unsigned char *) action, &action_len) != ERROR_SUCCESS) {
    RegCloseKey(key);
    /* Try again with * as the key if an exit code was defined */
    if (ret) return get_exit_action(service_name, 0, action, default_action);
    return 0;
  }

  /* Close registry */
  RegCloseKey(key);

  return 0;
}
Пример #15
0
int set_hook(const TCHAR *service_name, const TCHAR *hook_event, const TCHAR *hook_action, TCHAR *cmd) {
  /* Try to open the registry */
  TCHAR registry[KEY_LENGTH];
  if (_sntprintf_s(registry, _countof(registry), _TRUNCATE, _T("%s\\%s"), NSSM_REG_HOOK, hook_event) < 0) {
    log_event(EVENTLOG_ERROR_TYPE, NSSM_EVENT_OUT_OF_MEMORY, _T("hook registry"), _T("set_hook()"), 0);
    return 1;
  }

  HKEY key;
  long error;

  /* Don't create keys needlessly. */
  if (! _tcslen(cmd)) {
    key = open_registry(service_name, registry, KEY_READ, false);
    if (! key) return 0;
    error = RegQueryValueEx(key, hook_action, 0, 0, 0, 0);
    RegCloseKey(key);
    if (error == ERROR_FILE_NOT_FOUND) return 0;
  }

  key = open_registry(service_name, registry, KEY_WRITE);
  if (! key) return 1;

  int ret = 1;
  if (_tcslen(cmd)) ret = set_string(key, (TCHAR *) hook_action, cmd, true);
  else {
    error = RegDeleteValue(key, hook_action);
    if (error == ERROR_SUCCESS || error == ERROR_FILE_NOT_FOUND) ret = 0;
  }

  /* Close registry */
  RegCloseKey(key);

  return ret;
}
Пример #16
0
bool WinShm::create( size_t size )
{
	hFile = NULL;
	TCHAR keyname[80];
	id = 0;
	while( !hFile ) {
		id++;
		_sntprintf_s( keyname, 80, TEXT("skypekit-surface-%i"), id );
		hFile = CreateFileMapping( INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, size, keyname );
		if ( hFile == NULL ) {
			// printf( "Failed to create mapping: %d\n", GetLastError() );
			id = 0;
			return false;
		}
		if ( GetLastError() == ERROR_ALREADY_EXISTS ) {
			CloseHandle( hFile );
			hFile = NULL;
		}
	}
	datap = MapViewOfFile( hFile, FILE_MAP_ALL_ACCESS, 0, 0, 0 );
	if ( !datap ) {
		// printf( "Failed to map file: %d\n", GetLastError() );
		CloseHandle( hFile );
		id = 0;
		hFile = NULL;
		return false;
	}
	m_size=size;
	return true;
}
Пример #17
0
BOOL install_util::DeleteFolder(LPCTSTR pszFolder)
{
  if(IsFolderEmpty(pszFolder))
    return RemoveDirectory(pszFolder);

  //下面的实现据说有隐患。应改为递归删除所有子文件及文件夹
  _TCHAR szPath[MAX_PATH + 1] = {0};
  _sntprintf_s(szPath, _countof(szPath), sizeof(szPath), _TEXT("%s%c"), pszFolder, 0);

  SHFILEOPSTRUCT fos ;
  ZeroMemory(&fos, sizeof( fos)) ;
  fos.hwnd = HWND_DESKTOP;
  fos.wFunc = FO_DELETE ;
  fos.fFlags = FOF_NOCONFIRMATION | FOF_SILENT;
  fos.pFrom = szPath;

  // 删除文件夹及其内容
  if (0 == SHFileOperation(&fos))
    return TRUE;

  wstring tmpFile = szPath;
  tmpFile += L"_yytmp";
  if (MoveFileEx(szPath, tmpFile.c_str(), MOVEFILE_REPLACE_EXISTING))
    return MoveFileEx(tmpFile.c_str(),NULL,MOVEFILE_DELAY_UNTIL_REBOOT);

  return FALSE;
} 
Пример #18
0
void AFXAPI AfxTextFloatFormat(CDataExchange* pDX, int nIDC,
	void* pData, double value, int nSizeGcvt)
{
	ASSERT(pData != NULL);

	pDX->PrepareEditCtrl(nIDC);
	HWND hWndCtrl;
	pDX->m_pDlgWnd->GetDlgItem(nIDC, &hWndCtrl);
	
	const int TEXT_BUFFER_SIZE = 400;
	TCHAR szBuffer[TEXT_BUFFER_SIZE];
	if (pDX->m_bSaveAndValidate)
	{
		::GetWindowText(hWndCtrl, szBuffer, _countof(szBuffer));
		double d;
		if (_sntscanf_s(szBuffer, _countof(szBuffer), _T("%lf"), &d) != 1)
		{
			AfxMessageBox(AFX_IDP_PARSE_REAL);
			pDX->Fail();            // throws exception
		}
		if (nSizeGcvt == FLT_DIG)
			*((float*)pData) = (float)d;
		else
			*((double*)pData) = d;
	}
	else
	{
		ATL_CRT_ERRORCHECK_SPRINTF(_sntprintf_s(szBuffer, _countof(szBuffer), _countof(szBuffer) -1, _T("%.*g"), nSizeGcvt, value));
		AfxSetWindowText(hWndCtrl, szBuffer);
	}
}
Пример #19
0
StdString HashSHA1Impl::GetFileHash(StdString strFile)
{
	StdString strRet;

	HANDLE hFile = CreateFile(strFile.c_str(), GENERIC_READ, FILE_SHARE_READ,
		NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hFile != INVALID_HANDLE_VALUE)
	{
		HANDLE hMapping = CreateFileMapping(hFile, NULL, PAGE_WRITECOPY, 0, 0, NULL);
		if (hMapping != INVALID_HANDLE_VALUE)
		{
			PBYTE pByte = (PBYTE)MapViewOfFile(hMapping, FILE_MAP_COPY, 0, 0, 0);
			unsigned long dwSize = GetFileSize(hFile, NULL);			
			
			Reset();
			Input(pByte, dwSize);
			unsigned int digest[5] = {0};
			Result(digest);
			TCHAR szRes[48] = _T("");
			_sntprintf_s(szRes, 48, 48, _T("%x%x%x%x%x"),
				digest[0], digest[1], digest[2], digest[3], digest[4]);
			strRet = szRes;

			UnmapViewOfFile(pByte);
			CloseHandle(hMapping);
		}
		else
		{
			CloseHandle(hFile);
		}
	}
	return strRet;
}
Пример #20
0
static int elevate(int argc, TCHAR **argv, unsigned long message) {
  print_message(stderr, message);

  SHELLEXECUTEINFO sei;
  ZeroMemory(&sei, sizeof(sei));
  sei.cbSize = sizeof(sei);
  sei.lpVerb = _T("runas");
  sei.lpFile = (TCHAR *) nssm_imagepath();

  TCHAR *args = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, EXE_LENGTH * sizeof(TCHAR));
  if (! args) {
    print_message(stderr, NSSM_MESSAGE_OUT_OF_MEMORY, _T("GetCommandLine()"), _T("elevate()"));
    return 111;
  }

  /* Get command line, which includes the path to NSSM, and skip that part. */
  _sntprintf_s(args, EXE_LENGTH, _TRUNCATE, _T("%s"), GetCommandLine());
  size_t s = _tcslen(argv[0]) + 1;
  if (args[0] == _T('"')) s += 2;
  while (isspace(args[s])) s++;

  sei.lpParameters = args + s;
  sei.nShow = SW_SHOW;

  unsigned long exitcode = 0;
  if (! ShellExecuteEx(&sei)) exitcode = 100;

  HeapFree(GetProcessHeap(), 0, (void *) args);
  return exitcode;
}
Пример #21
0
//更新信息
bool CUserCompanionList::UpdateCompanionInfo(HTREEITEM hTreeItem, tagCompanionItem * pCompanionInfo)
{
	//效验参数
	ASSERT(hTreeItem!=NULL);
	if (hTreeItem==NULL) return false;

	//更新处理
	if (GetTreeItemCompanion(hTreeItem)==pCompanionInfo->Companion)
	{
		//生成标题
		TCHAR szTreeTitle[128]=TEXT("");
		_sntprintf_s(szTreeTitle,CountArray(szTreeTitle),TEXT("%s [ %ld ]"),pCompanionInfo->szAccounts,pCompanionInfo->dwGameID);

		//更新树项
		SetItemText(hTreeItem,szTreeTitle);
	}
	else
	{
		//删除树项
		DeleteItem(hTreeItem);
		InsertCompanionInfo(pCompanionInfo);
	}
	
	return true;
}
Пример #22
0
unsigned GetVMPipeNameW(unsigned PID, wchar_t *pName, size_t MaxNameLength, bool TryReconstructingIfNotAvailable)
{
	if (!pName || !PID)
		return 0;
	pName[0] = 0;

	TCHAR tszMappingName[MAX_PATH];
	_sntprintf_s(tszMappingName, __countof(tszMappingName), _TRUNCATE, tszMappingNameFormat, PID);
	//HANDLE hMapping = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READONLY, 0, sizeof(KdClientStatus), tszMappingName);
	HANDLE hMapping = OpenFileMapping(FILE_MAP_READ, FALSE, tszMappingName);
	bool bOldVersion = false;
	KdClientStatus *pStatus = (KdClientStatus *)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, sizeof(KdClientStatus));
	if (!pStatus)
	{
		bOldVersion = true;
		pStatus = (KdClientStatus *)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
	}
	BazisLib::DateTime startTime = BazisLib::DateTime::Now();
	if ((hMapping == INVALID_HANDLE_VALUE) || !pStatus)
	{
		if (hMapping != INVALID_HANDLE_VALUE)
			CloseHandle(hMapping);
		if (!TryReconstructingIfNotAvailable)
			return 0;
		
		TCHAR tszSession[MAX_PATH] = {0,};
		GetVMSessionNameW(PID, tszSession, __countof(tszSession));
		if (!tszSession[0])
			return 0;
		unsigned len = _snwprintf(pName, MaxNameLength, L"\\\\.\\pipe\\kd_%s", tszSession);
		for (int i = 0; pName[i]; i++)
			if (pName[i] == ' ')
				pName[i] = '_';
		return len;
	}
	unsigned len = (unsigned)wcslen(pStatus->PipeName);
	wcsncpy_s(pName, MaxNameLength, pStatus->PipeName, _TRUNCATE);

	if ((bOldVersion || (pStatus->HostSideDLLVersion != VIRTUALKD_VER_INT)) && !s_bUserWarnedAboutVersion)
	{
		unsigned oldVersion = 0, newVersion = VIRTUALKD_VER_INT;
		if (pStatus)
			oldVersion = pStatus->HostSideDLLVersion;

		oldVersion >>= 16;
		newVersion >>= 16;

		s_bUserWarnedAboutVersion = true;
		MessageBox(0, 
			BazisLib::String::sFormat(_T("One of the virtual machines has an old version of KDCLIENT.DLL/VBOXDD.DLL loaded (%d.%d.%d expected, %d.%d.%d found). Please install the latest file versions, as described on VirtualKD website, and restart your virtual machines."),
			(oldVersion >> 12) & 0x0F,
			(oldVersion >> 8) & 0x0F,
			(oldVersion >> 4) & 0x0F,
			(newVersion >> 12) & 0x0F,
			(newVersion >> 8) & 0x0F,
			(newVersion >> 4) & 0x0F).c_str(),
			_T("VirtualKD"),
			MB_ICONWARNING | MB_TASKMODAL);
	}
Пример #23
0
void UUIDToString(UUID const &Value, LPTSTR String) {
    int result = _sntprintf_s(String, 36 + 1, 36 + 1, _T("%08X-%04hX-%04hX-%02X%02X-%02X%02X%02X%02X%02X%02X"),
                              Value.Data1, Value.Data2, Value.Data3,
                              Value.Data4[0], Value.Data4[1], Value.Data4[2], Value.Data4[3],
                              Value.Data4[4], Value.Data4[5], Value.Data4[6], Value.Data4[7]);
    if (result < 0)
        FAIL(_T("Converting from GUID to string failed with error code %d"), errno);
}
Пример #24
0
ErrNo Calculus::GetStart_D(int iSelectIndex)
{
	PCTSTR pErrInfo;
	TCHAR szBuffer[MAXSIZE];
	int nLength;
	ErrNo err;

	//获取间隔大小
	if(err = GetLine_Double(GetDlgItem(hDlg,EditControlID_D[0]),&interval))
	{
		pErrInfo = FormatError(err);
		_sntprintf_s(szBuffer,_countof(szBuffer),MAXSIZE,TEXT("错误ID:%d\r\n错误信息:%s\r\n补充信息:输入间隔大小数据错误"),err,pErrInfo);
		MessageBox(hDlg,szBuffer,TEXT("错误"),MB_ICONERROR);
		return err;
	}
	//获取所求点
	if(err = GetLine_Double(GetDlgItem(hDlg,EditControlID_D[1]),&value))
	{
		pErrInfo = FormatError(err);
		_sntprintf_s(szBuffer,_countof(szBuffer),MAXSIZE,TEXT("错误ID:%d\r\n错误信息:%s\r\n补充信息:输入所求点数据错误"),err,pErrInfo);
		MessageBox(hDlg,szBuffer,TEXT("错误"),MB_ICONERROR);
		return err;
	}

	//获取函数表达式
	if(!(nLength = Edit_GetText(GetDlgItem(hDlg,EditControlID_D[2]),expression,MAXSIZE)))
	{
		err = NO_DATA_INPUT;
		pErrInfo = FormatError(err);
		_sntprintf_s(szBuffer,_countof(szBuffer),MAXSIZE,TEXT("错误ID:%d\r\n错误信息:%s\r\n补充信息:未输入微分计算所需的表达式"),err,pErrInfo);
		MessageBox(hDlg,szBuffer,TEXT("错误"),MB_ICONERROR);
		return err;
	}

	//复制一份函数表达式
	nLength = _tcslen(expression) + 1;
	for(int i=0;i<nLength;i++)
		exp_store[i] = expression[i];

	//算法选择
	err = Algorithm_Choice_D(iSelectIndex);

	//输出结果
	OutputResult_D(iSelectIndex,err);
	return 0;
}
Пример #25
0
//查询信息
LPCTSTR CWinFileInfo::QueryValue(LPCTSTR lpszValueName)
{
    UINT nQuerySize=0;
    LPTSTR pszValue=NULL;
	TCHAR szBlockName[128]=TEXT("");
	_sntprintf_s(szBlockName,sizeof(szBlockName),TEXT("\\StringFileInfo\\%08lx\\%s"),m_dwLangCharset,lpszValueName);
    ::VerQueryValue(m_cbInfoBuffer,szBlockName,(LPVOID *)&pszValue,&nQuerySize);
	return pszValue;
}
Пример #26
0
//加入关系
bool CUserCompanionList::InsertCompanionInfo(const tagCompanionItem * pCompanionInfo)
{
	//效验参数
	ASSERT(pCompanionInfo!=NULL);
	if (pCompanionInfo==NULL) return false;

	//变量定义
	INT nImageIndex=0;
	HTREEITEM hParentTreeItem=NULL;

	//插入准备
	switch (pCompanionInfo->Companion)
	{
	case enCompanion_Friend:		//游戏好友
		{
			hParentTreeItem=m_hItemFriend;
			nImageIndex=IMAGE_FRIEND_ITEM;
			break;
		}
	case enCompanion_Detest:		//厌恶玩家
		{
			hParentTreeItem=m_hItemDetest;
			nImageIndex=IMAGE_DETEST_ITEM;
			break;
		}
	default:						//默认玩家
		{
			hParentTreeItem=m_hItemNormal;
			nImageIndex=IMAGE_NORMAL_ITEM;
			break;
		}
	}

	//生成标题
	TCHAR szTreeTitle[128]=TEXT("");
	_sntprintf_s(szTreeTitle,CountArray(szTreeTitle),TEXT("%s [ %ld ]"),pCompanionInfo->szAccounts,pCompanionInfo->dwGameID);

	//变量定义
	TV_INSERTSTRUCT InsertStruct;
	ZeroMemory(&InsertStruct,sizeof(InsertStruct));

	//构造变量
	InsertStruct.hInsertAfter=TVI_LAST;
	InsertStruct.hParent=hParentTreeItem;
	InsertStruct.item.iImage=nImageIndex;
	InsertStruct.item.iSelectedImage=nImageIndex;
	InsertStruct.item.pszText=szTreeTitle;
	InsertStruct.item.lParam=(LPARAM)pCompanionInfo;
	InsertStruct.item.cchTextMax=CountArray(szTreeTitle);
	InsertStruct.item.mask=TVIF_IMAGE|TVIF_SELECTEDIMAGE|TVIF_TEXT|TVIF_PARAM;

	//插入子项
	InsertItem(&InsertStruct);

	return true;
}
Пример #27
0
LPCTSTR TSyncObjPoolException::Why(void) const {
	if (rWhy.length() == 0) {
		TString tWhy = Exception::Why();
		const_cast<TString*>(&rWhy)->resize(__DefErrorMsgBufferLen, NullWChar);
		int MsgLen = _sntprintf_s((TCHAR*)&rWhy.front(), __DefErrorMsgBufferLen, _TRUNCATE, SOPLogHeader _T("%s"), SyncObjPoolName.c_str(), tWhy.c_str());
		if (MsgLen >= 0)
			const_cast<TString*>(&rWhy)->resize(MsgLen);
	}
	return rWhy.c_str();
}
Пример #28
0
LPCTSTR Exception::Why(void) const {
	if (rWhy.length() == 0) {
		LPCTSTR dSource = (Source.length() > 0) ? Source.c_str() : ExceptSourceNone;
		LPCTSTR dReason = (Reason.length() > 0) ? Reason.c_str() : ExceptReasonNone;
		const_cast<TString*>(&rWhy)->assign(__DefErrorMsgBufferLen, NullWChar);
		int MsgLen = _sntprintf_s((TCHAR*)&rWhy.front(), __DefErrorMsgBufferLen, _TRUNCATE, FExceptionMessage, dSource, dReason);
		if (MsgLen >= 0)
			const_cast<TString*>(&rWhy)->resize(MsgLen);
	}
	return rWhy.c_str();
}
Пример #29
0
TString UUIDToString(UUID const &Val) {
	TString Ret(40, NullTChar);
	Cardinal128 const &Value = (Cardinal128 const &)Val;
	int result = _sntprintf_s((PTCHAR)Ret.data(), 36 + 1, 36 + 1, _T("%08X-%04hX-%04hX-%02X%02X-%02X%02X%02X%02X%02X%02X"),
							  Value.U32[0], Value.U16[2], Value.U16[3],
							  Value.U8[8], Value.U8[9], Value.U8[10], Value.U8[11],
							  Value.U8[12], Value.U8[13], Value.U8[14], Value.U8[15]);
	if (result < 0)
		FAIL(_T("Converting from GUID to string failed with error code %d"), errno);
	return Ret;
}
Пример #30
0
void CDeviceProp::PrintTextToEditBox(CEdit *pEditBox, BSTR bstrPrintText, HRESULT hrCheck)
{
	TCHAR tszPropertyString[DATA_BUFSIZE];
	if( hrCheck != S_OK ){
		PrintErrorText(hrCheck);
	}
	else{
		_sntprintf_s(tszPropertyString, DATA_BUFSIZE, _TRUNCATE, _T("%S"), bstrPrintText);
		(*pEditBox).SetWindowText(tszPropertyString);
	}

}