/// <summary>
/// Load an image from a resource into a buffer
/// </summary>
/// <param name="resourceName">name of image resource to load</param>
/// <param name="resourceType">type of resource to load</param>
/// <param name="cOutputBuffer">size of output buffer, in bytes</param>
/// <param name="outputBuffer">buffer that will hold the loaded image</param>
/// <returns>S_OK on success, otherwise failure code</returns>
HRESULT CBackgroundRemovalBasics::LoadResourceImage(
    PCWSTR resourceName,
    PCWSTR resourceType,
    DWORD cOutputBuffer,
    BYTE* outputBuffer
    )
{
    HRESULT hr = S_OK;

    IWICImagingFactory* pIWICFactory = NULL;
    IWICBitmapDecoder* pDecoder = NULL;
    IWICBitmapFrameDecode* pSource = NULL;
    IWICStream* pStream = NULL;
    IWICFormatConverter* pConverter = NULL;
    IWICBitmapScaler* pScaler = NULL;

    HRSRC imageResHandle = NULL;
    HGLOBAL imageResDataHandle = NULL;
    void *pImageFile = NULL;
    DWORD imageFileSize = 0;

    hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pIWICFactory);
    if ( FAILED(hr) ) return hr;

    // Locate the resource.
    imageResHandle = FindResourceW(HINST_THISCOMPONENT, resourceName, resourceType);
    hr = imageResHandle ? S_OK : E_FAIL;

    if (SUCCEEDED(hr))
    {
        // Load the resource.
        imageResDataHandle = LoadResource(HINST_THISCOMPONENT, imageResHandle);
        hr = imageResDataHandle ? S_OK : E_FAIL;
    }

    if (SUCCEEDED(hr))
    {
        // Lock it to get a system memory pointer.
        pImageFile = LockResource(imageResDataHandle);
        hr = pImageFile ? S_OK : E_FAIL;
    }

    if (SUCCEEDED(hr))
    {
        // Calculate the size.
        imageFileSize = SizeofResource(HINST_THISCOMPONENT, imageResHandle);
        hr = imageFileSize ? S_OK : E_FAIL;
    }

    if (SUCCEEDED(hr))
    {
        // Create a WIC stream to map onto the memory.
        hr = pIWICFactory->CreateStream(&pStream);
    }

    if (SUCCEEDED(hr))
    {
        // Initialize the stream with the memory pointer and size.
        hr = pStream->InitializeFromMemory(
            reinterpret_cast<BYTE*>(pImageFile),
            imageFileSize
            );
    }

    if (SUCCEEDED(hr))
    {
        // Create a decoder for the stream.
        hr = pIWICFactory->CreateDecoderFromStream(
            pStream,
            NULL,
            WICDecodeMetadataCacheOnLoad,
            &pDecoder
            );
    }

    if (SUCCEEDED(hr))
    {
        // Create the initial frame.
        hr = pDecoder->GetFrame(0, &pSource);
    }

    if (SUCCEEDED(hr))
    {
        // Convert the image format to 32bppPBGRA
        // (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
        hr = pIWICFactory->CreateFormatConverter(&pConverter);
    }

    if (SUCCEEDED(hr))
    {
        hr = pIWICFactory->CreateBitmapScaler(&pScaler);
    }

    if (SUCCEEDED(hr))
    {
        hr = pScaler->Initialize(
            pSource,
            m_colorWidth,
            m_colorHeight,
            WICBitmapInterpolationModeCubic
            );
    }

    if (SUCCEEDED(hr))
    {
        hr = pConverter->Initialize(
            pScaler,
            GUID_WICPixelFormat32bppPBGRA,
            WICBitmapDitherTypeNone,
            NULL,
            0.f,
            WICBitmapPaletteTypeMedianCut
            );
    }

    UINT width = 0;
    UINT height = 0;
    if (SUCCEEDED(hr))
    {
        hr = pConverter->GetSize(&width, &height);
    }

    // make sure the output buffer is large enough
    if (SUCCEEDED(hr))
    {
        if ( width*height*cBytesPerPixel > cOutputBuffer )
        {
            hr = E_FAIL;
        }
    }

    if (SUCCEEDED(hr))
    {
        hr = pConverter->CopyPixels(NULL, width*cBytesPerPixel, cOutputBuffer, outputBuffer);
    }

    SafeRelease(pScaler);
    SafeRelease(pConverter);
    SafeRelease(pSource);
    SafeRelease(pDecoder);
    SafeRelease(pStream);
    SafeRelease(pIWICFactory);

    return hr;
}
Esempio n. 2
0
//////////////////////////////////////////////////////////////////////////////////////
//
// RESOURCES => Extraction d'une ressource dans le rép. temp. de l'utilisateur
//
//
void resource_extract(char* name)
{
	// on créé un sous-répertoire dans le répertoire temporaire de l'utilisateur
	char Path2[MAX_PATH+1];
	GetTempPath(sizeof Path2, Path2);
	strcat(Path2, "\\SpaceInvaders-OpenGL");

	// déclarations et initialisations
	char		m_szFilename2[MAX_PATH];
	HINSTANCE	m_hModule2	= NULL;
	char		m_szType2[MAX_PATH];

	LPCSTR szType2		= "BINARY";
	LPCSTR szFilename2	= strcat(strcat(Path2, "\\"),name);

	memset(m_szType2,0,sizeof m_szType2);
	memcpy(m_szType2,(void*)szType2,strlen(szType2));

	memset(m_szFilename2,0,sizeof m_szFilename2);
	memcpy(m_szFilename2,szFilename2,strlen(szFilename2));

	// extraction de la ressource
	HRSRC hRes2;
	if (strcmp(name,"font.tga") == NULL)
		hRes2 = FindResource(m_hModule2, MAKEINTRESOURCE(IDR_BINARY_FONT_TGA), m_szType2);

	else if (strcmp(name,"player.3ds") == NULL)
		hRes2 = FindResource(m_hModule2, MAKEINTRESOURCE(IDR_BINARY_PLAYER_3DS), m_szType2);

	else if (strcmp(name,"ship.3ds") == NULL)
		hRes2 = FindResource(m_hModule2, MAKEINTRESOURCE(IDR_BINARY_SHIP_3DS), m_szType2);

	else if (strcmp(name,"sphere_ogive.3ds") == NULL)
		hRes2 = FindResource(m_hModule2, MAKEINTRESOURCE(IDR_BINARY_SPHERE_OGIVE_3DS), m_szType2);

	else if (strcmp(name,"supership.3ds") == NULL)
		hRes2 = FindResource(m_hModule2, MAKEINTRESOURCE(IDR_BINARY_SUPERSHIP_3DS), m_szType2);

	else if (strcmp(name,"fighter_laser.3ds") == NULL)
		hRes2 = FindResource(m_hModule2, MAKEINTRESOURCE(IDR_BINARY_FIGHTER_LASER_3DS), m_szType2);

	else return;

	DWORD	dwDataSize2	= SizeofResource(m_hModule2,hRes2);
	HGLOBAL	hGlob2		= LoadResource(m_hModule2,hRes2);
	LPVOID	pData2		= LockResource(hGlob2);

	// création du fichier
	HANDLE	hFile2 = CreateFile (m_szFilename2, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

	if( hFile2 == INVALID_HANDLE_VALUE )
	{
		UnlockResource(hGlob2);
		FreeResource(hGlob2);	
	}

	DWORD	dwBytesWritten2 = 0;

	if( !WriteFile(hFile2,pData2,dwDataSize2,&dwBytesWritten2,NULL) 
		||
		dwBytesWritten2 != dwDataSize2)
	{
		CloseHandle(hFile2);
		UnlockResource(hGlob2);
		FreeResource(hGlob2);	
		if(DeleteFile(m_szFilename2))
			memset(m_szFilename2,0,sizeof m_szFilename2);
	}

	CloseHandle(hFile2);
	UnlockResource(hGlob2);
	FreeResource(hGlob2);
}
Esempio n. 3
0
CStory::CStory(HWND hWindow)
/***********************************************************************/
{
	STRING szString, szFile; 
	FNAME szFileName;
	HRSRC hResource;
	HGLOBAL hData;
	LPSHORT lpShortData;
	DWORD dwSize;
	int id;

	m_hWnd = hWindow;
	m_nRects = 0;
	m_hMCIfile = NULL;
	m_iHighlight = 0;
	m_pDib = NULL;
	m_lpWordData = NULL;
	m_fPlaying = FALSE;
	m_szStoryFile[0] = '\0';
	m_szDibFile[0] = '\0';
	m_hHotSpotCursor = LoadCursor(GetWindowInstance(hWindow), MAKEINTRESOURCE(ID_POINTER));
	m_fCursorEnabled = TRUE;
	m_fMappedToPalette = FALSE;

	GetModuleFileName(GetWindowInstance(hWindow), szFileName, sizeof(szFileName));
	StripFile(szFileName);

	GetWindowText(hWindow, szString, sizeof(szString));
	for (int i = 0; i < 2; ++i)
	{
		if (GetStringParm(szString, i, ',', szFile))
		{
			if (lstrcmpi(Extension(szFile), ".wav") == 0)
			{
				lstrcpy(m_szStoryFile, szFileName);
				lstrcat(m_szStoryFile, szFile);
			}
			else
			{
				lstrcpy(m_szDibFile, szFileName);
				lstrcat(m_szDibFile, szFile);
			}
		}
		else
			break;
	}

	id = GetDlgCtrlID(hWindow)-IDC_STORY;	
	if (id)
		wsprintf(szString, "story%d", id+1);
	else
		lstrcpy(szString, "story");
		
	id = App.GetSceneNo(GetParent(hWindow));
	if ( !(hResource = FindResource( App.GetInstance(), MAKEINTRESOURCE(id), szString )) )
		return;
	if ( !(dwSize = SizeofResource( App.GetInstance(), hResource )) )
		return;
	if ( !(hData = LoadResource( App.GetInstance(), hResource )) )
		return;
	if ( !(lpShortData = (LPSHORT)LockResource( hData )) )
		{
		FreeResource( hData );
		return;
		}
	m_nRects = (int)(dwSize / (sizeof(WORD) * 6));
	if (m_nRects)
	{
		m_lpWordData = (LPWORD_DATA)AllocX( (m_nRects * sizeof(WORD_DATA)), GMEM_ZEROINIT|GMEM_SHARE );
		if (!m_lpWordData)
			return;
		for (int i = 0; i < m_nRects; ++i)
		{
			m_lpWordData[i].dwFrom = (int)*lpShortData++;
			m_lpWordData[i].dwTo = (int)*lpShortData++;
			m_lpWordData[i].rArea.left = (int)*lpShortData++;
			m_lpWordData[i].rArea.top = (int)*lpShortData++;
			m_lpWordData[i].rArea.right = (int)*lpShortData++;
			m_lpWordData[i].rArea.bottom = (int)*lpShortData++;
		}
	}
	UnlockResource( hData );
	FreeResource( hData );
}
Esempio n. 4
0
int main(int argc, char* argv[])
{
	SDAHEADER SDAHeader;
	FILE *fout;
	char szOutput[MAX_PATH+1];
	char szDirectory[MAX_PATH+1];
	FILELIST *flindex,*fl,*flnext;
	GETPUTINFO gpi;
	DWORD dwStubSize;
	HRSRC hRCStub;
	HGLOBAL hGBStub;
	char *pStubData;
	HMODULE hModule;

	if(argc!=3)
	{
		printf("MakeSEA <output filename> <input directory>\n");
		return 0;
	}

	strcpy(szOutput,argv[1]);
	strcpy(szDirectory,argv[2]);

	fout=fopen(szOutput,"wb");

	if(fout==0)
	{
		printf("Could not open output file for writing\n");
		return 0;
	}

	memset(&SDAHeader,0x00,sizeof(SDAHEADER));
	memcpy(&(SDAHeader.szPGPSDA),"PGPSEA",6);

	// Write out stub to disk from resources
	hModule=GetModuleHandle(NULL);

	hRCStub=FindResource(hModule,
		MAKEINTRESOURCE(IDR_SEASTUB),
		RT_RCDATA);

	dwStubSize=SizeofResource(hModule,hRCStub);

	hGBStub=LoadResource(hModule,hRCStub);
	pStubData=(char *)LockResource(hGBStub);

	fwrite(pStubData,1,dwStubSize,fout);
	SDAHeader.offset=dwStubSize;

	// Get files from directory parameter
	fl=flindex=NULL;

	AddToFileList(&flindex,szDirectory,NULL);

	// Reverse list since we need directories first
	while(flindex!=NULL)
	{
		flnext=flindex->next;
		
		flindex->next=fl;
		fl=flindex;

		flindex=flnext;
	}

	memset(&gpi,0x00,sizeof(GETPUTINFO));

	gpi.fout=fout;
	gpi.SDAHeader=&SDAHeader;
	gpi.fl=fl;
	gpi.bFeedFilename=TRUE;

	// Find beginning of SEA directory tree
	gpi.PathHead=strlen(gpi.fl->name);
	if(gpi.fl->name[gpi.PathHead]!='\\')
		gpi.PathHead++;
	gpi.fl=gpi.fl->next;

	Deflate_Compress(&gpi);

	FreeFileList(fl);

	fwrite(&SDAHeader,1,sizeof(SDAHEADER),fout);

	fclose(fout);

	if(gpi.CancelOperation)
	{
		remove(szOutput);
	}

	return 0;
}
Esempio n. 5
0
XMLNode xmlLoadFromResource(const TCHAR* lpName,
                            LPCTSTR tag, 
                            XMLResults *pResults) {
  LPTSTR lpRes; 
  HRSRC hResInfo;
  HGLOBAL hRes; 
  int l, len;

  // Find the xml resource.
  hResInfo = FindResource (hInst, lpName, TEXT("XMLDialog")); 

  if (hResInfo == NULL) {
    MessageBoxX(hWndMainWindow,
      TEXT("Can't find resource"),
      TEXT("Dialog error"),
      MB_OK|MB_ICONEXCLAMATION);

    // unable to find the resource
    return XMLNode::emptyXMLNode;
  }

  // Load the wave resource. 
  hRes = LoadResource (hInst, hResInfo); 

  if (hRes == NULL) {
    MessageBoxX(hWndMainWindow,
      TEXT("Can't load resource"),
      TEXT("Dialog error"),
      MB_OK|MB_ICONEXCLAMATION);

    // unable to load the resource
    return XMLNode::emptyXMLNode;
  }

  // Lock the wave resource and do something with it. 
  lpRes = (LPTSTR)LockResource (hRes);
  
  if (lpRes) {
    l = SizeofResource(hInst,hResInfo);
    if (l>0) {
      char *buf= (char*)malloc(l+2);
      if (!buf) {
	//StartupStore(_T("------ LoadFromRes malloc error%s"),NEWLINE); // 100101
        MessageBoxX(hWndMainWindow,
                    TEXT("Can't allocate memory"),
                    TEXT("Dialog error"),
                    MB_OK|MB_ICONEXCLAMATION);
        // unable to allocate memory
        return XMLNode::emptyXMLNode;
      }
      strncpy(buf,(char*)lpRes,l);
      buf[l]=0; // need to explicitly null-terminate.
      buf[l+1]=0;
      len = l;      
      
#if defined(WIN32) || defined(UNDER_CE)
#ifdef _UNICODE
#if !defined(UNDER_CE) && (WINDOWSPC<1)
      if (!IsTextUnicode(buf,mmin(l,10000),NULL))
        {
#endif
          LPTSTR b2=(LPTSTR)malloc(l*2+2);
	  if (b2==NULL) StartupStore(_T(".... LoadFromRes Malloc1 failed\n")); // 100101
          MultiByteToWideChar(CP_ACP,          // code page
                              MB_PRECOMPOSED,  // character-type options
                              buf,             // string to map
                              l,               // number of bytes in string
                              b2,              // wide-character buffer
                              l*2+2);          // size of buffer
          free(buf);
          buf=(char*)b2;
          buf[l*2]= 0;
          buf[l*2+1]= 0;
#if !defined(UNDER_CE) && (WINDOWSPC<1)
        }
#endif
#else
      if (IsTextUnicode(buf,mmin(l,10000),NULL))
        {
          l>>=1;
          LPTSTR b2=(LPTSTR)malloc(l+2);
	  if (b2==NULL) StartupStore(_T(".... LoadFromRes Malloc2 failed\n")); // 100101
          WideCharToMultiByte(CP_ACP,                      // code page
                              0,                           // performance and mapping flags
                              (const WCHAR*)buf,           // wide-character string
                              l,                           // number of chars in string
                              b2,                          // buffer for new string
                              l+2,                         // size of buffer
                              NULL,                        // default for unmappable chars
                              NULL                         // set when default char used
                              );
          free(buf);
          buf=(char*)b2;
        }
#endif
#endif
      
      XMLNode x=XMLNode::parseString((LPTSTR)buf,tag,pResults);

      free(buf);
      return x;
    }
Esempio n. 6
0
static HRESULT WINAPI ResProtocol_Start(IInternetProtocol *iface, LPCWSTR szUrl,
        IInternetProtocolSink* pOIProtSink, IInternetBindInfo* pOIBindInfo,
        DWORD grfPI, HANDLE_PTR dwReserved)
{
    ResProtocol *This = ResProtocol_from_IInternetProtocol(iface);
    WCHAR *url_dll, *url_file, *url, *mime, *res_type = (LPWSTR)RT_HTML, *ptr;
    DWORD grfBINDF = 0, len;
    BINDINFO bindinfo;
    HMODULE hdll;
    HRSRC src;
    HRESULT hres;

    static const WCHAR wszRes[] = {'r','e','s',':','/','/'};

    TRACE("(%p)->(%s %p %p %08x %lx)\n", This, debugstr_w(szUrl), pOIProtSink,
            pOIBindInfo, grfPI, dwReserved);

    memset(&bindinfo, 0, sizeof(bindinfo));
    bindinfo.cbSize = sizeof(BINDINFO);
    hres = IInternetBindInfo_GetBindInfo(pOIBindInfo, &grfBINDF, &bindinfo);
    if(FAILED(hres))
        return hres;
    ReleaseBindInfo(&bindinfo);

    len = strlenW(szUrl)+16;
    url = heap_alloc(len*sizeof(WCHAR));
    hres = CoInternetParseUrl(szUrl, PARSE_ENCODE, 0, url, len, &len, 0);
    if(FAILED(hres)) {
        WARN("CoInternetParseUrl failed: %08x\n", hres);
        heap_free(url);
        IInternetProtocolSink_ReportResult(pOIProtSink, hres, 0, NULL);
        return hres;
    }

    if(len < sizeof(wszRes)/sizeof(wszRes[0]) || memcmp(url, wszRes, sizeof(wszRes))) {
        WARN("Wrong protocol of url: %s\n", debugstr_w(url));
        IInternetProtocolSink_ReportResult(pOIProtSink, E_INVALIDARG, 0, NULL);
        heap_free(url);
        return E_INVALIDARG;
    }

    url_dll = url + sizeof(wszRes)/sizeof(wszRes[0]);
    if(!(res_type = strchrW(url_dll, '/'))) {
        WARN("wrong url: %s\n", debugstr_w(url));
        IInternetProtocolSink_ReportResult(pOIProtSink, MK_E_SYNTAX, 0, NULL);
        heap_free(url);
        return MK_E_SYNTAX;
    }

    *res_type++ = 0;
    if ((url_file = strchrW(res_type, '/'))) {
        *url_file++ = 0;
    }else {
        url_file = res_type;
        res_type = (LPWSTR)RT_HTML;
    }

    /* Ignore query and hash parts. */
    if((ptr = strchrW(url_file, '?')))
        *ptr = 0;
    if(*url_file && (ptr = strchrW(url_file+1, '#')))
        *ptr = 0;

    hdll = LoadLibraryExW(url_dll, NULL, LOAD_LIBRARY_AS_DATAFILE);
    if(!hdll) {
        WARN("Could not open dll: %s\n", debugstr_w(url_dll));
        IInternetProtocolSink_ReportResult(pOIProtSink, HRESULT_FROM_WIN32(GetLastError()), 0, NULL);
        heap_free(url);
        return HRESULT_FROM_WIN32(GetLastError());
    }

    TRACE("trying to find resource type %s, name %s\n", debugstr_w(res_type), debugstr_w(url_file));

    src = FindResourceW(hdll, url_file, res_type);
    if(!src) {
        LPWSTR endpoint = NULL;
        DWORD file_id = strtolW(url_file, &endpoint, 10);
        if(endpoint == url_file+strlenW(url_file))
            src = FindResourceW(hdll, MAKEINTRESOURCEW(file_id), res_type);

        if(!src) {
            WARN("Could not find resource\n");
            IInternetProtocolSink_ReportResult(pOIProtSink,
                    HRESULT_FROM_WIN32(GetLastError()), 0, NULL);
            heap_free(url);
            return HRESULT_FROM_WIN32(GetLastError());
        }
    }

    if(This->data) {
        WARN("data already loaded\n");
        heap_free(This->data);
    }

    This->data_len = SizeofResource(hdll, src);
    This->data = heap_alloc(This->data_len);
    memcpy(This->data, LoadResource(hdll, src), This->data_len);
    This->cur = 0;

    FreeLibrary(hdll);

    hres = FindMimeFromData(NULL, url_file, This->data, This->data_len, NULL, 0, &mime, 0);
    heap_free(url);
    if(SUCCEEDED(hres)) {
        IInternetProtocolSink_ReportProgress(pOIProtSink, BINDSTATUS_MIMETYPEAVAILABLE, mime);
        CoTaskMemFree(mime);
    }

    IInternetProtocolSink_ReportData(pOIProtSink,
            BSCF_FIRSTDATANOTIFICATION | BSCF_LASTDATANOTIFICATION | BSCF_DATAFULLYAVAILABLE,
            This->data_len, This->data_len);

    IInternetProtocolSink_ReportResult(pOIProtSink, S_OK, 0, NULL);
    
    return S_OK;
}
Esempio n. 7
0
/****************************************************************************
*
*     FUNCTION: ReadIconFromEXEFile
*
*     PURPOSE:  Load an Icon Resource from a DLL/EXE file
*
*     PARAMS:   LPCTSTR szFileName - name of DLL/EXE file
*               LPCTSTR lpID - Index of DLL/EXE file
*
*     RETURNS:  LPICONRESOURCE - pointer to icon resource
*
*
\****************************************************************************/
LPICONRESOURCE CIcons::ReadIconFromEXEFile( LPCTSTR szFileName,LPTSTR lpID )
{
    LPICONRESOURCE    	lpIR = NULL, lpNew = NULL;
    HINSTANCE        	hLibrary;
    EXEDLLICONINFO    	EDII;

    // Load the DLL/EXE - NOTE: must be a 32bit EXE/DLL for this to work
    if( (hLibrary = LoadLibraryEx( szFileName, NULL, LOAD_LIBRARY_AS_DATAFILE )) == NULL )
    {
        // Failed to load - abort
        MessageBox(AfxGetMainWnd()->m_hWnd , "装入文件时出错 - 请选择一个WIN32的DLL或EXE文件!", szFileName, MB_OK );
        return NULL;
    }
    // Store the info
    EDII.szFileName = szFileName;
    EDII.hInstance = hLibrary;
    // Ask the user, "Which Icon?"
    if( lpID != NULL )
    {
        HRSRC        	hRsrc = NULL;
        HGLOBAL        	hGlobal = NULL;
        LPMEMICONDIR    lpIcon = NULL;
        UINT            i;

        // Find the group icon resource
        if( (hRsrc = FindResource( hLibrary, lpID, RT_GROUP_ICON )) == NULL )
        {
            FreeLibrary( hLibrary );
            return NULL;
        }
        if( (hGlobal = LoadResource( hLibrary, hRsrc )) == NULL )
        {
            FreeLibrary( hLibrary );
            return NULL;
        }
        if( (lpIcon = (LPMEMICONDIR)LockResource(hGlobal)) == NULL )
        {
            FreeLibrary( hLibrary );
            return NULL;
        }
        // Allocate enough memory for the images
        if( (lpIR = (LPICONRESOURCE)malloc( sizeof(ICONRESOURCE) + ((lpIcon->idCount-1) * sizeof(ICONIMAGE)) )) == NULL )
        {
            MessageBox( AfxGetMainWnd()->m_hWnd, "内存分配出错!", szFileName, MB_OK );
            FreeLibrary( hLibrary );
            return NULL;
        }
        // Fill in local struct members
        lpIR->nNumImages = lpIcon->idCount;
        lstrcpy( lpIR->szOriginalDLLFileName, szFileName );
        lstrcpy( lpIR->szOriginalICOFileName, "" );
        // Loop through the images
        for( i = 0; i < lpIR->nNumImages; i++ )
        {
            // Get the individual image
            if( (hRsrc = FindResource( hLibrary, MAKEINTRESOURCE(lpIcon->idEntries[i].nID), RT_ICON )) == NULL )
            {
                free( lpIR );
                FreeLibrary( hLibrary );
                return NULL;
            }
            if( (hGlobal = LoadResource( hLibrary, hRsrc )) == NULL )
            {
                free( lpIR );
                FreeLibrary( hLibrary );
                return NULL;
            }
            // Store a copy of the resource locally
            lpIR->IconImages[i].dwNumBytes =SizeofResource( hLibrary, hRsrc );
            lpIR->IconImages[i].lpBits = (LPBYTE)malloc( lpIR->IconImages[i].dwNumBytes );
            memcpy( lpIR->IconImages[i].lpBits, LockResource( hGlobal ), lpIR->IconImages[i].dwNumBytes );
            // Adjust internal pointers
            if( ! AdjustIconImagePointers( &(lpIR->IconImages[i]) ) )
            {
                MessageBox(AfxGetMainWnd()->m_hWnd, "转换成图标内部格式时出错!", szFileName, MB_OK );
                free( lpIR );
                FreeLibrary( hLibrary );
                return NULL;
            }
        }
    }
    FreeLibrary( hLibrary );
    return lpIR;
}
Esempio n. 8
0
/***********************************************************************
 *           VERSION_GetFileVersionInfo_PE             [internal]
 *
 *    NOTE: returns size of the PE VERSION resource or 0xFFFFFFFF
 *    in the case if file exists, but VERSION_INFO not found.
 *    FIXME: handle is not used.
 */
static DWORD VERSION_GetFileVersionInfo_PE( LPCSTR filename, LPDWORD handle,
                                    DWORD datasize, LPVOID data )
{
    VS_FIXEDFILEINFO *vffi;
    DWORD len;
    BYTE *buf;
    HMODULE hModule;
    HRSRC hRsrc;
    HGLOBAL hMem;
    BOOL do_free_library = FALSE;

    TRACE("(%s,%p)\n", debugstr_a(filename), handle );

    hModule = GetModuleHandleA(filename);
    if(!hModule)
    {
	hModule = LoadLibraryExA(filename, 0, LOAD_LIBRARY_AS_DATAFILE);
	do_free_library = TRUE;
    }
    if(!hModule)
    {
	WARN("Could not load %s\n", debugstr_a(filename));
	return 0;
    }
    hRsrc = FindResourceW(hModule,
			  MAKEINTRESOURCEW(VS_VERSION_INFO),
			  MAKEINTRESOURCEW(VS_FILE_INFO));
    if(!hRsrc)
    {
	WARN("Could not find VS_VERSION_INFO in %s\n", debugstr_a(filename));
	if(do_free_library) FreeLibrary(hModule);
	return 0xFFFFFFFF;
    }
    len = SizeofResource(hModule, hRsrc);
    hMem = LoadResource(hModule, hRsrc);
    if(!hMem)
    {
	WARN("Could not load VS_VERSION_INFO from %s\n", debugstr_a(filename));
	if(do_free_library) FreeLibrary(hModule);
	return 0xFFFFFFFF;
    }
    buf = LockResource(hMem);

    vffi = (VS_FIXEDFILEINFO *)VersionInfo32_Value( (VS_VERSION_INFO_STRUCT32 *)buf );

    if ( vffi->dwSignature != VS_FFI_SIGNATURE )
    {
        WARN("vffi->dwSignature is 0x%08lx, but not 0x%08lx!\n",
                   vffi->dwSignature, VS_FFI_SIGNATURE );
	len = 0xFFFFFFFF;
	goto END;
    }

    if ( TRACE_ON(ver) )
        print_vffi_debug( vffi );

    if(data)
    {
	if(datasize < len)
	    len = datasize; /* truncate data */
	if(len)
	    memcpy(data, buf, len);
	else
	    len = 0xFFFFFFFF;
    }
END:
    FreeResource(hMem);
    if(do_free_library) FreeLibrary(hModule);

    return len;
}
Esempio n. 9
0
bool XlLibraryInitialize(XlAddInExportInfo* pExportInfo)
{
	HRESULT hr;
	CComPtr<ICorRuntimeHost> pHost;

	hr = LoadClr20(&pHost);
	if (FAILED(hr) || pHost == NULL)
	{
		// LoadClr20 shows diagnostic MessageBoxes if needed.
		// Perhaps remember that we are not loaded?
		return 0;
	}

	// If all is fine now, also start the CLR (always safe to do again.
	hr = pHost->Start();
	if (FAILED(hr))
	{
		ShowMessage(IDS_MSG_HEADER_NEEDCLR20, 
					IDS_MSG_BODY_HOSTSTART,
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CString addInFullPath = AddInFullPath();

	CPath xllDirectory(addInFullPath);
	xllDirectory.RemoveFileSpec();

	CComPtr<IUnknown> pAppDomainSetupUnk;
	hr = pHost->CreateDomainSetup(&pAppDomainSetupUnk);
	if (FAILED(hr) || pAppDomainSetupUnk == NULL)
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_APPDOMAINSETUP, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CComQIPtr<IAppDomainSetup> pAppDomainSetup = pAppDomainSetupUnk;

	hr = pAppDomainSetup->put_ApplicationBase(CComBSTR(xllDirectory));
	if (FAILED(hr))
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_APPLICATIONBASE, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}
	
	CComBSTR configFileName = addInFullPath;
	configFileName.Append(L".config");
	pAppDomainSetup->put_ConfigurationFile(configFileName);

	CComBSTR appDomainName = L"ExcelDna: ";
	appDomainName.Append(addInFullPath);
	pAppDomainSetup->put_ApplicationName(appDomainName);

	IUnknown *pAppDomainUnk = NULL;
	hr = pHost->CreateDomainEx(appDomainName, pAppDomainSetupUnk, 0, &pAppDomainUnk);
	if (FAILED(hr) || pAppDomainUnk == NULL)
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_APPDOMAIN, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CComQIPtr<_AppDomain> pAppDomain(pAppDomainUnk);

	// Load plan for ExcelDna.Loader:
	// Try AppDomain.Load with the name ExcelDna.Loader.
	// Then if it does not work, we will try to load from a known resource in the .xll.

	CComPtr<_Assembly> pExcelDnaLoaderAssembly;
	hr = pAppDomain->Load_2(CComBSTR(L"ExcelDna.Loader"), &pExcelDnaLoaderAssembly);
	if (FAILED(hr) || pExcelDnaLoaderAssembly == NULL)
	{
		HRSRC hResInfoLoader = FindResource(hModuleCurrent, L"EXCELDNA_LOADER", L"ASSEMBLY");
		if (hResInfoLoader == NULL)
		{
			ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
						IDS_MSG_BODY_MISSINGEXCELDNALOADER, 
						IDS_MSG_FOOTER_UNEXPECTED,
						hr);
			return 0;
		}
		HGLOBAL hLoader = LoadResource(hModuleCurrent, hResInfoLoader);
		void* pLoader = LockResource(hLoader);
		ULONG sizeLoader = (ULONG)SizeofResource(hModuleCurrent, hResInfoLoader);
		
		CComSafeArray<BYTE> bytesLoader;
		bytesLoader.Add(sizeLoader, (byte*)pLoader);

		hr = pAppDomain->Load_3(bytesLoader, &pExcelDnaLoaderAssembly);
		if (FAILED(hr))
		{
			ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
						IDS_MSG_BODY_EXCELDNALOADER, 
						IDS_MSG_FOOTER_UNEXPECTED,
						hr);
			return 0;
		}

		CComBSTR pFullName;
		hr = pExcelDnaLoaderAssembly->get_FullName(&pFullName);
		if (FAILED(hr))
		{
			ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
						IDS_MSG_BODY_EXCELDNALOADERNAME, 
						IDS_MSG_FOOTER_UNEXPECTED,
						hr);
			return 0;
		}
	}
	
	CComPtr<_Type> pXlAddInType;
	hr = pExcelDnaLoaderAssembly->GetType_2(CComBSTR(L"ExcelDna.Loader.XlAddIn"), &pXlAddInType);
	if (FAILED(hr) || pXlAddInType == NULL)
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_XLADDIN, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	CComSafeArray<VARIANT> initArgs;
	initArgs.Add(CComVariant((INT32)pExportInfo));
	initArgs.Add(CComVariant((INT32)hModuleCurrent));
	initArgs.Add(CComVariant(addInFullPath.AllocSysString()));
	CComVariant initRetVal;
	CComVariant target;
	hr = pXlAddInType->InvokeMember_3(CComBSTR("Initialize"), (BindingFlags)(BindingFlags_Static | BindingFlags_Public | BindingFlags_InvokeMethod), NULL, target, initArgs, &initRetVal);
	if (FAILED(hr))
	{
		ShowMessage(IDS_MSG_HEADER_APPDOMAIN, 
					IDS_MSG_BODY_XLADDININIT, 
					IDS_MSG_FOOTER_UNEXPECTED,
					hr);
		return 0;
	}

	pHost_ForUnload = pHost.Detach();
	pAppDomain_ForUnload = (IUnknown*)pAppDomain.Detach();

	return initRetVal.boolVal == 0 ? false : true;
}
BOOL CBADO::OnInitADOConn()
{
	CString StrTips;
	HANDLE hFind;//
	WIN32_FIND_DATA wfd;//
	hFind = FindFirstFile(m_dbfilepath, &wfd);//
	if (hFind == INVALID_HANDLE_VALUE)//说明当前目录下无t3000.mdb
	{
		// 	StrTips.Format(_T("%s\n The datebase file disappeared.T3000 help you create a default datebase of your current building."),m_dbfilepath);
		// 	AfxMessageBox(StrTips);
		CStringArray ArrayFileName;
		SplitCStringA(ArrayFileName, m_dbfilepath, L"\\");
		CString filename = L"";
		for (int i = 0; i < ArrayFileName.GetSize() - 1; i++)
		{
			filename += ArrayFileName[i];
			filename += L"\\";
		}
		CreateDirectory(filename,NULL);
		m_dbImgeFolder = filename + _T("image");
		CreateDirectory(m_dbImgeFolder,NULL);

		hFind = FindFirstFile(m_dbfilepath, &wfd);//
		if (hFind == INVALID_HANDLE_VALUE)//说明当前目录下没有building数据库的话,就创建一个
		{
#if 0
		HRSRC hrSrc = FindResource(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_BUILDING_DB2), _T("BUILDING_DB"));   
		HGLOBAL hGlobal = LoadResource(AfxGetResourceHandle(), hrSrc);   


		LPVOID lpExe = LockResource(hGlobal);   
		CFile file;
		if(file.Open(m_dbfilepath, CFile::modeCreate | CFile::modeWrite))    
			file.Write(lpExe, (UINT)SizeofResource(AfxGetResourceHandle(), hrSrc));    
		file.Close();    
		::UnlockResource(hGlobal);   
		::FreeResource(hGlobal);
#endif
		}//
		FindClose(hFind);

		//return FALSE;
	}
	::CoInitialize(NULL);
	try
	{
		////////////////////////////////////////////////////////////////////////////////////////////


		m_ConnectString = (CString)FOR_DATABASE_CONNECT + m_dbfilepath;

		// 		CStringArray  ArrayFileName;
		// 		SplitCStringA(ArrayFileName,m_dbfilepath,L"\\");
		// 		CString filename=L"";
		// 		for (int i=0;i<ArrayFileName.GetSize()-1;i++)
		// 		{
		// 			filename+=ArrayFileName[i];
		// 			filename+=L"\\";
		// 		}
		// 		m_dbImgeFolder=filename+_T("image");
		// 		CreateDirectory(m_dbImgeFolder,NULL);

		/////////////////////////////////////////////////////////////////////////////////////////////////
		//连接数据库


		m_pConnection.CreateInstance("ADODB.Connection");

		m_pConnection->Open(m_ConnectString.GetString(), "", "", adModeUnknown);
	}
	catch (_com_error e)
	{
		//AfxMessageBox(e.Description());
		return FALSE;
	}

	return TRUE;
}
Esempio n. 11
0
// Installation of WinPcap
void EmInstallWinPcap(HWND hWnd, RPC *r)
{
	wchar_t temp_name[MAX_SIZE];
	HGLOBAL g;
	HINSTANCE h;
	HRSRC hr;
	UINT size;
	void *data;
	IO *io;

	// Ask whether the user want to start the installation
	if (MsgBox(hWnd, MB_ICONQUESTION | MB_YESNO, _UU("EM_WPCAP_INSTALL")) == IDNO)
	{
		return;
	}

	// Generate a temporary file name
	UniFormat(temp_name, sizeof(temp_name), L"%s\\winpcap_installer.exe", MsGetTempDirW());

	// Read from the resource
	h = GetUiDll();
	hr = FindResource(h, MAKEINTRESOURCE(BIN_WINPCAP), "BIN");
	if (hr == NULL)
	{
RES_ERROR:
		MsgBox(hWnd, MB_ICONSTOP, _UU("EM_RESOURCE"));
		return;
	}

	g = LoadResource(h, hr);
	if (g == NULL)
	{
		goto RES_ERROR;
	}

	size = SizeofResource(h, hr);
	data = LockResource(g);

	if (data == NULL)
	{
		goto RES_ERROR;
	}

	// Write to a temporary file
	io = FileCreateW(temp_name);
	if (io == NULL)
	{
		goto RES_ERROR;
	}

	FileWrite(io, data, size);
	FileClose(io);

	// Run
	if (RunW(temp_name, NULL, false, true) == false)
	{
		// Failure
		FileDeleteW(temp_name);
		goto RES_ERROR;
	}

	FileDeleteW(temp_name);

	if (r == NULL)
	{
		return;
	}

	// Message after the end
	if (OS_IS_WINDOWS_NT(GetOsInfo()->OsType) == false)
	{
		// Need to restart the computer
		MsgBox(hWnd, MB_ICONINFORMATION, _UU("EM_WPCAP_REBOOT1"));
	}
	else
	{
		// Need to restart the service
		if (MsgBox(hWnd, MB_ICONQUESTION | MB_YESNO, _UU("EM_WPCAP_REBOOT2")) == IDNO)
		{
			// Not restart
		}
		else
		{
			// Restart
			RPC_TEST t;
			RPC_BRIDGE_SUPPORT t2;
			Zero(&t, sizeof(t));
			EcRebootServer(r, &t);

			SleepThread(500);

			Zero(&t2, sizeof(t2));
			CALL(hWnd, EcGetBridgeSupport(r, &t2));
		}
	}
}
Esempio n. 12
0
/* GetFileVersionInfoSize
 * Gets the size of the version information; notice this is quick
 * and dirty, and the handle is just the offset
 *
 * Returns size of version info in bytes
 * lpwstrFilename is the name of the file to get version information from
 * lpdwHandle is outdated for the Win32 api and is set to zero.
 */
DWORD
APIENTRY
GetFileVersionInfoSizeW(
        LPWSTR lpwstrFilename,
        LPDWORD lpdwHandle
        )
{
  DWORD dwTemp;
  VERHEAD *pVerHead;
  HANDLE hMod;
  HANDLE hVerRes;
  HANDLE h;

  if (lpdwHandle != NULL)
      *lpdwHandle = 0;
  dwTemp = SetErrorMode(SEM_FAILCRITICALERRORS);
  hMod = LoadLibraryEx(lpwstrFilename, NULL, LOAD_LIBRARY_AS_DATAFILE);
  SetErrorMode(dwTemp);

  if (hMod == NULL) {

      dwTemp = ExtractVersionResource16W(lpwstrFilename, &hVerRes);

      if (!dwTemp)
         return(0L);

      if (!(pVerHead = GlobalLock(hVerRes))) {

Error:
          SetLastError(ERROR_INVALID_DATA);
          GlobalFree(hVerRes);
          return(0L);
      }

      if (pVerHead->wTotLen > dwTemp)
          goto Error;

      GlobalUnlock(hVerRes);
      GlobalFree(hVerRes);

      return dwTemp+dwTemp<<1;
  }

  if ((hVerRes = FindResource(hMod, MAKEINTRESOURCE(VS_VERSION_INFO), VS_FILE_INFO)) == NULL) {
      FreeLibrary(hMod);
      return(0L);
  }

  if ((dwTemp=SizeofResource(hMod, hVerRes)) == 0) {
      FreeLibrary(hMod);
      return(0L);
  }

  if ((h = LoadResource(hMod, hVerRes)) == NULL) {
      FreeLibrary(hMod);
      return(0L);
  }

  if ((pVerHead = (VERHEAD*)LockResource(h)) == NULL) {
      FreeLibrary(hMod);
      return(0L);
  }

  if ((DWORD)pVerHead->wTotLen > dwTemp) {

      SetLastError(ERROR_INVALID_DATA);

      UnlockResource(h);
      FreeLibrary(hMod);

      return(0L);
  }

  dwTemp = (DWORD)pVerHead->wTotLen;

  dwTemp = DWORDUP(dwTemp);

  if (pVerHead->vsf.dwSignature != VS_FFI_SIGNATURE) {

      SetLastError(ERROR_INVALID_DATA);

      UnlockResource(h);
      FreeLibrary(hMod);

      return(0L);
  }

  UnlockResource(h);
  FreeLibrary(hMod);

   //
   // dwTemp should be evenly divisible by two since not single
   // byte components at all (also DWORDUP for safety above):
   // alloc space for ansi components
   //
  return(dwTemp + dwTemp/2);
}
Esempio n. 13
0
//-----------------------------------------------------------------------------
// Does:   Open a Resource And Load It Into IPicture (Interface)
// ~~~~    (.BMP .DIB .EMF .GIF .ICO .JPG .WMF)
//
// Note:   When Adding a Bitmap Resource It Would Automatically Show On "Bitmap"
// ~~~~    This NOT Good Coz We Need To Load It From a Custom Resource "BMP"
//         To Add a Custom Rresource: Import Resource -> Open As -> Custom
//         (Both .BMP And .DIB Should Be Found Under "BMP")
//
// InPut:  ResourceName - As a UINT Defined (Example: IDR_PICTURE_RESOURCE)
// ~~~~~   ResourceType - Type Name (Example: "JPG")
//
// OutPut: TRUE If Succeeded...
// ~~~~~~
//-----------------------------------------------------------------------------
BOOL CPicViewer::Load(UINT ResourceName, LPCSTR ResourceType)
//=============================================================================
{
    BOOL bResult = FALSE;
    
    HGLOBAL		hGlobal = NULL;
    HRSRC		hSource = NULL;
    LPVOID		lpVoid  = NULL;
    int			nSize   = 0;
    
    if(m_IPicture != NULL) FreePictureData(); // Important - Avoid Leaks...
    
    hSource = FindResource(AfxGetResourceHandle(), MAKEINTRESOURCE(ResourceName), ResourceType);
    
    if(hSource == NULL)
    {
        TRACE( "FindResource() Failed\n" );
        // 		HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
        // 		MessageBoxEx(hWnd, "FindResource() Failed\t", ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
        return(FALSE);
    }
    
    hGlobal = LoadResource(AfxGetResourceHandle(), hSource);
    if(hGlobal == NULL)
    {
        TRACE( "LoadResource() Failed\n" );
        // 		HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
        // 		MessageBoxEx(hWnd, "LoadResource() Failed\t", ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
        return(FALSE);
    }
    
    lpVoid = LockResource(hGlobal);
    if(lpVoid == NULL)
    {
        TRACE( "LockResource() Failed\n" );
        // 		HWND hWnd = AfxGetApp()->GetMainWnd()->m_hWnd;
        // 		MessageBoxEx(hWnd, "LockResource() Failed\t", ERROR_TITLE, MB_OK | MB_ICONSTOP, LANG_ENGLISH);
        return(FALSE);
    }
    
    nSize = (UINT)SizeofResource(AfxGetResourceHandle(), hSource);
    if(LoadPictureData((BYTE*)hGlobal, nSize)) bResult = TRUE;
    
    UnlockResource(hGlobal); // 16Bit Windows Needs This
    FreeResource(hGlobal); // 16Bit Windows Needs This (32Bit - Automatic Release)
    
    m_Weight = nSize; // Update Picture Size Info...
    
    if(m_IPicture != NULL) // Do Not Try To Read From Memory That Is Not Exist...
    { 
        m_IPicture->get_Height(&m_Height);
        m_IPicture->get_Width(&m_Width);
        // Calculate Its Size On a "Standard" (96 DPI) Device Context
        m_Height = MulDiv(m_Height, 96, HIMETRIC_INCH);
        m_Width  = MulDiv(m_Width,  96, HIMETRIC_INCH);
    }
    else // Picture Data Is Not a Known Picture Type
    {
        m_Height = 0;
        m_Width = 0;
        bResult = FALSE;
    }
    
    return(bResult);
}
Esempio n. 14
0
//-----------------------------------------------------------------------------
// Name: CWaveFile::Open()
// Desc: Opens a wave file for reading
//-----------------------------------------------------------------------------
HRESULT CWaveFile::Open( LPWSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags )
{
    HRESULT hr;

    m_dwFlags = dwFlags;
    m_bIsReadingFromMemory = FALSE;

    if( m_dwFlags == WAVEFILE_READ )
    {
        if( strFileName == NULL )
            return E_INVALIDARG;
        SAFE_DELETE_ARRAY( m_pwfx );

        m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF | MMIO_READ );

        if( NULL == m_hmmio )
        {
            HRSRC hResInfo;
            HGLOBAL hResData;
            DWORD dwSize;
            VOID* pvRes;

            // Loading it as a file failed, so try it as a resource
            if( NULL == ( hResInfo = FindResource( NULL, strFileName, L"WAVE" ) ) )
            {
                if( NULL == ( hResInfo = FindResource( NULL, strFileName, L"WAV" ) ) )
                    return DXTRACE_ERR( L"FindResource", E_FAIL );
            }

            if( NULL == ( hResData = LoadResource( GetModuleHandle( NULL ), hResInfo ) ) )
                return DXTRACE_ERR( L"LoadResource", E_FAIL );

            if( 0 == ( dwSize = SizeofResource( GetModuleHandle( NULL ), hResInfo ) ) )
                return DXTRACE_ERR( L"SizeofResource", E_FAIL );

            if( NULL == ( pvRes = LockResource( hResData ) ) )
                return DXTRACE_ERR( L"LockResource", E_FAIL );

            m_pResourceBuffer = new CHAR[ dwSize ];
            if( m_pResourceBuffer == NULL )
                return DXTRACE_ERR( L"new", E_OUTOFMEMORY );
            memcpy( m_pResourceBuffer, pvRes, dwSize );

            MMIOINFO mmioInfo;
            ZeroMemory( &mmioInfo, sizeof( mmioInfo ) );
            mmioInfo.fccIOProc = FOURCC_MEM;
            mmioInfo.cchBuffer = dwSize;
            mmioInfo.pchBuffer = ( CHAR* )m_pResourceBuffer;

            m_hmmio = mmioOpen( NULL, &mmioInfo, MMIO_ALLOCBUF | MMIO_READ );
        }

        if( FAILED( hr = ReadMMIO() ) )
        {
            // ReadMMIO will fail if its an not a wave file
            mmioClose( m_hmmio, 0 );
            return DXTRACE_ERR( L"ReadMMIO", hr );
        }

        if( FAILED( hr = ResetFile() ) )
            return DXTRACE_ERR( L"ResetFile", hr );

        // After the reset, the size of the wav file is m_ck.cksize so store it now
        m_dwSize = m_ck.cksize;
    }
    else
    {
        m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF |
                            MMIO_READWRITE |
                            MMIO_CREATE );
        if( NULL == m_hmmio )
            return DXTRACE_ERR( L"mmioOpen", E_FAIL );

        if( FAILED( hr = WriteMMIO( pwfx ) ) )
        {
            mmioClose( m_hmmio, 0 );
            return DXTRACE_ERR( L"WriteMMIO", hr );
        }

        if( FAILED( hr = ResetFile() ) )
            return DXTRACE_ERR( L"ResetFile", hr );
    }

    return hr;
}
Esempio n. 15
0
//-----------------------------------------------------------------------------
// Name: CMusicManager::CreateSegmentFromResource()
// Desc: 
//-----------------------------------------------------------------------------
HRESULT CMusicManager::CreateSegmentFromResource( CMusicSegment** ppSegment, 
                                                  TCHAR* strResource,
                                                  TCHAR* strResourceType,
                                                  BOOL bDownloadNow,
                                                  BOOL bIsMidiFile )
{
    HRESULT               hr;
    IDirectMusicSegment8* pSegment      = NULL;
    HRSRC                 hres          = NULL;
    void*                 pMem          = NULL;
    DWORD                 dwSize        = 0;
    DMUS_OBJECTDESC       objdesc;

    // Find the resource
    hres = FindResource( NULL,strResource,strResourceType );
    if( NULL == hres ) 
        return E_FAIL;

    // Load the resource
    pMem = (void*)LoadResource( NULL, hres );
    if( NULL == pMem ) 
        return E_FAIL;

    // Store the size of the resource
    dwSize = SizeofResource( NULL, hres ); 
    
    // Set up our object description 
    ZeroMemory(&objdesc,sizeof(DMUS_OBJECTDESC));
    objdesc.dwSize = sizeof(DMUS_OBJECTDESC);
    objdesc.dwValidData = DMUS_OBJ_MEMORY | DMUS_OBJ_CLASS;
    objdesc.guidClass = CLSID_DirectMusicSegment;
    objdesc.llMemLength =(LONGLONG)dwSize;
    objdesc.pbMemData = (BYTE*)pMem;
    
    if (FAILED ( hr = m_pLoader->GetObject( &objdesc,
                                            IID_IDirectMusicSegment8,
                                            (void**)&pSegment ) ) )
    {
        if( hr == DMUS_E_LOADER_FAILEDOPEN )
            return hr;
        return DXTRACE_ERR_MSGBOX( TEXT("LoadObjectFromFile"), hr );
    }

    *ppSegment = new CMusicSegment( m_pPerformance, m_pLoader, pSegment );
    if( NULL == *ppSegment )
        return E_OUTOFMEMORY;

    if( bIsMidiFile )
    {
        // Do this to make sure that the default General MIDI set 
        // is connected appropriately to the MIDI file and 
        // all instruments sound correct.                  
        if( FAILED( hr = pSegment->SetParam( GUID_StandardMIDIFile, 
                                             0xFFFFFFFF, 0, 0, NULL ) ) )
            return DXTRACE_ERR_MSGBOX( TEXT("SetParam"), hr );
    }

    if( bDownloadNow )
    {
        // The segment needs to be download first before playing.  
        // However, some apps may want to wait before calling this 
        // to because the download allocates memory for the 
        // instruments. The more instruments currently downloaded, 
        // the more memory is in use by the synthesizer.
        if( FAILED( hr = (*ppSegment)->Download() ) )
            return DXTRACE_ERR_MSGBOX( TEXT("Download"), hr );
    }

    return S_OK;
}
Esempio n. 16
0
BOOL SimpleBrowser::LoadFromResource(INT resID)
{
	ASSERT(m_pBrowser != NULL);
	if (m_pBrowser != NULL) 
	{
		CString resource_string;
		// load HTML document from resource
		HRSRC resource_handle = FindResource(AfxGetResourceHandle(), MAKEINTRESOURCE(resID), RT_HTML);
		if (resource_handle != NULL) 
		{
			HGLOBAL resource = LoadResource(AfxGetResourceHandle(),	resource_handle);
			if (resource != NULL) 
			{
				LPVOID resource_memory = LockResource(resource);
				if (resource_memory != NULL) 
				{
					DWORD resource_size = SizeofResource(AfxGetResourceHandle(), resource_handle);
					// identify the resource document as MBCS (e.g. ANSI) or UNICODE
					bool     UNICODE_document = false;
					wchar_t *UNICODE_memory   = (wchar_t *)resource_memory;
					int      UNICODE_size     = resource_size / sizeof(wchar_t);
					if (UNICODE_size >= 1) 
					{
						// check for UNICODE byte order mark
						if (*UNICODE_memory == L'\xFEFF') 
						{
							UNICODE_document = true;
							UNICODE_memory  += 1;
							UNICODE_size    -= 1;
						}
						// otherwise, check for UNICODE leading tag

						else if (UNICODE_size >= 5) 
						{
							if ((UNICODE_memory[0]           == L'<') &&
							    (towupper(UNICODE_memory[1]) == L'H') &&
							    (towupper(UNICODE_memory[2]) == L'T') &&
							    (towupper(UNICODE_memory[3]) == L'M') &&
							    (towupper(UNICODE_memory[4]) == L'L')) 
							{
								UNICODE_document = true;
							}
						}

						// Note: This logic assumes that the UNICODE resource document is 
						//       in little-endian byte order, which would be typical for 
						//       any HTML document used as a resource in a Windows application.

					}
					// convert resource document if required
#if !defined(UNICODE)
					if (UNICODE_document) 
					{
						char *MBCS_buffer = resource_string.GetBufferSetLength(resource_size + 1);
						int MBCS_length = ::WideCharToMultiByte(CP_ACP,
							0, UNICODE_memory, UNICODE_size, MBCS_buffer, resource_size + 1, NULL, NULL);
						resource_string.ReleaseBuffer(MBCS_length);
					}
					else 
						resource_string = CString((char *)resource_memory,resource_size);
#else
					if (UNICODE_document) 
						resource_string = CString(UNICODE_memory,UNICODE_size);
					else 
					{
						wchar_t *UNICODE_buffer = resource_string.GetBufferSetLength(resource_size + 1);
						int UNICODE_length = ::MultiByteToWideChar(CP_ACP,
							0, (const char *)resource_memory, resource_size, UNICODE_buffer, (resource_size + 1));
						resource_string.ReleaseBuffer(UNICODE_length);
					}
#endif
				}
			}
		}
		return LoadHTML(resource_string);
	}
	return FALSE;
}
Esempio n. 17
0
BOOL CCaCertExtPage::OnInitDialog()
{
    CPropertyPage::OnInitDialog();

    // TODO: Add extra initialization here

    ClassXP(GetDlgItem(IDC_LIST)->m_hWnd,TRUE);


    CImageList * pImgList = ((CMiniCaApp *)AfxGetApp())->GetImgList();
    m_CheckList.SetImageList(pImgList,LVSIL_SMALL);//用来改变LISTCTRL行宽度

    ListView_SetExtendedListViewStyle(m_CheckList.m_hWnd, LVS_EX_CHECKBOXES | LVS_EX_SUBITEMIMAGES |
                                      LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);

    CRect rect;
    m_CheckList.GetClientRect(rect);
    int width = rect.Width();

    m_CheckList.InsertColumn(0, MiniCT_0400, LVCFMT_LEFT,width/3); //MiniCT_0400 "扩展名称"
    m_CheckList.InsertColumn(1, MiniCT_0401, LVCFMT_LEFT,2*width/3);		//MiniCT_0401 "内容"


    CString m_IniPathName = ((CMiniCaApp *)AfxGetApp())->GetAppPath() +  "\\MiniExt.ini";

    //加载配置信息
    //检测是否已经打开,如果打不开,则重新写入
    CFile file;
    if(!file.Open(m_IniPathName,CFile::modeRead))
    {
        /*得到配置,判断是否繁体环境*/
        HRSRC hRsrc = 0;

        if(CMiniCaApp::IsBig())
            hRsrc = FindResource(NULL,MAKEINTRESOURCE(IDR_MINICA_EXT_BG),"INI");
        else
            hRsrc = FindResource(NULL,MAKEINTRESOURCE(IDR_MINICA_EXT),"INI");

        DWORD lenCert = SizeofResource(NULL, hRsrc);
        HGLOBAL hgCert=LoadResource(NULL,hRsrc);
        LPSTR lpCert=(LPSTR)LockResource(hgCert);

        if(file.Open(m_IniPathName,CFile::modeCreate|CFile::modeWrite))	//存文件
        {
            file.Write(lpCert,lenCert);
        }

    }
    file.Close();

    GetIniInfo(m_IniPathName);

    /*LVS_EX_CHECKBOXES 使用检查框
    LVS_EX_FULLROWSELECT 选择整行
    LVS_EX_GRIDLINES 在REPORT中画出分隔线
    LVS_EX_HEADERDRAGDROP LVS_REPORT时可以利用drag-and-drop重新排序
    LVS_EX_SUBITEMIMAGES 允许在子项中显示image
    LVS_EX_TRACKSELECT 当鼠标指到某一项时便自动选择该项 */

    m_toolTip.Create(this);
    m_toolTip.AddTool(GetDlgItem(IDC_LIST), "证书扩展设置\r详细设置请转到配置选项卡");


    return TRUE;  // return TRUE unless you set the focus to a control
    // EXCEPTION: OCX Property Pages should return FALSE
}
Esempio n. 18
0
INT_PTR CALLBACK DlgProcAbout(HWND hwndDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
	static int iState = 0;
	switch (msg) {
	case WM_INITDIALOG:
		TranslateDialogDefault(hwndDlg);
		{	TCHAR filename[MAX_PATH], *productCopyright;
			DWORD unused;
			DWORD verInfoSize;
			UINT blockSize;
			PVOID pVerInfo;

			GetModuleFileName(NULL,filename,SIZEOF(filename));
			verInfoSize=GetFileVersionInfoSize(filename,&unused);
			pVerInfo=mir_alloc(verInfoSize);
			GetFileVersionInfo(filename,0,verInfoSize,pVerInfo);
			VerQueryValue(pVerInfo,_T("\\StringFileInfo\\000004b0\\LegalCopyright"),(LPVOID*)&productCopyright,&blockSize);
			SetDlgItemText(hwndDlg,IDC_DEVS,productCopyright);
			mir_free(pVerInfo);
		}
		{	char productVersion[56], *p;
			int isAnsi = 0;
			TCHAR str[64];
			CallService(MS_SYSTEM_GETVERSIONTEXT,SIZEOF(productVersion),(LPARAM)productVersion);
			// Hide Unicode from version text as it is assumed at this point
			p = strstr(productVersion, " Unicode"); 
			if (p)
				*p = '\0';
			else
				isAnsi = 1;
			mir_sntprintf(str,SIZEOF(str),_T(STR_VERSION_FORMAT), TranslateT("v"), productVersion, isAnsi?" ANSI":"");
			{
				TCHAR oldTitle[256], newTitle[256];
				GetDlgItemText( hwndDlg, IDC_HEADERBAR, oldTitle, SIZEOF( oldTitle ));
				mir_sntprintf( newTitle, SIZEOF(newTitle), oldTitle, str );
				SetDlgItemText( hwndDlg, IDC_HEADERBAR, newTitle );
			}
			
			mir_sntprintf(str,SIZEOF(str),TranslateT("Built %s %s"),_T(__DATE__),_T(__TIME__));
			SetDlgItemText(hwndDlg,IDC_BUILDTIME,str);
		}
		ShowWindow(GetDlgItem(hwndDlg, IDC_CREDITSFILE), SW_HIDE);
		{	
			HRSRC   hResInfo  = FindResource(hMirandaInst,MAKEINTRESOURCE(IDR_CREDITS),_T("TEXT"));
			DWORD   ResSize   = SizeofResource(hMirandaInst,hResInfo);
			HGLOBAL hRes      = LoadResource(hMirandaInst,hResInfo);
			char*   pszMsg    = (char*)LockResource(hRes);
			if (pszMsg)
			{
				char* pszMsgt = (char*)alloca(ResSize + 1);
				memcpy(pszMsgt, pszMsg, ResSize); pszMsgt[ResSize] = 0;

				TCHAR *ptszMsg;
				if (ResSize >=3 && pszMsgt[0] == '\xef' && pszMsgt[1] == '\xbb' && pszMsgt[2] == '\xbf')
					ptszMsg = Utf8DecodeT(pszMsgt + 3);
				else
					ptszMsg = mir_a2t_cp(pszMsgt, 1252);

				SetDlgItemText(hwndDlg, IDC_CREDITSFILE, ptszMsg);
				UnlockResource(pszMsg);
				mir_free(ptszMsg);
			}
			FreeResource(hRes);
		}
		Window_SetIcon_IcoLib(hwndDlg, SKINICON_OTHER_MIRANDA);
		return TRUE;

	case WM_COMMAND:
		switch( LOWORD( wParam )) {
		case IDOK:
		case IDCANCEL:
			DestroyWindow(hwndDlg);
			return TRUE;
		case IDC_CONTRIBLINK:
			if (iState) {
				iState = 0;
				SetDlgItemText(hwndDlg, IDC_CONTRIBLINK, TranslateT("Credits >"));
				ShowWindow(GetDlgItem(hwndDlg, IDC_DEVS), SW_SHOW);
				ShowWindow(GetDlgItem(hwndDlg, IDC_BUILDTIME), SW_SHOW);
				ShowWindow(GetDlgItem(hwndDlg, IDC_CREDITSFILE), SW_HIDE);
			}
			else {
				iState = 1;
				SetDlgItemText(hwndDlg, IDC_CONTRIBLINK, TranslateT("< Copyright"));
				ShowWindow(GetDlgItem(hwndDlg, IDC_DEVS), SW_HIDE);
				ShowWindow(GetDlgItem(hwndDlg, IDC_BUILDTIME), SW_HIDE);
				ShowWindow(GetDlgItem(hwndDlg, IDC_CREDITSFILE), SW_SHOW);
			}
			break;
		}
		break;

	case WM_CTLCOLOREDIT:
	case WM_CTLCOLORSTATIC:
		switch ( GetWindowLongPtr(( HWND )lParam, GWL_ID )) {
		case IDC_WHITERECT:
		case IDC_BUILDTIME:
		case IDC_CREDITSFILE:
		case IDC_DEVS:
			SetTextColor((HDC)wParam,GetSysColor(COLOR_WINDOWTEXT));
			break;
		default:
			return FALSE;
	  }
		SetBkColor((HDC)wParam, GetSysColor(COLOR_WINDOW));
		return (INT_PTR)GetSysColorBrush(COLOR_WINDOW);

	case WM_DESTROY:
		Window_FreeIcon_IcoLib( hwndDlg );
		{	
			HFONT hFont=(HFONT)SendDlgItemMessage(hwndDlg,IDC_VERSION,WM_GETFONT,0,0);
			SendDlgItemMessage(hwndDlg,IDC_VERSION,WM_SETFONT,SendDlgItemMessage(hwndDlg,IDOK,WM_GETFONT,0,0),0);
			DeleteObject(hFont);				
		}
		break;
	}
	return FALSE;
}
Esempio n. 19
0
//-----------------------------------------------------------------------------
// Name: CWaveFile::Open()
// Desc: Opens a wave file for reading
//-----------------------------------------------------------------------------
HRESULT CPCMFile::Open( LPTSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags )
{
    HRESULT hr;

    m_dwFlags = dwFlags;
    m_bIsReadingFromMemory = FALSE;

    if( m_dwFlags == WAVEFILE_READ )
    {
        if( strFileName == NULL )
            return E_INVALIDARG;
        SAFE_DELETE_ARRAY( m_pwfx );

        m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF | MMIO_READ );

        if( NULL == m_hmmio )
        {
            HRSRC   hResInfo;
            HGLOBAL hResData;
            DWORD   dwSize;
            VOID*   pvRes;

            // Loading it as a file failed, so try it as a resource
            if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAVE") ) ) )
            {
                if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAV") ) ) )
                    return DXTRACE_ERR_NOMSGBOX( TEXT("FindResource"), E_FAIL );
            }

            if( NULL == ( hResData = LoadResource( NULL, hResInfo ) ) )
                return DXTRACE_ERR( TEXT("LoadResource"), E_FAIL );

            if( 0 == ( dwSize = SizeofResource( NULL, hResInfo ) ) ) 
                return DXTRACE_ERR( TEXT("SizeofResource"), E_FAIL );

            if( NULL == ( pvRes = LockResource( hResData ) ) )
                return DXTRACE_ERR( TEXT("LockResource"), E_FAIL );

            CHAR* pData = new CHAR[ dwSize ];
            memcpy( pData, pvRes, dwSize );

            MMIOINFO mmioInfo;
            ZeroMemory( &mmioInfo, sizeof(mmioInfo) );
            mmioInfo.fccIOProc = FOURCC_MEM;
            mmioInfo.cchBuffer = dwSize;
            mmioInfo.pchBuffer = (CHAR*) pData;

            m_hmmio = mmioOpen( NULL, &mmioInfo, MMIO_ALLOCBUF | MMIO_READ );
        }

        if( FAILED( hr = ReadMMIO() ) )
        {
            // ReadMMIO will fail if its an not a wave file
            mmioClose( m_hmmio, 0 );
            return DXTRACE_ERR_NOMSGBOX( TEXT("ReadMMIO"), hr );
        }

		if( FAILED( hr = ResetFile() ) )
            return DXTRACE_ERR( TEXT("ResetFile"), hr );

        // After the reset, the size of the wav file is m_ck.cksize so store it now
        m_dwSize = m_ck.cksize;

		//  Calculate the total playing seconds
		m_dwTotalSeconds = m_dwSize/ m_pwfx->nAvgBytesPerSec;
    }
    else
    {
        m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF  | 
                                                  MMIO_READWRITE | 
                                                  MMIO_CREATE );
        if( NULL == m_hmmio )
            return DXTRACE_ERR( TEXT("mmioOpen"), E_FAIL );

        if( FAILED( hr = WriteMMIO( pwfx ) ) )
        {
            mmioClose( m_hmmio, 0 );
            return DXTRACE_ERR( TEXT("WriteMMIO"), hr );
        }
                        
        if( FAILED( hr = ResetFile() ) )
            return DXTRACE_ERR( TEXT("ResetFile"), hr );
    }

    return hr;
}
Esempio n. 20
0
LICE_IBitmap *LICE_LoadJPGFromResource(HINSTANCE hInst, const char *resid, LICE_IBitmap *bmp)
{
#ifdef _WIN32
  HRSRC hResource = FindResource(hInst, resid, "JPG");
  if(!hResource) return NULL;

  DWORD imageSize = SizeofResource(hInst, hResource);
  if(imageSize < 8) return NULL;

  HGLOBAL res = LoadResource(hInst, hResource);
  const void* pResourceData = LockResource(res);
  if(!pResourceData) return NULL;

  unsigned char *data = (unsigned char *)pResourceData;

  struct jpeg_decompress_struct cinfo;
  struct my_error_mgr jerr={0,};
  JSAMPARRAY buffer;
  int row_stride;

  jerr.pub.error_exit = LICEJPEG_Error;
  jerr.pub.emit_message = LICEJPEG_EmitMsg;
  jerr.pub.output_message = LICEJPEG_OutMsg;
  jerr.pub.format_message = LICEJPEG_FmtMsg;
  jerr.pub.reset_error_mgr = LICEJPEG_reset_error_mgr;

  cinfo.err = &jerr.pub;

  if (setjmp(jerr.setjmp_buffer)) 
  {
    jpeg_destroy_decompress(&cinfo);
    return 0;
  }
  jpeg_create_decompress(&cinfo);

  cinfo.src = (struct jpeg_source_mgr *) (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo, JPOOL_PERMANENT, sizeof (struct jpeg_source_mgr));
  
  cinfo.src->init_source = LICEJPEG_init_source;
  cinfo.src->fill_input_buffer = LICEJPEG_fill_input_buffer;
  cinfo.src->skip_input_data = LICEJPEG_skip_input_data;
  cinfo.src->resync_to_restart = jpeg_resync_to_restart;	
  cinfo.src->term_source = LICEJPEG_term_source;

  cinfo.src->next_input_byte = data;
  cinfo.src->bytes_in_buffer = imageSize;

  jpeg_read_header(&cinfo, TRUE);
  jpeg_start_decompress(&cinfo);

  row_stride = cinfo.output_width * cinfo.output_components;

  buffer = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);

  LICE_IBitmap *delbmp = NULL;
  if (bmp) bmp->resize(cinfo.output_width,cinfo.output_height);
  else delbmp = bmp = new WDL_NEW LICE_MemBitmap(cinfo.output_width,cinfo.output_height);

  if (!bmp || bmp->getWidth() != (int)cinfo.output_width || bmp->getHeight() != (int)cinfo.output_height) 
  {
    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);
    delete delbmp;
    return 0;
  }

  LICE_pixel *bmpptr = bmp->getBits();
  int dbmpptr=bmp->getRowSpan();
  if (bmp->isFlipped())
  {
    bmpptr += dbmpptr*(bmp->getHeight()-1);
    dbmpptr=-dbmpptr;
  }

  while (cinfo.output_scanline < cinfo.output_height)
  {
    /* jpeg_read_scanlines expects an array of pointers to scanlines.
     * Here the array is only one element long, but you could ask for
     * more than one scanline at a time if that's more convenient.
     */
    jpeg_read_scanlines(&cinfo, buffer, 1);
    /* Assume put_scanline_someplace wants a pointer and sample count. */
//    put_scanline_someplace(buffer[0], row_stride);
    if (cinfo.output_components==3)
    {
      int x;
      for (x = 0; x < (int)cinfo.output_width; x++)
      {
        bmpptr[x]=LICE_RGBA(buffer[0][x*3],buffer[0][x*3+1],buffer[0][x*3+2],255);
      }
    }
    else if (cinfo.output_components==1)
    {
      int x;
      for (x = 0; x < (int)cinfo.output_width; x++)
      {
        int v=buffer[0][x];
        bmpptr[x]=LICE_RGBA(v,v,v,255);
      }
    }
    else
    {
      memset(bmpptr,0,4*cinfo.output_width);
    }
    bmpptr+=dbmpptr;
  }

  jpeg_finish_decompress(&cinfo);
  jpeg_destroy_decompress(&cinfo);  // we created cinfo.src with some special alloc so I think it gets collected

  return bmp;

#else
  return 0;
#endif
}
Esempio n. 21
0
void main()
{ CreateFiles();
  HZIP hz; DWORD writ;

  // EXAMPLE 1 - create a zipfile from existing files
  hz = CreateZip(_T("\\simple1.zip"),0);
  ZipAdd(hz,_T("znsimple.bmp"), _T("\\simple.bmp"));
  ZipAdd(hz,_T("znsimple.txt"), _T("\\simple.txt"));
  CloseZip(hz);
  _tprintf(_T("Created '\\simple1.zip'\n"));


  // EXAMPLE 2 - unzip it with the names suggested in the zip
  hz = OpenZip(_T("\\simple1.zip"),0);
  SetUnzipBaseDir(hz,_T("\\"));
  ZIPENTRY ze; GetZipItem(hz,-1,&ze); int numitems=ze.index;
  for (int zi=0; zi<numitems; zi++)
  { GetZipItem(hz,zi,&ze);
    UnzipItem(hz,zi,ze.name);
  }
  CloseZip(hz);
  _tprintf(_T("Unzipped 'znsimple.bmp' and 'znsimple.txt' from 'simple1.zip'\n"));



  // EXAMPLE 3 - create an auto-allocated pagefile-based zip file from various sources
  // the second argument says how much address space to reserve for it. We can
  // afford to be generous: no address-space is allocated unless it's actually needed.
  hz = CreateZip(0,100000,"password");
  // adding a conventional file...
  ZipAdd(hz,_T("znsimple.txt"),  _T("\\simple.txt"));
  // adding something from memory...
  char buf[1000]; for (int zj=0; zj<1000; zj++) buf[zj]=(char)(zj&0x7F);
  ZipAdd(hz,_T("simple.dat"),  buf,1000);
  // adding something from a pipe...
#ifndef UNDER_CE
  HANDLE hread,hwrite; CreatePipe(&hread,&hwrite,NULL,0);
  DWORD WINAPI Ex3ThreadFunc(void *dat);
  HANDLE hthread = CreateThread(0,0,Ex3ThreadFunc,(void*)hwrite,0,0);
  ZipAddHandle(hz,_T("simple3.dat"),  hread,1000);  // the '1000' is optional, but it makes for nicer zip files if sizes are known in advance.
  WaitForSingleObject(hthread,INFINITE);
  CloseHandle(hthread); CloseHandle(hread); // the thread will close hwrite
#endif
  //
  // and now that the zip is created in pagefile, let's do something with it:
  void *zbuf; unsigned long zlen; ZipGetMemory(hz,&zbuf,&zlen);
  HANDLE hfz = CreateFile(_T("\\simple3 - pwd is 'password'.zip"),GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
  WriteFile(hfz,zbuf,zlen,&writ,NULL);
  CloseHandle(hfz);
  CloseZip(hz);
  _tprintf(_T("Created 'simple3.zip' via pagefile\n"));


  // EXAMPLE 4 - unzip directly from resource into a file
  // resource RT_RCDATA/#1 happens to be a zip file...
  HINSTANCE hInstance=GetModuleHandle(0);
  HRSRC hrsrc = FindResource(hInstance,MAKEINTRESOURCE(1),RT_RCDATA);
  HANDLE hglob = LoadResource(hInstance,hrsrc);
  void *zipbuf=LockResource(hglob);
  unsigned int ziplen=SizeofResource(hInstance,hrsrc);
  hz = OpenZip(zipbuf, ziplen, 0);  SetUnzipBaseDir(hz,_T("\\"));
  int i; FindZipItem(hz,_T("simple.jpg"),true,&i,&ze);
  //   - unzip to a file -
  UnzipItem(hz,i,ze.name);
  //   - unzip to a membuffer -
  char *ibuf = new char[ze.unc_size];
  UnzipItem(hz,i, ibuf, ze.unc_size);
  delete[] ibuf;
  //   - unzip to a fixed membuff, bit by bit -
  char fbuf[1024]; ZRESULT zr=ZR_MORE; unsigned long totsize=0;
  while (zr==ZR_MORE)
  { zr = UnzipItem(hz,i, fbuf,1024);
    unsigned long bufsize=1024; if (zr==ZR_OK) bufsize=ze.unc_size-totsize;
    // now do something with this chunk which we just unzipped...
    totsize+=bufsize;
  }
  //   - finished -
  CloseZip(hz);
  // note: no need to free resources obtained through Find/Load/LockResource
  _tprintf(_T("Unzipped 'simple.jpg' from resource zipfile\n"));


  
  DeleteFile(_T("\\simple.txt"));
  DeleteFile(_T("\\simple.bmp"));
  _tprintf(_T("Deleted 'simple.txt' and 'simple.bmp'\n"));
}
Esempio n. 22
0
/**
 *\fn           HDC AddImageDC(int id, int resId)
 *\brief        Ìí¼ÓJPGͼÏñDC
 *\param[in]    int id ͼÏñDCÐòºÅ
 *\param[in]    int resId ×ÊÔ´ID
 *\return       JPGͼÏñDC¾ä±ú
 */
HDC CXTDC::AddImageDC(int id, int resId)
{
    DeleteDC(IMAGEDC, id);

    HRSRC   res     = FindResource(module_, MAKEINTRESOURCE(resId), _T("jpg"));
    HGLOBAL resData = LoadResource(module_, (HRSRC)res);
    DWORD   resSize = SizeofResource(module_, (HRSRC)res);

    if (NULL == resData)
    {
        return NULL;
    }

    HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, resSize);
    if (NULL == hGlobal)
    {
        return NULL;
    }

    LPVOID pvData = GlobalLock(hGlobal);// Ëø¶¨ÄÚ´æ
    if (NULL == pvData)
    {
        FreeResource(resData);
        GlobalFree(hGlobal);
        return NULL;
    }

    LockResource(resData);              // Ëø¶¨×ÊÔ´
    memcpy(pvData, resData, resSize);   // ÔØÈëÄÚ´æ
    GlobalUnlock(hGlobal);              // ½âËøÄÚ´æ
    FreeResource(resData);              // ÊÍ·Å×ÊÔ´

    CComPtr<IStream> spStream = NULL;
    HRESULT hr = ::CreateStreamOnHGlobal(hGlobal, TRUE, &spStream); // ½¨Á¢IStream
    if (!SUCCEEDED(hr))
    {
        GlobalFree(hGlobal);
        return NULL;
    }

    CComPtr<IPicture> spPicture;
    hr = OleLoadPicture(spStream, resSize, FALSE, IID_IPicture, (LPVOID*)&spPicture);   // ½¨Á¢IPicture
    if (!SUCCEEDED(hr))
    {
        GlobalFree(hGlobal);
        return NULL;
    }

    GlobalFree(hGlobal);

    OLE_HANDLE picHandle = NULL;
    spPicture->get_Handle(&picHandle);

    XTDC xtDC;
    xtDC.dc = CreateCompatibleDC(NULL);
    xtDC.image = (HGDIOBJ)picHandle;
    xtDC.oldImage = SelectObject(xtDC.dc, xtDC.image);

    imageDcMap_[id] = xtDC;

    return xtDC.dc;
}
Esempio n. 23
0
STDAPI DllRegisterServer(void) {
	//register server
	WCHAR path[MAX_PATH];
	GetModuleFileName(g_hMod, path, MAX_PATH);
	auto ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\InprocServer32",
		NULL, path);
	if (!ret)
		return E_FAIL;

	ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\InprocServer32",
		L"ThreadingModel", L"Apartment");
	if (!ret)
		return E_FAIL;

	ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\ProgID",
		NULL, L"CircleControl.CircleControl.1");
	if (!ret)
		return E_FAIL;

	ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\VersionIndependentProgID",
		NULL, L"CircleControl.CircleControl");
	if (!ret)
		return E_FAIL;

	ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\TypeLib",
		NULL, L"{E9D304EC-552C-4D89-9804-7AB9E45FEF32}");
	if (!ret)
		return E_FAIL;

	HKEY hKey = NULL;
	auto hr = RegCreateKeyEx(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\Programmable",
		NULL, NULL, NULL, KEY_ALL_ACCESS, NULL, &hKey, NULL);
	if (hr != ERROR_SUCCESS)
		return hr;

	hr = RegCreateKeyEx(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\Control",
		NULL, NULL, NULL, KEY_ALL_ACCESS, NULL, &hKey, NULL);
	if (hr != ERROR_SUCCESS)
		return hr;

	ret = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\Version",
		NULL, L"1.0");
	if (!ret)
		return E_FAIL;

	WCHAR pathRsrc[MAX_PATH + 100];
	StringCchPrintf(pathRsrc, MAX_PATH + 100, L"%s, 101", path);
	hr = RegSetString(HKEY_CLASSES_ROOT, L"CLSID\\{1C797BFB-3F97-4CF8-B857-45C90028759B}\\ToolboxBitmap32",
		NULL, pathRsrc);
	if (hr != ERROR_SUCCESS)
		return hr;

	ret = RegSetString(HKEY_CLASSES_ROOT, L"CircleControl.CircleControl.1\\CLSID",
		NULL, L"{1C797BFB-3F97-4CF8-B857-45C90028759B}");
	if (!ret)
		return E_FAIL;

	ret = RegSetString(HKEY_CLASSES_ROOT, L"CircleControl.CircleControl\\CLSID",
		NULL, L"{1C797BFB-3F97-4CF8-B857-45C90028759B}");
	if (!ret)
		return E_FAIL;

	ret = RegSetString(HKEY_CLASSES_ROOT, L"CircleControl.CircleControl\\CurVer",
		NULL, L"CircleControl.CircleControl.1");
	if (!ret)
		return E_FAIL;

	//register the typelib
	HRSRC hrsrc = FindResource(g_hMod, MAKEINTRESOURCE(1), L"TYPELIB");
	if (!hrsrc)
		return E_FAIL;
	HGLOBAL hGlobal = LoadResource(g_hMod, hrsrc);
	if (!hGlobal)
		return E_FAIL;
	auto size = SizeofResource(g_hMod, hrsrc);
	WCHAR tempDir[MAX_PATH];
	GetTempPath(MAX_PATH, tempDir);
	WCHAR tempFile[MAX_PATH];
	GetTempFileName(tempDir, L"keke", 0, tempFile);
	HANDLE hFile = CreateFile(tempFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL);
	if (hFile == INVALID_HANDLE_VALUE)
		return E_FAIL;
	DWORD byteCount;
	if (!WriteFile(hFile, hGlobal, size, &byteCount, NULL) || byteCount != size)
		return E_FAIL;
	if (!CloseHandle(hFile))
		return E_FAIL;
	ITypeLib* typeLib = nullptr;
	hr = LoadTypeLib(tempFile, &typeLib);
	if (hr != S_OK) {
		return hr;
	}
	hr = RegisterTypeLib(typeLib, path, NULL);
	return hr;
}
Esempio n. 24
0
BOOL CALLBACK DlgProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	OPENFILENAME ofn;
	POINT pt;
	RECT rect;
	switch(uMsg){
	case WM_INITDIALOG:
		InitCommonControls();
		hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_MAIN));
		SendMessage(hDlg, WM_SETICON, (WPARAM)ICON_SMALL, (LPARAM)hIcon);
		CheckDlgButton(hDlg, IDC_BACKUP, BST_CHECKED);
		SendMessage(GetDlgItem(hDlg, IDC_FILE), EM_SETREADONLY, (WPARAM)TRUE, (LPARAM)0);
		hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_EXE));
		SendMessage(GetDlgItem(hDlg, IDC_ICONIMG), STM_SETICON, (WPARAM)hIcon, (LPARAM)0);
		EnableWindow(GetDlgItem(hDlg, IDC_BUILD), FALSE);
		SetWindowPos(hDlg, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
		break;
	case WM_CLOSE:
		EndDialog(hDlg, 0);
		break;
	case WM_PAINT:
		SendMessage(GetDlgItem(hDlg, IDC_ICONIMG), STM_SETICON, (WPARAM)hIcon, (LPARAM)0);
		break;
	case WM_DROPFILES:
		HDROP hDrop;
		hDrop = HDROP(wParam);
		DragQueryFile(hDrop, 0, szEFileName, sizeof(szEFileName));
		DragFinish(hDrop);
		if(LoadPE(szEFileName) == FALSE)
		{
			MessageBox(hDlg, "Could not load file!", "Cryptic", MB_ICONERROR);
			return TRUE;
		}
		SetDlgItemText(hDlg, IDC_FILE, szEFileName);
		EnableWindow(GetDlgItem(hDlg, IDC_BUILD), TRUE);
		break;
	case WM_MOUSEMOVE:
		GetCursorPos(&pt);
		GetWindowRect(GetDlgItem(hDlg, IDC_ICONIMG), &rect);
		if(PtInRect(&rect, pt))
		{
			SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(32649)));
		}
		else
		{
			SetCursor(LoadCursor(NULL, IDC_ARROW));
		}
		break;
	case WM_LBUTTONDOWN:
		GetCursorPos(&pt);
		GetWindowRect(GetDlgItem(hDlg, IDC_ICONIMG), &rect);
		if(PtInRect(&rect, pt))
		{
			SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(32649)));
			memset(&ofn, 0, sizeof(ofn));
			szIFileName[0] = '\0';
			ofn.lStructSize = sizeof(OPENFILENAME);
			ofn.hwndOwner = hDlg;
			ofn.lpstrFilter = "Icon Files (*.ico)\0*.ico\0\0";
			ofn.lpstrFile = szIFileName;
			ofn.nMaxFile = MAX_PATH;
			ofn.Flags = OFN_PATHMUSTEXIST;
			if(GetOpenFileName(&ofn))
			{
				hIcon = ExtractIcon(hInst, szIFileName, 0);
				SendMessage(GetDlgItem(hDlg, IDC_ICONIMG), STM_SETICON, (WPARAM)hIcon, (LPARAM)0);
			}
		}
		break;
	case WM_RBUTTONDOWN:
		GetCursorPos(&pt);
		GetWindowRect(GetDlgItem(hDlg, IDC_ICONIMG), &rect);
		if(PtInRect(&rect, pt))
		{
			SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(32649)));
		}
		break;
	case WM_COMMAND:
		switch LOWORD(wParam){
		case IDC_BROWSE:
			memset(&ofn, 0, sizeof(ofn));
			szEFileName[0] = '\0';
			ofn.lStructSize = sizeof(OPENFILENAME);
			ofn.hwndOwner = hDlg;
			ofn.lpstrFilter = "Executable Files (*.exe)\0*.exe\0\0";
			ofn.lpstrFile = szEFileName;
			ofn.nMaxFile = MAX_PATH;
			ofn.Flags = OFN_PATHMUSTEXIST;
			if(GetOpenFileName(&ofn))
			{
				if(LoadPE(szEFileName) == FALSE)
				{
					MessageBox(hDlg, "Could not load file!", "Cryptic", MB_ICONERROR);
					return TRUE;
				}
				SetDlgItemText(hDlg, IDC_FILE, szEFileName);
				EnableWindow(GetDlgItem(hDlg, IDC_BUILD), TRUE);
			}
			break;
		case IDC_BUILD:
			EnableControls(hDlg, FALSE);
			HRSRC hRsrc;
			hRsrc = FindResource(NULL, MAKEINTRESOURCE(IDR_STUB), "STUB");
			if(hRsrc == NULL)
			{
				MessageBox(hDlg, "Could not find resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			DWORD dwRsrcSize;
			dwRsrcSize = SizeofResource(NULL, hRsrc);
			HGLOBAL hGlob;
			hGlob = LoadResource(NULL, hRsrc);
			if(hGlob == NULL)
			{
				MessageBox(hDlg, "Could not load resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			LPBYTE lpBuffer;
			lpBuffer = (LPBYTE)LockResource(hGlob);
			if(lpBuffer == NULL)
			{
				MessageBox(hDlg, "Could not lock resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			GetDlgItemText(hDlg, IDC_FILE, szEFileName, MAX_PATH);
			if(IsDlgButtonChecked(hDlg, IDC_BACKUP) == BST_CHECKED)
			{
				CHAR szBFileName[MAX_PATH];
				GetDlgItemText(hDlg, IDC_FILE, szBFileName, MAX_PATH);
				strcat(szBFileName, ".bak");
				if(CopyFile(szEFileName, szBFileName, FALSE) == 0)
				{
					free(lpBuffer);
					MessageBox(hDlg, "Could not copy file!", "Cryptic", MB_ICONERROR);
					EnableControls(hDlg, TRUE);
					return TRUE;
				}
			}
			BYTE lpKey[14];
			srand(time(NULL));
			int i;
			for(i = 0; i < 15; i++)
			{
				lpKey[i] = BYTE(rand() % 255 + 1);
			}
			HANDLE hFile;
			hFile = CreateFile(szEFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL);
			if(hFile == INVALID_HANDLE_VALUE)
			{
				free(lpBuffer);
				MessageBox(hDlg, "Could not create file!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			DWORD dwBytesWritten;
			if(WriteFile(hFile, lpBuffer, dwRsrcSize, &dwBytesWritten, NULL) == 0)
			{
				CloseHandle(hFile);
				free(lpBuffer);
				MessageBox(hDlg, "Could not write to file!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			CloseHandle(hFile);
			free(lpBuffer);
			if(IsDlgButtonChecked(hDlg, IDC_ADDICON) == BST_CHECKED)
			{
				if(AddIcon(szIFileName, szEFileName) == FALSE)
				{
					MessageBox(hDlg, "Could add icon!", "Cryptic", MB_ICONERROR);
					EnableControls(hDlg, TRUE);
					return TRUE;
				}
			}
			HANDLE hUpdate;
			hUpdate = BeginUpdateResource(szEFileName, FALSE);
			if(hUpdate == NULL)
			{
				MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			if(UpdateResource(hUpdate, RT_RCDATA, MAKEINTRESOURCE(150), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), RC4(lpFileBuffer, lpKey, dwFileSize, 15), dwFileSize) == FALSE)
			{
				MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			if(UpdateResource(hUpdate, RT_RCDATA, MAKEINTRESOURCE(151), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), &lpKey[0], 15) == FALSE)
			{
				MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			if(EndUpdateResource(hUpdate, FALSE) == FALSE)
			{
				MessageBox(hDlg, "Could add resource!", "Cryptic", MB_ICONERROR);
				EnableControls(hDlg, TRUE);
				return TRUE;
			}
			RC4(lpFileBuffer, lpKey, dwFileSize, 15);
			pish = (PIMAGE_SECTION_HEADER)&lpFileBuffer[pidh->e_lfanew + sizeof(IMAGE_NT_HEADERS) + sizeof(IMAGE_SECTION_HEADER) * (pinh->FileHeader.NumberOfSections - 1)];
			if(dwFileSize > (pish->PointerToRawData + pish->SizeOfRawData))
			{
				MessageBox(hDlg, "EOF data found!", "Cryptic", MB_OK);
				hFile = CreateFile(szEFileName, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
				if(hFile == INVALID_HANDLE_VALUE)
				{
					MessageBox(hDlg, "Could not open file!", "Cryptic", MB_ICONERROR);
					EnableControls(hDlg, TRUE);
					return TRUE;
				}
				SetFilePointer(hFile, 0, NULL, FILE_END);
				if(WriteFile(hFile, &lpFileBuffer[pish->PointerToRawData + pish->SizeOfRawData + 1], dwFileSize - (pish->PointerToRawData + pish->SizeOfRawData), &dwBytesWritten, NULL) == 0)
				{
					CloseHandle(hFile);
					MessageBox(hDlg, "Could not write to file!", "Cryptic", MB_ICONERROR);
					EnableControls(hDlg, TRUE);
					return TRUE;
				}
				CloseHandle(hFile);
			}
			MessageBox(hDlg, "File successfully crypted!", "Cryptic", MB_ICONINFORMATION);
			EnableControls(hDlg, TRUE);
			break;
		case IDC_ABOUT:
			MessageBox(hDlg, "Cryptic v3.0\nCoded by Tughack", "About", MB_ICONINFORMATION);
			break;
		case IDC_EXIT:
			EndDialog(hDlg, 0);
			break;
		}
	}
	return FALSE;
}
Esempio n. 25
0
bool SolverCalculateNormals::LoadShaders()
{
	if (true == mNeedProgramReload)
	{
		mProgramZero.Clear();
		mProgramNorm.Clear();
		mProgramRecomputeNormals.Clear();
		mNeedProgramReload = false;
	}

	// check for a compute shader
	/*
	if (false == mProgramZero.PrepProgram("\\GLSL_CS\\recomputeNormalsZero.cs") )
		return false;

	if (false == mProgramRecomputeNormals.PrepProgram("\\GLSL_CS\\recomputeNormals.cs") )
		return false;
	
	if (false == mProgramNorm.PrepProgram("\\GLSL_CS\\recomputeNormalsNorm.cs") )
		return false;
		*/

	
	if (0 == mProgramZero.GetProgramId() )
	{
		bool res = false;
		char* data = nullptr;
		HINSTANCE hInst = GetThisModuleHandle();
		
		HRSRC hRes = FindResourceEx(hInst,
                           "TEXT",
                           MAKEINTRESOURCE(IDR_TEXT1),
                           MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_NEUTRAL));
						   
		if(nullptr != hRes)
		{
			HGLOBAL hData = LoadResource(hInst, hRes);
			if (hData)
			{
				DWORD dataSize = SizeofResource(hInst, hRes);
				data = (char*)LockResource(hData);
				
				char *shaderData = new char[dataSize+1];
				memset( shaderData, 0, sizeof(char) * (dataSize+1) );
				memcpy( shaderData, data, sizeof(char) * dataSize );

				res = mProgramZero.PrepProgramFromBuffer(shaderData, "recomputeNormalsZero");
				
				delete [] shaderData;

				UnlockResource(hData);
			}
		}

		if (false == res)
		{
			Active =false;
			return false;
		}
	}
	if (0 == mProgramNorm.GetProgramId() )
	{
		bool res = false;
		char* data = nullptr;
		HINSTANCE hInst = GetThisModuleHandle();
		
		HRSRC hRes = FindResourceEx(hInst,
                           "TEXT",
                           MAKEINTRESOURCE(IDR_TEXT2),
                           MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_NEUTRAL));
		if(nullptr != hRes)
		{
			HGLOBAL hData = LoadResource(hInst, hRes);
			if (hData)
			{
				DWORD dataSize = SizeofResource(hInst, hRes);
				data = (char*)LockResource(hData);

				char *shaderData = new char[dataSize+1];
				memset( shaderData, 0, sizeof(char) * (dataSize+1) );
				memcpy( shaderData, data, sizeof(char) * dataSize );

				res = mProgramNorm.PrepProgramFromBuffer(shaderData, "recomputeNormalsNorm");
				
				delete [] shaderData;

				UnlockResource(hData);
			}
		}

		if (false == res)
		{
			Active =false;
			return false;
		}
	}
	if (0 == mProgramRecomputeNormals.GetProgramId() )
	{
		bool res = false;
		char* data = nullptr;
		HINSTANCE hInst = GetThisModuleHandle();
		
		HRSRC hRes = FindResourceEx(hInst,
                           "TEXT",
                           MAKEINTRESOURCE(IDR_TEXT3),
                           MAKELANGID(LANG_NEUTRAL,
                           SUBLANG_NEUTRAL));
		if(nullptr != hRes)
		{
			HGLOBAL hData = LoadResource(hInst, hRes);
			if (hData)
			{
				DWORD dataSize = SizeofResource(hInst, hRes);
				data = (char*)LockResource(hData);

				char *shaderData = new char[dataSize+1];
				memset( shaderData, 0, sizeof(char) * (dataSize+1) );
				memcpy( shaderData, data, sizeof(char) * dataSize );

				res = mProgramRecomputeNormals.PrepProgramFromBuffer(shaderData, "recomputeNormals");
				
				delete [] shaderData;

				UnlockResource(hData);
			}
		}

		if (false == res)
		{
			Active =false;
			return false;
		}
	}

	return true;
}
Esempio n. 26
0
/*** IDirectXFile methods ***/
static HRESULT WINAPI IDirectXFileImpl_CreateEnumObject(IDirectXFile* iface, LPVOID pvSource, DXFILELOADOPTIONS dwLoadOptions, LPDIRECTXFILEENUMOBJECT* ppEnumObj)
{
  IDirectXFileImpl *This = impl_from_IDirectXFile(iface);
  IDirectXFileEnumObjectImpl* object;
  HRESULT hr;
  LPBYTE file_buffer;
  DWORD file_size;
  DWORD bytes_written;

  TRACE("(%p/%p)->(%p,%x,%p)\n", This, iface, pvSource, dwLoadOptions, ppEnumObj);

  if (!ppEnumObj)
    return DXFILEERR_BADVALUE;

  /* Only lowest 4 bits are relevant in DXFILELOADOPTIONS */
  dwLoadOptions &= 0xF;

  hr = IDirectXFileEnumObjectImpl_Create(&object);
  if (FAILED(hr))
    return hr;

  if (dwLoadOptions == DXFILELOAD_FROMFILE)
  {
    HANDLE hFile, file_mapping;

    TRACE("Open source file '%s'\n", (char*)pvSource);

    hFile = CreateFileA(pvSource, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
      TRACE("File '%s' not found\n", (char*)pvSource);
      return DXFILEERR_FILENOTFOUND;
    }

    file_size = GetFileSize(hFile, NULL);

    file_mapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    CloseHandle(hFile);
    if (!file_mapping)
    {
      hr = DXFILEERR_BADFILETYPE;
      goto error;
    }

    object->mapped_memory = MapViewOfFile(file_mapping, FILE_MAP_READ, 0, 0, 0);
    CloseHandle(file_mapping);
    if (!object->mapped_memory)
    {
      hr = DXFILEERR_BADFILETYPE;
      goto error;
    }
    file_buffer = object->mapped_memory;
  }
  else if (dwLoadOptions == DXFILELOAD_FROMRESOURCE)
  {
    HRSRC resource_info;
    HGLOBAL resource_data;
    LPDXFILELOADRESOURCE lpdxflr = pvSource;

    TRACE("Source in resource (module = %p, name = %s, type = %s)\n", lpdxflr->hModule, debugstr_a(lpdxflr->lpName), debugstr_a(lpdxflr->lpType));

    resource_info = FindResourceA(lpdxflr->hModule, lpdxflr->lpName, lpdxflr->lpType);
    if (!resource_info)
    {
      hr = DXFILEERR_RESOURCENOTFOUND;
      goto error;
    }

    file_size = SizeofResource(lpdxflr->hModule, resource_info);

    resource_data = LoadResource(lpdxflr->hModule, resource_info);
    if (!resource_data)
    {
      hr = DXFILEERR_BADRESOURCE;
      goto error;
    }

    file_buffer = LockResource(resource_data);
    if (!file_buffer)
    {
      hr = DXFILEERR_BADRESOURCE;
      goto error;
    }
  }
  else if (dwLoadOptions == DXFILELOAD_FROMMEMORY)
  {
    LPDXFILELOADMEMORY lpdxflm = pvSource;

    TRACE("Source in memory at %p with size %d\n", lpdxflm->lpMemory, lpdxflm->dSize);

    file_buffer = lpdxflm->lpMemory;
    file_size = lpdxflm->dSize;
  }
  else
  {
    FIXME("Source type %d is not handled yet\n", dwLoadOptions);
    hr = DXFILEERR_NOTDONEYET;
    goto error;
  }

  TRACE("File size is %d bytes\n", file_size);

  if (TRACE_ON(d3dxof_dump))
  {
    static USHORT num;
    char tmp[12];
    HANDLE file;
    sprintf(tmp, "file%05u.x", num++);

    file = CreateFileA(tmp, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
    if (file != INVALID_HANDLE_VALUE)
    {
      WriteFile(file, file_buffer, file_size, &bytes_written, NULL);
      CloseHandle(file);
    }
  }

  object->pDirectXFile = This;

  object->buf.pdxf = This;
  object->buf.token_present = FALSE;
  object->buf.buffer = file_buffer;
  object->buf.rem_bytes = file_size;
  hr = parse_header(&object->buf, &object->decomp_buffer);
  if (FAILED(hr))
    goto error;

  /* Check if there are templates defined before the object */
  if (!parse_templates(&object->buf, TRUE))
  {
    hr = DXFILEERR_PARSEERROR;
    goto error;
  }

  if (TRACE_ON(d3dxof))
  {
    ULONG i;
    TRACE("Registered templates (%d):\n", This->nb_xtemplates);
    for (i = 1; i < This->nb_xtemplates; i++)
      DPRINTF("%s - %s\n", This->xtemplates[i].name, debugstr_guid(&This->xtemplates[i].class_id));
  }

  *ppEnumObj = &object->IDirectXFileEnumObject_iface;

  return DXFILE_OK;

error:
  IDirectXFileEnumObject_Release(&object->IDirectXFileEnumObject_iface);
  *ppEnumObj = NULL;

  return hr;
}
Esempio n. 27
0
//////////////////////////////////////////////////////////////////////////////////////
//
// RESOURCES => Extraction de fmod.dll (en run-time grâce à l'option /DELAYLOAD:fmod.dll)
//              le déchargement éventuel de l'ancienne version nécessite /DELAY:UNLOAD
//
void fmod_extract (void)
{
	// on vérifie si fmod.dll est présent dans le répertoire système de windows
	// (/system pour win9x/ME, /system32 pour win2000/XP)

	char Path[MAX_PATH+1];
	GetSystemDirectory ( Path, MAX_PATH+1 );

	WIN32_FIND_DATA FindFileData;
	HANDLE hFind;

	char searchFile[MAX_PATH+1];
	strcpy(searchFile, Path);
	strcat(searchFile, "\\fmod.dll");

	hFind = FindFirstFile(searchFile, &FindFileData);

	// la version est-elle à jour ?
	// si la version trouvée est inférieure à la version en ressource interne
	// nous devons décharger de la mémoire la première pour la remplacer par la
	// deuxième. Car l'appel de FSOUND_GetVersion() ci-dessous charge
	// automatiquement l'ancienne version pour toute la durée d'exécution.

	bool fmodIsUptodate = false;
	if ((hFind != INVALID_HANDLE_VALUE))						// si le fichier existe
		if (FSOUND_GetVersion() < FMOD_VERSION)					// si la version est inférieure
		{
			fmodIsUptodate = false;
			// décharge l'ancienne dll			
			#if _MSC_VER >= 1300
				if (FAILED(__FUnloadDelayLoadedDLL2("fmod.dll")))	// MSVC++ 7.0 et +
			#else
				//if (FAILED(__FUnloadDelayLoadedDLL("fmod.dll")))	// MSVC++ 6.0 et -
			#endif
				ERR("Error unloading the old fmod.dll.\nTry to delete %system%/fmod.dll and restart the game.\nIt will extract a new version automatically.\n");
		}
		else
			fmodIsUptodate = true;

	// s'il n'est pas présent ou la version plus ancienne on le crée
	if ((hFind == INVALID_HANDLE_VALUE) || (hFind != INVALID_HANDLE_VALUE && !fmodIsUptodate))
	{
		// déclarations et initialisations
		char		m_szFilename[MAX_PATH];
		HINSTANCE	m_hModule	= NULL;
		char		m_szType[MAX_PATH];
		DWORD		m_dwID;

		DWORD		dwID		= IDR_BINARY_FMOD;
		LPCSTR		szType		= "BINARY";
		LPCSTR		szFilename	= strcat(Path, "\\fmod.dll");

		memset(m_szType,0,sizeof m_szType);
		memcpy(m_szType,(void*)szType,strlen(szType));

		memset(m_szFilename,0,sizeof m_szFilename);
		memcpy(m_szFilename,szFilename,strlen(szFilename));

		m_dwID = dwID;

		// extraction de la ressource
		HRSRC	hRes		= FindResource(m_hModule, MAKEINTRESOURCE(m_dwID), m_szType);
		DWORD	dwDataSize	= SizeofResource(m_hModule,hRes);
		HGLOBAL	hGlob		= LoadResource(m_hModule,hRes);
		LPVOID	pData		= LockResource(hGlob);

		// création du fichier
		HANDLE hFile = CreateFile (m_szFilename, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

		if( hFile == INVALID_HANDLE_VALUE )
		{
			UnlockResource(hGlob);
			FreeResource(hGlob);	
		}

		DWORD	dwBytesWritten=0;

		if( !WriteFile(hFile,pData,dwDataSize,&dwBytesWritten,NULL) 
			||
			dwBytesWritten != dwDataSize)
		{
			CloseHandle(hFile);
			UnlockResource(hGlob);
			FreeResource(hGlob);	
			if(DeleteFile(m_szFilename))
				memset(m_szFilename,0,sizeof m_szFilename);
		}

		CloseHandle(hFile);
		UnlockResource(hGlob);
		FreeResource(hGlob);
	}

	FindClose (hFind);
}
Esempio n. 28
0
PGPError SDAEncryptFile(MYSTATE *ms,
		PGPSymmetricCipherContextRef CASTContext)
{
	SDAHEADER *SDAHeader;
	FILE *fout;
	char inbuffer[kBlockSize];
	char outbuffer[kBlockSize];
	char szOutput[MAX_PATH+1];
	PGPFileSpecRef filespec;
	char *fullPathPtr;
	BOOL CancelOperation;
	GETPUTINFO gpi;
	DWORD dwStubSize;
	HRSRC hRCStub;
	HGLOBAL hGBStub;
	char *pStubData;
	FILELIST *flnext,*fl;
	char *lastslash;
	BOOL OneDirectory;
	char szCaption[256];

	hRCStub=FindResource(g_hinst,
		MAKEINTRESOURCE(IDR_SDASTUB),
		RT_RCDATA);

	dwStubSize=SizeofResource(g_hinst,hRCStub);

	hGBStub=LoadResource(g_hinst,hRCStub);
	pStubData=(char *)LockResource(hGBStub);

	// Sanity checking here for resource munging
	if(!((*(USHORT *)pStubData == IMAGE_DOS_SIGNATURE) &&
        (*(DWORD *)NTSIGNATURE (pStubData) == IMAGE_NT_SIGNATURE)))
	{
		PGPscMessageBox (ms->hwndWorking,IDS_PGPERROR,IDS_COULDNOTOPENSTUB,
		MB_OK|MB_ICONSTOP);

		return kPGPError_NoErr;
	}

	// Reverse list since we need directories first
	fl=NULL;

	while(ms->ListHead!=NULL)
	{
		flnext=ms->ListHead->next;
		
		ms->ListHead->next=fl;
		fl=ms->ListHead;

		ms->ListHead=flnext;
	}

	// Now same, but reversed
	ms->ListHead=fl;

	// Check to see if we only have one directory with contents
	OneDirectory=ms->ListHead->IsDirectory;

	SDAHeader=ms->SDAHeader;

	strcpy(szOutput,ms->ListHead->name);
	strcat(szOutput,".sda.exe");

	if(OneDirectory)
	{
		LoadString (g_hinst, IDS_FILECONFLICT, szCaption, sizeof(szCaption));

		// Do automatically if possible
		CancelOperation=SaveOutputFile(ms->context,
			ms->hwndWorking, 
			szCaption,
			szOutput, 
			&filespec,
			FALSE);
	}
	else
	{
		LoadString (g_hinst, IDS_CONFIRMSDANAME, szCaption, sizeof(szCaption));

		// Always check with the user first
		CancelOperation=SaveOutputFile(ms->context,
			ms->hwndWorking, 
			szCaption,
			szOutput, 
			&filespec,
			TRUE);
	}

	if(CancelOperation)
		return kPGPError_UserAbort;

	PGPGetFullPathFromFileSpec( filespec,
		&fullPathPtr);

	strcpy(szOutput,fullPathPtr);
	PGPFreeData(fullPathPtr);
	PGPFreeFileSpec(filespec);

	fout=fopen(szOutput,"wb");

	if(fout==0)
	{
		PGPscMessageBox (ms->hwndWorking,IDS_PGPERROR,IDS_COULDNOTOPENFILE,
				MB_OK|MB_ICONSTOP);

		return kPGPError_UserAbort;
	}

	// Copy SDA.exe prefix executable into SDA file and
	// set header offset so we can find data again.
	// Write out stub to disk from resources
	fwrite(pStubData,1,dwStubSize,fout);

	UnlockResource(hGBStub);
	FreeResource(hGBStub);

	SDAHeader->offset=dwStubSize;

	// Initialize variables for compression call
	memset(&gpi,0x00,sizeof(GETPUTINFO));

	gpi.fout=fout;
	gpi.SDAHeader=SDAHeader;
	gpi.blockindex=0;
	gpi.outbuffer=outbuffer;
	gpi.inbuffer=inbuffer;
	gpi.hwnd=ms->hwndWorking;
	gpi.CASTContext=CASTContext;
	gpi.from_pointer=0;
	gpi.CancelOperation=FALSE;
	gpi.ms=ms;
	gpi.bFeedFilename=TRUE;
	gpi.fl=fl;
	gpi.hPrgDlg=(HPRGDLG)GetWindowLong(ms->hwndWorking, GWL_USERDATA);

	// Find beginning of SDA directory tree
	lastslash=strrchr(gpi.fl->name,'\\');
	if(lastslash==NULL)
		lastslash=gpi.fl->name;
	else
		lastslash++;

	gpi.PathHead=lastslash-gpi.fl->name;

	Deflate_Compress(&gpi);

	if(gpi.fin)
		fclose(gpi.fin);

	fl=NULL;

	// Re-reverse list since we may need to delete
	while(ms->ListHead!=NULL)
	{
		flnext=ms->ListHead->next;
		
		ms->ListHead->next=fl;
		fl=ms->ListHead;

		ms->ListHead=flnext;
	}

	// Now same, but reversed
	ms->ListHead=fl;

	// Write out the last block since compress doesn't
	// know how we are delaying writes
	if(gpi.to_pointer!=0)
	{
		EncryptBlock512(gpi.CASTContext,
			gpi.SDAHeader,
			gpi.blockindex,
			(const PGPUInt32 *)gpi.inbuffer,
			(PGPUInt32 *)gpi.outbuffer);

		fwrite(gpi.outbuffer,1,kBlockSize,gpi.fout);
	}

	fwrite(SDAHeader,1,sizeof(SDAHEADER),fout);

	memset(inbuffer,0x00,kBlockSize);
	memset(outbuffer,0x00,kBlockSize);

	fclose(fout);

	if(gpi.CancelOperation)
	{
		remove(szOutput);
		return kPGPError_UserAbort;
	}

	return kPGPError_NoErr;
}
Esempio n. 29
0
// Load bitmap from app's resource
HRESULT LoadResourceBitmap(
						   ID2D1RenderTarget* pRendertarget,
						   IWICImagingFactory* pIWICFactory,
						   PCSTR resourceName,
						   PCSTR resourceType,
						   UINT destinationWidth,
						   UINT destinationHeight,
						   ID2D1Bitmap** ppBitmap
						   )
{
	HRESULT hr = S_OK ;

	IWICBitmapDecoder* pDecoder = NULL ;
	IWICBitmapFrameDecode* pSource = NULL ;
	IWICStream* pStream = NULL ;
	IWICFormatConverter* pConverter = NULL ;
	IWICBitmapScaler* pScaler = NULL ;

	HRSRC imageResHandle = NULL ;
	HGLOBAL imageResDataHandle = NULL ;
	void* pImageFile = NULL ;
	DWORD imageFileSize = 0 ;

	// Find the resource then load it
	imageResHandle = FindResource(HINST_THISCOMPONENT, resourceName, resourceType) ;
	hr = imageResHandle ? S_OK : E_FAIL ;
	if (SUCCEEDED(hr))
	{
		imageResDataHandle = LoadResource(HINST_THISCOMPONENT, imageResHandle) ;

		hr = imageResDataHandle ? S_OK : E_FAIL ;
	}

	// Lock the resource and calculate the image's size
	if (SUCCEEDED(hr))
	{
		// Lock it to get the system memory pointer
		pImageFile = LockResource(imageResDataHandle) ;

		hr = pImageFile ? S_OK : E_FAIL ;
	}
	if (SUCCEEDED(hr))
	{
		// Calculate the size
		imageFileSize = SizeofResource(HINST_THISCOMPONENT, imageResHandle) ;

		hr = imageFileSize ? S_OK : E_FAIL ;
	}

	// Create an IWICStream object
	if (SUCCEEDED(hr))
	{
		// Create a WIC stream to map onto the memory
		hr = pIWICFactory->CreateStream(&pStream) ;
	}

	if (SUCCEEDED(hr))
	{
		// Initialize the stream with the memory pointer and size
		hr = pStream->InitializeFromMemory(
			reinterpret_cast<BYTE*>(pImageFile),
			imageFileSize
			) ;
	}

	// Create IWICBitmapDecoder
	if (SUCCEEDED(hr))
	{
		// Create a decoder for the stream
		hr = pIWICFactory->CreateDecoderFromStream(
			pStream,
			NULL,
			WICDecodeMetadataCacheOnLoad,
			&pDecoder
			) ;
	}

	// Retrieve a frame from the image and store it in an IWICBitmapFrameDecode object
	if (SUCCEEDED(hr))
	{
		// Create the initial frame
		hr = pDecoder->GetFrame(0, &pSource) ;
	}

	// Before Direct2D can use the image, it must be converted to the 32bppPBGRA pixel format.
	// To convert the image format, use the IWICImagingFactory::CreateFormatConverter method to create an IWICFormatConverter object, then use the IWICFormatConverter object's Initialize method to perform the conversion.
	if (SUCCEEDED(hr))
	{
		// Convert the image format to 32bppPBGRA
		// (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
		hr = pIWICFactory->CreateFormatConverter(&pConverter) ;
	}

	if (SUCCEEDED(hr))
	{
		// If a new width or height was specified, create and
		// IWICBitmapScaler and use it to resize the image.
		if (destinationWidth != 0 || destinationHeight != 0)
		{
			UINT originalWidth ;
			UINT originalHeight ;
			hr = pSource->GetSize(&originalWidth, &originalHeight) ;
			if (SUCCEEDED(hr))
			{
				if (destinationWidth == 0)
				{
					FLOAT scalar = static_cast<FLOAT>(destinationHeight) / static_cast<FLOAT>(originalHeight);
					destinationWidth = static_cast<UINT>(scalar * static_cast<FLOAT>(originalWidth)) ;
				}
				else if (destinationHeight == 0)
				{
					FLOAT scalar = static_cast<FLOAT>(destinationWidth) / static_cast<FLOAT>(originalWidth);
					destinationHeight = static_cast<UINT>(scalar * static_cast<FLOAT>(originalHeight));
				}

				hr = pIWICFactory->CreateBitmapScaler(&pScaler) ;
				if (SUCCEEDED(hr))
				{
					hr = pScaler->Initialize(
						pSource,
						destinationWidth,
						destinationHeight,
						WICBitmapInterpolationModeCubic
						) ;
					if (SUCCEEDED(hr))
					{
						hr = pConverter->Initialize(
							pScaler,
							GUID_WICPixelFormat32bppPBGRA,
							WICBitmapDitherTypeNone,
							NULL,
							0.f,
							WICBitmapPaletteTypeMedianCut
							) ;
					}
				}
			}
		}

		else // use default width and height
		{
			hr = pConverter->Initialize(
				pSource,
				GUID_WICPixelFormat32bppPBGRA,
				WICBitmapDitherTypeNone,
				NULL,
				0.f,
				WICBitmapPaletteTypeMedianCut
				) ;
		}
	}

	// Finally, Create an ID2D1Bitmap object, that can be drawn by a render target and used with other Direct2D objects
	if (SUCCEEDED(hr))
	{
		// Create a Direct2D bitmap from the WIC bitmap
		hr = pRendertarget->CreateBitmapFromWicBitmap(
			pConverter,
			NULL,
			ppBitmap
			) ;
	}

	SAFE_RELEASE(pDecoder) ;
	SAFE_RELEASE(pSource) ;
	SAFE_RELEASE(pStream) ;
	SAFE_RELEASE(pConverter) ;
	SAFE_RELEASE(pScaler) ;

	return hr ;
}
Esempio n. 30
0
//////////////////////////////////////////////////////////////////////////
//  This is the routine where we create the data being output by the Virtual
//  Camera device.
//////////////////////////////////////////////////////////////////////////
bool badRes = false;
bool badServer = false;
HANDLE fileHandle = NULL;
void* file;
int frameWidth = 640;
int frameHeight = 480;
int fileSize = (1280 * 1024 * 3) + 3;
int serverDown = 0;

HMODULE thisLibrary = LoadLibrary(L"NiVirtualCamFilter.dll");
HRSRC errorBitmapInfo = FindResource(thisLibrary, MAKEINTRESOURCE(4), MAKEINTRESOURCE(10));
int errorBitmapSize = SizeofResource(thisLibrary, errorBitmapInfo);
HGLOBAL errorBitmap = LoadResource(thisLibrary, errorBitmapInfo);
void* errorBitmapData = LockResource(errorBitmap);
bool errorBitmapLoaded = errorBitmapSize > 0;
HRESULT CKCamStream::FillBuffer(IMediaSample *pms)
{
	// Init setting object
	if (fileHandle == NULL){
		fileHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, L"OpenNiVirtualCamFrameData");
		if (fileHandle == NULL){
			//fileHandle = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, FILE_MAP_ALL_ACCESS, 0, fileSize, L"OpenNiVirtualCamFrameData");
			if (fileHandle == NULL && !badServer){
				badServer = true;
                MessageBox(NULL, L"Can not connect to the Server; please make sure that NiVirtualCam Controller Application is running. We keep trying until you open it.", L"Connection failed", MB_ICONWARNING);
            }
		}else