Exemplo n.º 1
1
void VolumeControlData::DrawVolumeControl(HDC hDC)
{
    HDC hdcTemp = CreateCompatibleDC(hDC);
    HBITMAP hbmpTemp = CreateCompatibleBitmap(hDC, cx, cy);
    SelectObject(hdcTemp, hbmpTemp);

    RECT clientRect = {0, 0, cx, cy};
    FillRect(hdcTemp, &clientRect, (HBRUSH)COLOR_WINDOW);

    HBRUSH hGray = CreateSolidBrush(REVERSE_COLOR(Color_Gray));
    HBRUSH hRed  = CreateSolidBrush(0x2020bf);//0xff4040);

    float visualVolume = (bDisabled) ? 0.0f : curVolume;

    int cxAdjust = cx;
    if(bDrawIcon) cxAdjust -= 32;

    const int padding = 1;
    const float volSliceSize = float(cxAdjust-(padding*9))/10.0f;

    int volPixelPos = int(visualVolume*float(cxAdjust));

    if(volSliceSize > 1.0f)
    {
        float ySliceStart, ySliceSize;
        if(bDrawIcon)
        {
            ySliceStart = 4.0f;
            ySliceSize = float((cy-ySliceStart)/10);
        }
        else
        {
            ySliceStart = 0.0f;
            ySliceSize = float(cy/10);
        }

        for(int i=0; i<10; i++)
        {
            int pos = int(volSliceSize*float(i)) + (padding*i);

            RECT sliceRect = {pos, int(ySliceStart+((9.0f-float(i))*ySliceSize)), pos+int(volSliceSize), cy};

            if(sliceRect.right < volPixelPos) //full
                FillRect(hdcTemp, &sliceRect, hRed);
            else if(sliceRect.left < volPixelPos) //half
            {
                RECT leftHalf, rightHalf;
                mcpy(&leftHalf,  &sliceRect, sizeof(sliceRect));
                mcpy(&rightHalf, &sliceRect, sizeof(sliceRect));

                rightHalf.left = leftHalf.right = volPixelPos;
                FillRect(hdcTemp, &leftHalf, hRed);
                FillRect(hdcTemp, &rightHalf, hGray);
            }
            else //empty
                FillRect(hdcTemp, &sliceRect, hGray);
        }

        if(bDrawIcon)
            DrawIcon(hdcTemp, cx-32, 0, (visualVolume > VOLN_MUTELEVEL) ? hiconPlay : hiconMute);

        if(visualVolume > VOLN_MUTELEVEL && bHasCapture)
        {
            HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
            HFONT hfontOld = (HFONT)SelectObject(hdcTemp, hFont);

            SetTextColor(hdcTemp, GetSysColor(COLOR_WINDOWTEXT));
        
            SetBkMode(hdcTemp, TRANSPARENT);

            String volText= FormattedString(TEXT("%d%%"), int(curVolume*100));

            TextOut(hdcTemp, clientRect.left + (LONG)volSliceSize, clientRect.top, volText, slen(volText));
        
            SelectObject(hdcTemp, hfontOld);
        }
    }

    BitBlt(hDC, 0, 0, cx, cy, hdcTemp, 0, 0, SRCCOPY);

    DeleteObject(hdcTemp);
    DeleteObject(hbmpTemp);

    DeleteObject(hGray);
    DeleteObject(hRed);
}
Exemplo n.º 2
0
int main()
{
// Create a normal DC and a memory DC for the entire screen. The
// normal DC provides a "snapshot" of the screen contents. The
// memory DC keeps a copy of this "snapshot" in the associated
// bitmap.
HDC hdcScreen, hdcCompatible;
HBITMAP hbmScreen;
SYSTEMTIME time;
char* filename;
char* filepath;
char* regSubKeyBase = "Software\\PJBSoftware\\ScreenShooter";

bool isRegVersion = false;

filepath = (char*)malloc(100 * sizeof(char));
if (!filepath) return 1;


HKEY progKey;
//Get the screenshot location from the registry, else stuff 'em in "My Documents"
if (RegOpenKeyEx(HKEY_CURRENT_USER,regSubKeyBase,0,KEY_QUERY_VALUE,&progKey) == ERROR_SUCCESS)
{
    DWORD buffsize = 100;
    DWORD type;
    if (RegQueryValueEx(progKey,"ScreenshotPath",NULL,&type,(LPBYTE)filepath,&buffsize) != ERROR_SUCCESS) return 1;
 }
else
{
    char* username = (char*) malloc(25 * sizeof(char));
    if (! username) return 1;
    DWORD buffsize = 25;
    BOOL st = GetUserName(username,&buffsize);
    if (!st) return 1;


    sprintf(filepath,"C:\\Documents and Settings\\%s\\My Documents",username);
    free (username);
}

// Get the time
GetLocalTime((LPSYSTEMTIME)&time);

hdcScreen = CreateDC("DISPLAY", NULL, NULL, NULL);
hdcCompatible = CreateCompatibleDC(hdcScreen);

// Create a compatible bitmap for hdcScreen.

hbmScreen = CreateCompatibleBitmap(hdcScreen,
                     GetDeviceCaps(hdcScreen, HORZRES),
                     GetDeviceCaps(hdcScreen, VERTRES));

if (hbmScreen == 0)
    printf("Could not create bitmap\n");

// Select the bitmaps into the compatible DC.

if (!SelectObject(hdcCompatible, hbmScreen))
    printf("Could not select bitmap\n");



         //Copy color data for the entire display into a
         //bitmap that is selected into a compatible DC.

        if (!BitBlt(hdcCompatible,
               0,0,
               GetDeviceCaps(hdcScreen, HORZRES), GetDeviceCaps(hdcScreen, VERTRES),
               hdcScreen,
               0,0,
               SRCCOPY))

         printf("Screen to Compat Blt Failed\n");

    filename = (char*)malloc(150 * sizeof(char));
    if (!filename) return 1;

    sprintf(filename,"%s\\screenshot-%04u-%02u-%02u-%02u%02u%02u.bmp",filepath,time.wYear,time.wMonth,time.wDay,time.wHour,time.wMinute,time.wSecond);
    free(filepath);


    CreateBMPFile(filename,CreateBitmapInfoStruct(hbmScreen),hbmScreen,hdcCompatible);

    free(filename);

 	return 0;


}
//Loosely based on writeWindowText() @ 0x0041F2B0
void Bitmap::blitKoreanChar(const char *ch, int &x, int &y, u8 fontSize, u8 color) {
  static HFONT gulim_8pt = NULL, gulim_9pt = NULL, gulim_10pt = NULL, gulim_11pt = NULL;
  static HDC bufferDc = NULL;
  static HBITMAP bufferBmp = NULL; //Temporary bitmap to draw the character
  
  //Load Korean fonts
  if (!gulim_9pt) {
    HDC screenDc = GetDC(NULL);
    LOGFONT lFont = {};
    strcpy(lFont.lfFaceName, "±¼¸²");
    lFont.lfCharSet = HANGUL_CHARSET;
    
    lFont.lfHeight = -MulDiv(8, GetDeviceCaps(screenDc, LOGPIXELSY), 72); //Not in StarCraft
    gulim_8pt = CreateFontIndirect(&lFont);
    
    lFont.lfHeight = -MulDiv(9, GetDeviceCaps(screenDc, LOGPIXELSY), 72);
    gulim_9pt = CreateFontIndirect(&lFont);
    
    lFont.lfWeight = FW_BOLD;
    lFont.lfHeight = -MulDiv(10, GetDeviceCaps(screenDc, LOGPIXELSY), 72);
    gulim_10pt = CreateFontIndirect(&lFont);
    
    lFont.lfWeight = FW_BOLD;
    lFont.lfHeight = -MulDiv(11, GetDeviceCaps(screenDc, LOGPIXELSY), 72);
    gulim_11pt = CreateFontIndirect(&lFont);
    
    ReleaseDC(NULL, screenDc);
  }
  
  //Load main and buffer DCs
  if (!bufferBmp) {
    HDC mainDc = GetDC(*hWndMainSC);

    bufferDc = CreateCompatibleDC(mainDc);
    SetBkMode(bufferDc, OPAQUE);
    SetTextColor(bufferDc, RGB(255, 255, 255));
    SetBkColor(bufferDc, RGB(0, 0, 0));
    SelectObject(bufferDc, GetStockObject(BLACK_BRUSH));

    bufferBmp = CreateCompatibleBitmap(mainDc, KOR_CHAR_MAX_WIDTH, KOR_CHAR_MAX_HEIGHT);
    SelectObject(bufferDc, bufferBmp);
    
    ReleaseDC(*hWndMainSC, mainDc);
  }

  //Assume this function is only drawing in-game stuff
  HFONT currentFont;
  switch (fontSize) {
    case 0:
      currentFont = gulim_8pt; break;   //SC uses 9pt, but who cares :P
    case 1:
      currentFont = gulim_9pt; break;
    case 2:
      currentFont = gulim_10pt; break;  //SC uses 11pt, but who cares :P
    case 3:
    default:
      currentFont = gulim_11pt; break;
  }

  SelectObject(bufferDc, currentFont);
  
  char koreanChars[3];
  *(u16*)koreanChars = *(u16*) ch;
  koreanChars[2] = '\0';

  //Retrieve the size of the rectangular area to draw the character
  RECT chRect = {};
  DrawText(bufferDc, koreanChars, strlen(koreanChars), &chRect, DT_CALCRECT);
  
  //Fill the character rectangle with black background
  Rectangle(bufferDc, chRect.left - 1, chRect.top - 1, chRect.right + 1, chRect.bottom + 1);

  //Write character into temporary bitmap buffer
  DrawText(bufferDc, koreanChars, strlen(koreanChars), &chRect, 0);

  //Copy pixel data from temporary bitmap into temporary buffer
  static u8 bitmapBuffer[KOR_CHAR_MAX_WIDTH * KOR_CHAR_MAX_HEIGHT];
  GetBitmapBits(bufferBmp, KOR_CHAR_MAX_WIDTH * chRect.bottom, bitmapBuffer);
  
  //Copy pixels from temporary buffer into StarCraft's own buffer
  for (int yOff = 0; yOff < chRect.bottom; ++yOff) {
    for (int xOff = 0; xOff < chRect.right; ++xOff) {
      if (bitmapBuffer[xOff + KOR_CHAR_MAX_WIDTH * yOff]) {
        this->drawDot(x + xOff + 1, y + yOff + 3, gbFontColors[color][0]); //Shadow
        this->drawDot(x + xOff, y + yOff + 2, gbFontColors[color][1]);
      }
    }
  }

  //Advance pixels
  x += chRect.right;
}
Exemplo n.º 4
0
static void readscreen(void)
{
#if !defined(OPENSSL_SYS_WINCE) && !defined(OPENSSL_SYS_WIN32_CYGWIN)
  HDC		hScrDC;		/* screen DC */
  HDC		hMemDC;		/* memory DC */
  HBITMAP	hBitmap;	/* handle for our bitmap */
  HBITMAP	hOldBitmap;	/* handle for previous bitmap */
  BITMAP	bm;		/* bitmap properties */
  unsigned int	size;		/* size of bitmap */
  char		*bmbits;	/* contents of bitmap */
  int		w;		/* screen width */
  int		h;		/* screen height */
  int		y;		/* y-coordinate of screen lines to grab */
  int		n = 16;		/* number of screen lines to grab at a time */

  if (GetVersion() >= 0x80000000 || !OPENSSL_isservice())
    return;

  /* Create a screen DC and a memory DC compatible to screen DC */
  hScrDC = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
  hMemDC = CreateCompatibleDC(hScrDC);

  /* Get screen resolution */
  w = GetDeviceCaps(hScrDC, HORZRES);
  h = GetDeviceCaps(hScrDC, VERTRES);

  /* Create a bitmap compatible with the screen DC */
  hBitmap = CreateCompatibleBitmap(hScrDC, w, n);

  /* Select new bitmap into memory DC */
  hOldBitmap = SelectObject(hMemDC, hBitmap);

  /* Get bitmap properties */
  GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm);
  size = (unsigned int)bm.bmWidthBytes * bm.bmHeight * bm.bmPlanes;

  bmbits = OPENSSL_malloc(size);
  if (bmbits) {
    /* Now go through the whole screen, repeatedly grabbing n lines */
    for (y = 0; y < h-n; y += n)
    	{
	unsigned char md[MD_DIGEST_LENGTH];

	/* Bitblt screen DC to memory DC */
	BitBlt(hMemDC, 0, 0, w, n, hScrDC, 0, y, SRCCOPY);

	/* Copy bitmap bits from memory DC to bmbits */
	GetBitmapBits(hBitmap, size, bmbits);

	/* Get the hash of the bitmap */
	MD(bmbits,size,md);

	/* Seed the random generator with the hash value */
	RAND_add(md, MD_DIGEST_LENGTH, 0);
	}

    OPENSSL_free(bmbits);
  }

  /* Select old bitmap back into memory DC */
  hBitmap = SelectObject(hMemDC, hOldBitmap);

  /* Clean up */
  DeleteObject(hBitmap);
  DeleteDC(hMemDC);
  DeleteDC(hScrDC);
#endif /* !OPENSSL_SYS_WINCE */
}
Exemplo n.º 5
0
bool
Initialize () {

    // no WinMain so get the module handle:
    g_hInstance = GetModuleHandle(NULL);
    if (g_hInstance == NULL)
        return false;

    // register the window class:
    WNDCLASS wc;

    wc.style         = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = g_hInstance;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = WINDOW_TITLE;

    if (RegisterClass(&wc) == 0)
        return false;

    // create the window:
    g_hWnd = CreateWindow(
        WINDOW_TITLE,                                             // class name
        WINDOW_TITLE,                                             // title
        WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, // style
        CW_USEDEFAULT, CW_USEDEFAULT,                             // position
        CW_USEDEFAULT, CW_USEDEFAULT,                             // size
        NULL,                                                     // no parent
        NULL,                                                     // no menu
        g_hInstance,                                              // instance
        NULL                                                      // no special
    );

    if (g_hWnd == NULL)
        return false;

    // setup double buffering:
    g_hDC = GetDC(g_hWnd);
    if (g_hDC == NULL)
        return false;

    g_hMemDC = CreateCompatibleDC(g_hDC);
    if (g_hMemDC == NULL)
        return false;

    g_hMemBMP = CreateCompatibleBitmap(g_hDC, WINDOW_WIDTH, WINDOW_HEIGHT);
    if (g_hMemBMP == NULL)
        return false;

    SelectObject(g_hMemDC, g_hMemBMP);

    // colors used to draw the effect:
    g_hColor1 = CreateSolidBrush(RGB(184, 178, 251));
    g_hColor2 = CreateSolidBrush(RGB(98, 72, 124));

    if (g_hColor1 == NULL || g_hColor2 == NULL)
        return false;

    return true;
}
Exemplo n.º 6
0
bool
Initialize () {

    // no WinMain so get the module handle:
    g_hInstance = GetModuleHandle(NULL);
    if (g_hInstance == NULL)
        return false;

    // register the window class:
    WNDCLASS wc;

    wc.style         = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = g_hInstance;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = WINDOW_TITLE;

    if (RegisterClass(&wc) == 0)
        return false;

    // create the window:
    g_hWnd = CreateWindow(
        WINDOW_TITLE,                                             // class name
        WINDOW_TITLE,                                             // title
        WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, // style
        CW_USEDEFAULT, CW_USEDEFAULT,                             // position
        CW_USEDEFAULT, CW_USEDEFAULT,                             // size
        NULL,                                                     // no parent
        NULL,                                                     // no menu
        g_hInstance,                                              // instance
        NULL                                                      // no special
    );

    if (g_hWnd == NULL)
        return false;

    // setup double buffering:
    g_hDC = GetDC(g_hWnd);
    if (g_hDC == NULL)
        return false;

    g_hMemDC = CreateCompatibleDC(g_hDC);
    if (g_hMemDC == NULL)
        return false;

    g_hMemBMP = CreateCompatibleBitmap(g_hDC, WINDOW_WIDTH, WINDOW_HEIGHT);
    if (g_hMemBMP == NULL)
        return false;

    SelectObject(g_hMemDC, g_hMemBMP);

    // color used to draw the background:
    g_hBlue = CreateSolidBrush(RGB(100, 149, 237));
    if (g_hBlue == NULL)
        return FALSE;

    // setup octocat:
    octocat_hdc = CreateCompatibleDC(g_hDC);
    if (octocat_hdc == NULL)
        return FALSE;

    octocat_bmp = CreateCompatibleBitmap(g_hDC, octocat_w, octocat_h);
    if (octocat_bmp == NULL)
        return FALSE;

    SelectObject(octocat_hdc, octocat_bmp);
    SetDIBits(octocat_hdc, octocat_bmp, 0, 320, octocat, &sprbmi, DIB_RGB_COLORS);

    return true;
}
Exemplo n.º 7
0
int _tmain(int argc, _TCHAR* argv[])
{
	if( argc < 2 )
	{
		_tprintf(_T("converts a picture to a tank map\n"));
		_tprintf(_T("supported formats: bmp, gif, jpg, wmf, ico\n"));
		_tprintf(_T("using: mkmap bmpfile.bmp [mapfile]\n"));
		return 0;
	}

	_tprintf(_T("input file: \n  %s\n"), argv[1]);


	IPicture *pPicture = LoadPicture(argv[1]);

	if( NULL == pPicture )
	{
		_tprintf(_T("Loading FAILED!\n"));
		return -1;
	}


	HDC hdc = GetDC(NULL);


	long height, width;
	pPicture->get_Height(&height);
	pPicture->get_Width(&width);

    long height_ = MulDiv(height, GetDeviceCaps(hdc, LOGPIXELSY), HIMETRIC_INCH);
    long width_  = MulDiv(width,  GetDeviceCaps(hdc, LOGPIXELSX), HIMETRIC_INCH);


	_tprintf(_T("width  %d px\n"), width_);
	_tprintf(_T("height %d px\n"), height_);


	HDC hdc_tmp = CreateCompatibleDC(hdc);
	HBITMAP bmp = CreateCompatibleBitmap(hdc, width_, height_);

	ReleaseDC(NULL, hdc);


	HBITMAP old = (HBITMAP) SelectObject(hdc_tmp, bmp);

	pPicture->Render(hdc_tmp, 0, 0, width_, height_, 0, height, width, -height, NULL);
    

	_TCHAR outfn[MAX_PATH];
	if( argc > 2 )
		_tcscpy(outfn, argv[2]);
	else
		_stprintf(outfn, _T("%s.tankmap"), argv[1]);

    FILE *file = _tfopen(outfn, _T("wt"));
	if( NULL != file )
	{
		_tprintf(_T("writing map to '%s'\n"), outfn);
		try 
		{
			fwassert(_ftprintf(file, _T("<tank map>\n")));
			fwassert(_ftprintf(file, _T("width %d\n"), width_));
			fwassert(_ftprintf(file, _T("height %d\n"), height_));

			_TCHAR name[MAX_OBJNAME];

			int objcount = 0;
			for( int y = 0; y < height_; y++ )
			for( int x = 0; x < width_; x++ )
			{
				if( ObjectFromColor(name, GetPixel(hdc_tmp, x, y)) )
				{
					fwassert(_ftprintf(file, _T("%s %d %d\n"), name, 16 + x * 32, 16 + y * 32));
					objcount++;
				}
			}

			_tprintf(_T("%d objects written\n"), objcount);
			_tprintf(_T("done.\n"), objcount);
		}
		catch(const _TCHAR *msg)
		{
			fclose(file);
			_tprintf(msg);
		}
	}
	else
	{
		_tprintf(_T("can't open file '%s' for writing\n"), outfn);
	}


	SelectObject(hdc_tmp, old);
	DeleteObject(bmp);
	DeleteDC(hdc_tmp);

	SAFE_RELEASE(pPicture);

	return 0;
}
Exemplo n.º 8
0
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_CREATE:
		break;
	case WM_PAINT:

		hdc = BeginPaint(hWnd, &ps);

		{
			RECT cr;
			GetClientRect(hWnd, &cr);

			int width = cr.right - cr.left;
			int height = cr.bottom - cr.top;

			HDC bufDC;
			HBITMAP bufBMP;

			bufDC = CreateCompatibleDC(hdc);
			bufBMP = CreateCompatibleBitmap(hdc, width, height);
			SelectObject(bufDC, bufBMP);

			setPaintDC(bufDC);

			RECT r = {0};
			r.right = width;
			r.bottom = height;

			FillRect(bufDC, &r, GetStockBrush(WHITE_BRUSH));

			paint();

			setPaintDC(NULL);

			BitBlt(hdc, 0, 0, width, height, bufDC, 0, 0, SRCCOPY);

			DeleteObject(bufBMP);
			DeleteDC(bufDC);
		}

		EndPaint(hWnd, &ps);
		break;
	
	case WM_MOUSEMOVE:
		{
			int x = GET_X_LPARAM(lParam); 
			int y = GET_Y_LPARAM(lParam);

			mouseMove(x, y);
		}
	break;
	
	case WM_LBUTTONDOWN:
		SetCapture(hWnd);
		mouseDown();
	break;

	case WM_LBUTTONUP:
		ReleaseCapture();
		mouseUp();
	break;

	case WM_KEYDOWN:
		{
			int vk = wParam;
			char ch = MapVirtualKey(vk, MAPVK_VK_TO_CHAR);

			keyDown(ch, vk);
		}

		break;
	
	case WM_KEYUP:
		{
			int vk = wParam;
			char ch = MapVirtualKey(vk, MAPVK_VK_TO_CHAR);

			keyUp(ch, vk);
		}

		break;

	case WM_TIMER:
		switch(wParam)
		{
		case IDT_TIMER0:
			timerTick();
			break;
		}
		
		break;

	case WM_DESTROY:
		finalize();

		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Exemplo n.º 9
0
void __cdecl InitGui(void *param)
{
  HWND hparentwnd;
  HANDLE hinst;
  WNDCLASSEX wndclass;
  char szFile[80];

  hinst = GetModuleHandle(NULL);
  GetModuleFileName (hinst, szFile, sizeof(szFile));
#ifdef DEBUG
  printf ("hinst = %x\n", hinst);
  printf ("File = %s\n", szFile);
#endif
  /* Fill in window class structure with parameters that describe
     the main window. */
  /* CS_OWNDC : un DC pour chaque fenêtre de la classe */
  wndclass.cbSize        = sizeof(wndclass);
  wndclass.style         = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
  wndclass.lpfnWndProc   = (WNDPROC)WndProc;
  wndclass.cbClsExtra    = 0;
  wndclass.cbWndExtra    = 0;
  wndclass.hInstance     = hinst;
  wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION);
  wndclass.hIconSm       = LoadIcon (NULL, IDI_APPLICATION);
  wndclass.hCursor       = LoadCursor(NULL, IDC_ARROW);
  wndclass.hbrBackground = GetStockObject(WHITE_BRUSH);
  wndclass.lpszClassName = szFile;
  wndclass.lpszMenuName  = NULL;

  if (!RegisterClassEx(&wndclass))
    Win32Error("Register class");

  hparentwnd = GetFocus();
  my_window = CreateWindow(szFile, szTitle, 
			   WS_OVERLAPPEDWINDOW | WS_HSCROLL | WS_VSCROLL,
			   CW_USEDEFAULT, 0, 
			   CW_USEDEFAULT, 0,
			   /* screenwidth, screendepth, */
			   hparentwnd, NULL, hinst, NULL);
  if (!my_window) {
    Win32Error("Create window");
  }
#ifdef DEBUG
  fprintf(stderr, "my_window = %x\n", my_window);
#endif
  
#ifdef LOOPMSG
  /* Acknowledge for UpdateWindow() (WM_PAINT message generated) */
  hMutex = CreateMutex(NULL, FALSE, "DrawingMutex");
  my_dc = GetDC(my_window);
  /* Device context for drawing and the associated bitmap. */
  drawing_dc = CreateCompatibleDC(my_dc);
  hbm = CreateCompatibleBitmap(my_dc, screenwidth, screendepth);
  SelectObject(drawing_dc, hbm);
  /* Blank the bitmap */
  SelectObject(drawing_dc, GetStockObject(WHITE_BRUSH));
  PatBlt(drawing_dc, 0, 0, screenwidth, screendepth, PATCOPY);
  hAccelTable = LoadAccelerators (hinst, szTitle);

  ShowWindow(my_window, SW_SHOWNORMAL);
  UpdateWindow(my_window);

  /* Running the message loop */
  while (GetMessage(&msg, my_window, 0, 0)) {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
  }

#else
  drawing_dc = my_dc = GetDC(my_window);
#endif
}
//
//  FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	static int x1 = 0;
	static int y1 = 0;
	static int x2 = 0;
	static int y2 = 0;
	static vector<mLine> lList;

	static HBITMAP currentBitmap = NULL;
	static bool isCopy = false;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDM_ABOUT:
			//isCopy = !isCopy;
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		case ID_DRAW:
		{
			isCopy = false;
			HMENU men = GetMenu(hWnd);
			EnableMenuItem(men, ID_COPY, MF_BYCOMMAND | MF_ENABLED);
			EnableMenuItem(men, ID_DRAW, MF_BYCOMMAND | MF_GRAYED);
			break;
		}
			
		case ID_COPY:
		{
			HMENU men = GetMenu(hWnd);
			EnableMenuItem(men, ID_COPY, MF_BYCOMMAND | MF_GRAYED);
			EnableMenuItem(men, ID_DRAW, MF_BYCOMMAND | MF_ENABLED);
			isCopy = true;
			break;
		}
			
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_CREATE:
	{
		HMENU men = GetMenu(hWnd);
		EnableMenuItem(men, ID_COPY, MF_BYCOMMAND | MF_ENABLED);
		EnableMenuItem(men, ID_DRAW, MF_BYCOMMAND | MF_GRAYED);
		break;
	}
	case WM_RENDERFORMAT:
	{
		onRenderFormat(hWnd, wParam, currentBitmap);
		break;
	}
	case WM_RENDERALLFORMATS:
	{
		onRenderAllFormat(hWnd, wParam, currentBitmap);
		break;
	}
	case WM_DESTROYCLIPBOARD:
	{
		if (currentBitmap != NULL)
		{
			DeleteObject(currentBitmap);
			currentBitmap = NULL;
		}
		break;
	}
	case WM_LBUTTONDOWN:
	{
		x1 = x2 = GET_X_LPARAM(lParam);
		y1 = y2 = GET_Y_LPARAM(lParam);
		
		break;
	}

	case WM_LBUTTONUP:
	{

		if (isCopy)
		{
			
			hdc = GetDC(hWnd);
			HDC memDC = CreateCompatibleDC(hdc);
			SetROP2(hdc, R2_NOTXORPEN);
			Rectangle(hdc, min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2));
			//
			if (x1 > x2)
				std::swap(x1, x2);
			if (y1 > y2)
				std::swap(y1, y2);
			//
			
			if (currentBitmap != NULL)
				DeleteObject(currentBitmap);
			
			
			HBITMAP temp = (HBITMAP)SelectObject(memDC, CreateCompatibleBitmap(hdc, x2 - x1, y2 - y1));

			BitBlt(memDC, 0, 0, x2 - x1, y2 - y1, hdc, x1, y1, SRCCOPY);
			
			temp = (HBITMAP) SelectObject(memDC, temp);
			
			DeleteDC(memDC);
			ReleaseDC(hWnd, hdc);

			//int gg = sizeof(BITMAP);
			if (temp != NULL)
			{
				
				OpenClipboard(hWnd);
				EmptyClipboard();
				

				SetClipboardData(CF_BITMAP, NULL);
				CloseClipboard();
				
				currentBitmap = temp;
				MessageBox(hWnd, L"The Image has been copied to clipboard.", L"Copy Successfully", MB_OK);
			}
			else
			{
				MessageBox(hWnd, L"Cannot copy image to clipboard.", L"Error", MB_OK);
			}
			x1 = x2;
			y1 = y2;
		}
		else
		{
			
			

		}
		break;
	}
	case WM_MOUSEMOVE:
	{ 
		if (wParam & VK_LBUTTON)
		{
			int nx, ny;
			nx = GET_X_LPARAM(lParam);
			ny = GET_Y_LPARAM(lParam);
			hdc = GetDC(hWnd);


			if (isCopy)
			{
				hdc = GetDC(hWnd);

				SetROP2(hdc, R2_NOTXORPEN);
				Rectangle(hdc, min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2));

				Rectangle(hdc, min(x1, nx), min(y1, ny), max(x1, nx), max(y1, ny));
				ReleaseDC(hWnd, hdc);
			}
			else
			{
				
				mLine l;
				
				l.setPos(x1, y1, nx, ny);
				x1 = nx;
				y1 = ny;
				lList.push_back(l);
				InvalidateRect(hWnd, 0, TRUE);
				UpdateWindow(hWnd);
			}
			x2 = nx;
			y2 = ny;
			ReleaseDC(hWnd, hdc);
		}
		
		break;
	}
	case WM_PAINT:
		hdc = BeginPaint(hWnd, &ps);
		// TODO: Add any drawing code here...
		for (int i = 0; i < lList.size(); ++i)
			lList[i].Draw(hdc, NULL);
		EndPaint(hWnd, &ps);
		break;
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Exemplo n.º 11
0
static void drawbmp(fz_context *ctx, fz_document *doc, fz_page *page, fz_display_list *list, int pagenum, fz_cookie *cookie)
{
	float zoom;
	fz_matrix ctm;
	fz_irect ibounds;
	fz_rect bounds, tbounds;

	int w, h;
	fz_device *dev;
	HDC dc, dc_main;
	RECT rc;
	HBRUSH bg_brush;
	HBITMAP hbmp;
	BITMAPINFO bmi = { 0 };
	int bmp_data_len;
	unsigned char *bmp_data;

	fz_bound_page(doc, page, &bounds);
	zoom = resolution / 72;
	fz_pre_scale(fz_rotate(&ctm, rotation), zoom, zoom);
	tbounds = bounds;
	fz_round_rect(&ibounds, fz_transform_rect(&tbounds, &ctm));

	w = width;
	h = height;
	if (res_specified)
	{
		fz_round_rect(&ibounds, &tbounds);
		if (w && ibounds.x1 - ibounds.x0 <= w)
			w = 0;
		if (h && ibounds.y1 - ibounds.y0 <= h)
			h = 0;
	}
	if (w || h)
	{
		float scalex = w / (tbounds.x1 - tbounds.x0);
		float scaley = h / (tbounds.y1 - tbounds.y0);
		fz_matrix scale_mat;
		if (w == 0)
			scalex = fit ? 1.0f : scaley;
		if (h == 0)
			scaley = fit ? 1.0f : scalex;
		if (!fit)
			scalex = scaley = min(scalex, scaley);
		fz_concat(&ctm, &ctm, fz_scale(&scale_mat, scalex, scaley));
		tbounds = bounds;
		fz_transform_rect(&tbounds, &ctm);
	}
	fz_round_rect(&ibounds, &tbounds);
	fz_rect_from_irect(&tbounds, &ibounds);

	w = ibounds.x1 - ibounds.x0;
	h = ibounds.y1 - ibounds.y0;

	dc_main = GetDC(NULL);
	hbmp = CreateCompatibleBitmap(dc_main, w, h);
	if (!hbmp)
		fz_throw(ctx, FZ_ERROR_GENERIC, "failed to create a %d x %d bitmap for page %d", w, h, pagenum);
	dc = CreateCompatibleDC(dc_main);
	DeleteObject(SelectObject(dc, hbmp));

	SetRect(&rc, 0, 0, w, h);
	bg_brush = CreateSolidBrush(RGB(0xFF,0xFF,0xFF));
	FillRect(dc, &rc, bg_brush);
	DeleteObject(bg_brush);

	dev = fz_new_gdiplus_device(ctx, dc, &tbounds);
	if (list)
		fz_run_display_list(list, dev, &ctm, &tbounds, cookie);
	else
		fz_run_page(doc, page, dev, &ctm, cookie);
	fz_free_device(dev);

	bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
	bmi.bmiHeader.biWidth = w;
	bmi.bmiHeader.biHeight = output_format == OUT_TGA ? -h : h;
	bmi.bmiHeader.biPlanes = 1;
	bmi.bmiHeader.biBitCount = output_format == OUT_TGA ? 32 : 24;
	bmi.bmiHeader.biCompression = BI_RGB;

	bmp_data_len = output_format == OUT_TGA ? w * h * 4 : ((w * 3 + 3) / 4) * 4 * h;
	bmp_data = fz_malloc(ctx, bmp_data_len);
	if (!GetDIBits(dc, hbmp, 0, h, bmp_data, &bmi, DIB_RGB_COLORS))
		fz_throw(ctx, FZ_ERROR_GENERIC, "cannot draw page %d", pagenum, filename);

	DeleteDC(dc);
	ReleaseDC(NULL, dc_main);
	DeleteObject(hbmp);

	if (output)
	{
		char buf[512];
		FILE *f;

		sprintf(buf, output, pagenum);
		f = fopen(buf, "wb");
		if (!f)
			fz_throw(ctx, FZ_ERROR_GENERIC, "could not create raster file '%s'", buf);

		if (output_format == OUT_TGA)
		{
			fz_pixmap *pix = fz_new_pixmap_with_data(ctx, fz_device_bgr(ctx), w, h, bmp_data);
			fz_write_tga(ctx, pix, buf, 0);
			fz_drop_pixmap(ctx, pix);
		}
		else
		{
			BITMAPFILEHEADER bmpfh = { 0 };
			static const int one = 1;
			if (!*(char *)&one)
				fz_throw(ctx, FZ_ERROR_GENERIC, "rendering to BMP is not supported on big-endian architectures");

			bmpfh.bfType = MAKEWORD('B', 'M');
			bmpfh.bfOffBits = sizeof(bmpfh) + sizeof(bmi);
			bmpfh.bfSize = bmpfh.bfOffBits + bmp_data_len;

			fwrite(&bmpfh, sizeof(bmpfh), 1, f);
			fwrite(&bmi, sizeof(bmi), 1, f);
			fwrite(bmp_data, 1, bmp_data_len, f);
		}

		fclose(f);
	}

	if (showmd5)
	{
		fz_pixmap *pix = fz_new_pixmap_with_data(ctx, fz_device_bgr(ctx), bmp_data_len / 4 / h, h, bmp_data);
		unsigned char digest[16];
		int i;

		fz_md5_pixmap(pix, digest);
		printf(" ");
		for (i = 0; i < 16; i++)
			printf("%02x", digest[i]);

		fz_drop_pixmap(ctx, pix);
	}

	fz_free(ctx, bmp_data);
}
Exemplo n.º 12
0
static SDL_bool
WIN_GetDisplayMode(_THIS, LPCTSTR deviceName, DWORD index, SDL_DisplayMode * mode)
{
    SDL_VideoData *vid_data = (SDL_VideoData *) _this->driverdata;
    SDL_DisplayModeData *data;
    DEVMODE devmode;
    HDC hdc;

    devmode.dmSize = sizeof(devmode);
    devmode.dmDriverExtra = 0;
    if (!EnumDisplaySettings(deviceName, index, &devmode)) {
        return SDL_FALSE;
    }

    data = (SDL_DisplayModeData *) SDL_malloc(sizeof(*data));
    if (!data) {
        return SDL_FALSE;
    }
    data->DeviceMode = devmode;
    data->DeviceMode.dmFields =
        (DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY |
         DM_DISPLAYFLAGS);
    data->ScaleX = 1.0f;
    data->ScaleY = 1.0f;
    data->DiagDPI = 0.0f;
    data->HorzDPI = 0.0f;
    data->VertDPI = 0.0f;

    /* Fill in the mode information */
    mode->format = SDL_PIXELFORMAT_UNKNOWN;
    mode->w = devmode.dmPelsWidth;
    mode->h = devmode.dmPelsHeight;
    mode->refresh_rate = devmode.dmDisplayFrequency;
    mode->driverdata = data;

    if (index == ENUM_CURRENT_SETTINGS
        && (hdc = CreateDC(deviceName, NULL, NULL, NULL)) != NULL) {
        char bmi_data[sizeof(BITMAPINFOHEADER) + 256 * sizeof(RGBQUAD)];
        LPBITMAPINFO bmi;
        HBITMAP hbm;

#if 0
        int logical_width = GetDeviceCaps( hdc, HORZRES );
        int logical_height = GetDeviceCaps( hdc, VERTRES );

        data->ScaleX = (float)logical_width / devmode.dmPelsWidth;
        data->ScaleY = (float)logical_height / devmode.dmPelsHeight;
        mode->w = logical_width;
        mode->h = logical_height;
#endif
        
        // WIN_GetMonitorDPI needs mode->w and mode->h
        // so only call after those are set.
        if (vid_data->GetDpiForMonitor) {
            WIN_GetMonitorDPIData dpi_data;
            RECT monitor_rect;

            dpi_data.vid_data = vid_data;
            dpi_data.mode = mode;
            dpi_data.mode_data = data;
            monitor_rect.left = devmode.dmPosition.x;
            monitor_rect.top = devmode.dmPosition.y;
            monitor_rect.right = monitor_rect.left + 1;
            monitor_rect.bottom = monitor_rect.top + 1;
            EnumDisplayMonitors(NULL, &monitor_rect, WIN_GetMonitorDPI, (LPARAM)&dpi_data);
        } else {
            // We don't have the Windows 8.1 routine so just
            // get system DPI.
            data->HorzDPI = (float)GetDeviceCaps( hdc, LOGPIXELSX );
            data->VertDPI = (float)GetDeviceCaps( hdc, LOGPIXELSY );
            if (data->HorzDPI == data->VertDPI) {
                data->DiagDPI = data->HorzDPI;
            } else {
                data->DiagDPI = SDL_ComputeDiagonalDPI( mode->w,
                                                        mode->h,
                                                        (float)GetDeviceCaps( hdc, HORZSIZE ) / 25.4f,
                                                        (float)GetDeviceCaps( hdc, VERTSIZE ) / 25.4f );
            }
        }
        
        SDL_zero(bmi_data);
        bmi = (LPBITMAPINFO) bmi_data;
        bmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);

        hbm = CreateCompatibleBitmap(hdc, 1, 1);
        GetDIBits(hdc, hbm, 0, 1, NULL, bmi, DIB_RGB_COLORS);
        GetDIBits(hdc, hbm, 0, 1, NULL, bmi, DIB_RGB_COLORS);
        DeleteObject(hbm);
        DeleteDC(hdc);
        if (bmi->bmiHeader.biCompression == BI_BITFIELDS) {
            switch (*(Uint32 *) bmi->bmiColors) {
            case 0x00FF0000:
                mode->format = SDL_PIXELFORMAT_RGB888;
                break;
            case 0x000000FF:
                mode->format = SDL_PIXELFORMAT_BGR888;
                break;
            case 0xF800:
                mode->format = SDL_PIXELFORMAT_RGB565;
                break;
            case 0x7C00:
                mode->format = SDL_PIXELFORMAT_RGB555;
                break;
            }
        } else if (bmi->bmiHeader.biBitCount == 8) {
            mode->format = SDL_PIXELFORMAT_INDEX8;
        } else if (bmi->bmiHeader.biBitCount == 4) {
            mode->format = SDL_PIXELFORMAT_INDEX4LSB;
        }
    } else {
        /* FIXME: Can we tell what this will be? */
        if ((devmode.dmFields & DM_BITSPERPEL) == DM_BITSPERPEL) {
            switch (devmode.dmBitsPerPel) {
            case 32:
                mode->format = SDL_PIXELFORMAT_RGB888;
                break;
            case 24:
                mode->format = SDL_PIXELFORMAT_RGB24;
                break;
            case 16:
                mode->format = SDL_PIXELFORMAT_RGB565;
                break;
            case 15:
                mode->format = SDL_PIXELFORMAT_RGB555;
                break;
            case 8:
                mode->format = SDL_PIXELFORMAT_INDEX8;
                break;
            case 4:
                mode->format = SDL_PIXELFORMAT_INDEX4LSB;
                break;
            }
        }
    }
    return SDL_TRUE;
}
Exemplo n.º 13
0
void CtrlMemView::onPaint(WPARAM wParam, LPARAM lParam)
{
	// draw to a bitmap for double buffering
	PAINTSTRUCT ps;	
	HDC actualHdc = BeginPaint(wnd, &ps);
	HDC hdc = CreateCompatibleDC(actualHdc);
	HBITMAP hBM = CreateCompatibleBitmap(actualHdc, rect.right-rect.left, rect.bottom-rect.top);
	SelectObject(hdc, hBM);

	SetBkMode(hdc,OPAQUE);
	HPEN standardPen = CreatePen(0,0,0xFFFFFF);
	HBRUSH standardBrush = CreateSolidBrush(0xFFFFFF);

	HPEN oldPen = (HPEN) SelectObject(hdc,standardPen);
	HBRUSH oldBrush = (HBRUSH) SelectObject(hdc,standardBrush);
   	HFONT oldFont = (HFONT) SelectObject(hdc,(HGDIOBJ)font);

	// white background
	SelectObject(hdc,standardPen);
	SelectObject(hdc,standardBrush);
	Rectangle(hdc,0,0,rect.right,rect.bottom);

	// draw one extra row that may be partially visible
	for (int i = 0; i < visibleRows+1; i++)
	{
		char temp[32];

		unsigned int address=windowStart + i*rowSize;
		int rowY = rowHeight*i;
		
		sprintf(temp,"%08X",address);
		SetTextColor(hdc,0x600000);
		TextOutA(hdc,addressStart,rowY,temp,(int)strlen(temp));

		SetTextColor(hdc,0x000000);

		u32 memory[4];
		bool valid = debugger != NULL && debugger->isAlive() && Memory::IsValidAddress(address);
		if (valid)
		{
			memory[0] = debugger->readMemory(address);
			memory[1] = debugger->readMemory(address+4);
			memory[2] = debugger->readMemory(address+8);
			memory[3] = debugger->readMemory(address+12);
		}

		u8* m = (u8*) memory;
		for (int j = 0; j < rowSize; j++)
		{
			if (valid) sprintf(temp,"%02X",m[j]);
			else strcpy(temp,"??");

			unsigned char c = m[j];
			if (c < 32 || c >= 128 || valid == false) c = '.';

			if (address+j == curAddress && searching == false)
			{
				COLORREF oldBkColor = GetBkColor(hdc);
				COLORREF oldTextColor = GetTextColor(hdc);

				if (hasFocus && !asciiSelected)
				{
					SetTextColor(hdc,0xFFFFFF);
					SetBkColor(hdc,0xFF9933);
					if (selectedNibble == 0) SelectObject(hdc,(HGDIOBJ)underlineFont);
				} else {
					SetTextColor(hdc,0);
					SetBkColor(hdc,0xC0C0C0);
				}
				TextOutA(hdc,hexStart+j*3*charWidth,rowY,&temp[0],1);
							
				if (hasFocus && !asciiSelected)
				{
					if (selectedNibble == 1) SelectObject(hdc,(HGDIOBJ)underlineFont);
					else SelectObject(hdc,(HGDIOBJ)font);
				}
				TextOutA(hdc,hexStart+j*3*charWidth+charWidth,rowY,&temp[1],1);

				if (hasFocus && asciiSelected)
				{
					SetTextColor(hdc,0xFFFFFF);
					SetBkColor(hdc,0xFF9933);
				} else {
					SetTextColor(hdc,0);
					SetBkColor(hdc,0xC0C0C0);
					SelectObject(hdc,(HGDIOBJ)font);
				}
				TextOutA(hdc,asciiStart+j*(charWidth+2),rowY,(char*)&c,1);

				SetTextColor(hdc,oldTextColor);
				SetBkColor(hdc,oldBkColor);
			} else {
				TextOutA(hdc,hexStart+j*3*charWidth,rowY,temp,2);
				TextOutA(hdc,asciiStart+j*(charWidth+2),rowY,(char*)&c,1);
			}
		}
	}

	SelectObject(hdc,oldFont);
	SelectObject(hdc,oldPen);
	SelectObject(hdc,oldBrush);
	
	// copy bitmap to the actual hdc
	BitBlt(actualHdc,0,0,rect.right,rect.bottom,hdc,0,0,SRCCOPY);
	DeleteObject(hBM);
	DeleteDC(hdc);

	DeleteObject(standardPen);
	DeleteObject(standardBrush);
	
	EndPaint(wnd, &ps);
}
Exemplo n.º 14
0
HBITMAP Explorerplusplus::CaptureTabScreenshot(int iTabId)
{
	HDC hdc;
	HDC hdcSrc;
	HBITMAP hBitmap;
	HBITMAP hPrevBitmap;
	Gdiplus::Color color(0,0,0);
	RECT rcMain;
	RECT rcTab;

	HWND hTab = m_hListView[iTabId];

	GetClientRect(m_hContainer,&rcMain);
	GetClientRect(hTab,&rcTab);

	/* Main window BitBlt. */
	hdc = GetDC(m_hContainer);
	hdcSrc = CreateCompatibleDC(hdc);

	/* Any bitmap sent back to the operating system will need to be in 32-bit
	ARGB format. */
	Gdiplus::Bitmap bi(GetRectWidth(&rcMain),GetRectHeight(&rcMain),PixelFormat32bppARGB);
	bi.GetHBITMAP(color,&hBitmap);

	/* BitBlt the main window into the bitmap. */
	hPrevBitmap = (HBITMAP)SelectObject(hdcSrc,hBitmap);
	BitBlt(hdcSrc,0,0,GetRectWidth(&rcMain),GetRectHeight(&rcMain),hdc,0,0,SRCCOPY);


	/* Now BitBlt the tab onto the main window. */
	HDC hdcTab;
	HDC hdcTabSrc;
	HBITMAP hbmTab;
	HBITMAP hbmTabPrev;
	BOOL bVisible;

	hdcTab = GetDC(hTab);
	hdcTabSrc = CreateCompatibleDC(hdcTab);
	hbmTab = CreateCompatibleBitmap(hdcTab,GetRectWidth(&rcTab),GetRectHeight(&rcTab));

	hbmTabPrev = (HBITMAP)SelectObject(hdcTabSrc,hbmTab);

	bVisible = IsWindowVisible(hTab);

	if(!bVisible)
	{
		ShowWindow(hTab,SW_SHOW);
	}

	PrintWindow(hTab,hdcTabSrc,PW_CLIENTONLY);

	if(!bVisible)
	{
		ShowWindow(hTab,SW_HIDE);
	}

	MapWindowPoints(hTab,m_hContainer,(LPPOINT)&rcTab,2);
	BitBlt(hdcSrc,rcTab.left,rcTab.top,GetRectWidth(&rcTab),GetRectHeight(&rcTab),hdcTabSrc,0,0,SRCCOPY);

	SelectObject(hdcTabSrc,hbmTabPrev);
	DeleteObject(hbmTab);
	DeleteDC(hdcTabSrc);
	ReleaseDC(hTab,hdcTab);


	/* Shrink the bitmap. */
	HDC hdcThumbnailSrc;
	HBITMAP hbmThumbnail;
	POINT pt;

	hdcThumbnailSrc = CreateCompatibleDC(hdc);

	/* Thumbnail bitmap. */
	Gdiplus::Bitmap bmpThumbnail(GetRectWidth(&rcMain),GetRectHeight(&rcMain),PixelFormat32bppARGB);

	bmpThumbnail.GetHBITMAP(color,&hbmThumbnail);

	hPrevBitmap = (HBITMAP)SelectObject(hdcThumbnailSrc,hbmThumbnail);

	/* Finally, shrink the full-scale bitmap down into a thumbnail. */
	SetStretchBltMode(hdcThumbnailSrc,HALFTONE);
	SetBrushOrgEx(hdcThumbnailSrc,0,0,&pt);
	BitBlt(hdcThumbnailSrc,0,0,GetRectWidth(&rcMain),GetRectHeight(&rcMain),hdcSrc,0,0,SRCCOPY);

	SetBitmapDimensionEx(hbmThumbnail,GetRectWidth(&rcMain),GetRectHeight(&rcMain),NULL);

	SelectObject(hdcThumbnailSrc,hPrevBitmap);
	DeleteDC(hdcThumbnailSrc);

	DeleteObject(hBitmap);

	SelectObject(hdcSrc,hPrevBitmap);

	DeleteDC(hdcSrc);
	ReleaseDC(m_hContainer,hdc);

	return hbmThumbnail;
}
Exemplo n.º 15
0
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
  HWND hwndParent = hWndParent;
  HWND hwndImage = hWndImage;

  if (hwnd == hwndParent) {
    if (message == WM_SIZE) {
      ShowWindow(hwndImage, wParam == SIZE_MINIMIZED ? SW_HIDE : SW_SHOW);
    }
    if (message == WM_WINDOWPOSCHANGED) {
      SetWindowPos(hwndImage, hwndParent, 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE);
    }
    return CallWindowProc(
      (long (__stdcall *)(HWND,unsigned int,unsigned int,long))oldProc,
      hwnd,
      message,
      wParam,
      lParam
    );
  }
  switch (message) {
    case WM_PAINT:
    if (bgBitmap.bReady) {
      ECS();

      PAINTSTRUCT ps;
      HDC hdc = BeginPaint(hwnd, &ps);

      if (bgBitmap.iType == MIL_BITMAP) {
        HDC cdc = CreateCompatibleDC(hdc);
        SelectObject(cdc, bgBitmap.hBitmap);
        for (unsigned int x = 0; x < uWndWidth; x += bgBitmap.rPos.right) {
          for (unsigned int y = 0; y < uWndHeight; y += bgBitmap.rPos.bottom) {
            BitBlt(hdc, x, y, bgBitmap.rPos.right, bgBitmap.rPos.bottom, cdc, 0, 0, SRCCOPY);
          }
        }
        DeleteDC(cdc);
      }
      else {
        int r = GetRValue(bgBitmap.cGradientFrom) << 10;
        int g = GetGValue(bgBitmap.cGradientFrom) << 10;
        int b = GetBValue(bgBitmap.cGradientFrom) << 10;
        int dr = ((GetRValue(bgBitmap.cGradientTo) << 10) - r) / (int)uWndHeight * 4;
        int dg = ((GetGValue(bgBitmap.cGradientTo) << 10) - g) / (int)uWndHeight * 4;
        int db = ((GetBValue(bgBitmap.cGradientTo) << 10) - b) / (int)uWndHeight * 4;
        RECT rect;
        rect.left = 0;
        rect.top = 0;
        rect.right = uWndWidth;
        rect.bottom = 4;
        while (rect.top < (int)uWndHeight)
        {
          HBRUSH brush = CreateSolidBrush(RGB(r>>10,g>>10,b>>10));
          FillRect(hdc, &rect, brush);
          DeleteObject(brush);
          rect.top+=4;
          rect.bottom+=4;
          r+=dr;
          g+=dg;
          b+=db;
        }
      }

      myImageList *img = bgBitmap.next;
      while (img) {
        if (img->iType == MIL_TEXT) {
          SetBkMode(hdc, TRANSPARENT);

          SetTextColor(hdc, img->cTextColor);
          SelectObject(hdc, img->hFont);
          DrawText(hdc, img->szText, -1, &img->rPos, DT_TOP | DT_LEFT | DT_NOPREFIX | DT_WORDBREAK);
        }
        else if (img->iType == MIL_BITMAP) {
          HDC cdc = CreateCompatibleDC(hdc);
          SelectObject(cdc, img->hBitmap);
          BitBlt(hdc, img->rPos.left, img->rPos.top, img->rPos.right - img->rPos.left, img->rPos.bottom - img->rPos.top, cdc, 0, 0, SRCCOPY);
          DeleteDC(cdc);
        }
        else {
          COLORREF   cColor;
          HBITMAP    bmAndBack, bmAndObject, bmAndMem, bmSave;
          HBITMAP    bmBackOld, bmObjectOld, bmMemOld, bmSaveOld;
          HDC        hdcMem, hdcBack, hdcObject, hdcTemp, hdcSave;
          POINT      ptSize;

          HBITMAP hBitmap = img->hBitmap;

          hdcTemp = CreateCompatibleDC(hdc);
          SelectObject(hdcTemp, hBitmap);   // Select the bitmap

          ptSize.x = img->rPos.right - img->rPos.left;
          ptSize.y = img->rPos.bottom - img->rPos.top;
          DPtoLP(hdcTemp, &ptSize, 1);  // Convert from device to logical points

          // Create some DCs to hold temporary data.
          hdcBack   = CreateCompatibleDC(hdc);
          hdcObject = CreateCompatibleDC(hdc);
          hdcMem    = CreateCompatibleDC(hdc);
          hdcSave   = CreateCompatibleDC(hdc);

          // Create a bitmap for each DC. DCs are required for a number of
          // GDI functions.

          // Monochrome DC
          bmAndBack   = CreateBitmap(ptSize.x, ptSize.y, 1, 1, NULL);

          // Monochrome DC
          bmAndObject = CreateBitmap(ptSize.x, ptSize.y, 1, 1, NULL);

          bmAndMem    = CreateCompatibleBitmap(hdc, ptSize.x, ptSize.y);
          bmSave      = CreateCompatibleBitmap(hdc, ptSize.x, ptSize.y);

          // Each DC must select a bitmap object to store pixel data.
          bmBackOld   = (HBITMAP)SelectObject(hdcBack, bmAndBack);
          bmObjectOld = (HBITMAP)SelectObject(hdcObject, bmAndObject);
          bmMemOld    = (HBITMAP)SelectObject(hdcMem, bmAndMem);
          bmSaveOld   = (HBITMAP)SelectObject(hdcSave, bmSave);

          // Set proper mapping mode.
          SetMapMode(hdcTemp, GetMapMode(hdc));

          // Save the bitmap sent here, because it will be overwritten.
          BitBlt(hdcSave, 0, 0, ptSize.x, ptSize.y, hdcTemp, 0, 0, SRCCOPY);

          // Set the background color of the source DC to the color.
          // contained in the parts of the bitmap that should be transparent
          cColor = SetBkColor(hdcTemp, img->cTransparent);

          // Create the object mask for the bitmap by performing a BitBlt
          // from the source bitmap to a monochrome bitmap.
          BitBlt(hdcObject, 0, 0, ptSize.x, ptSize.y, hdcTemp, 0, 0,
              SRCCOPY);

          // Set the background color of the source DC back to the original
          // color.
          SetBkColor(hdcTemp, cColor);

          // Create the inverse of the object mask.
          BitBlt(hdcBack, 0, 0, ptSize.x, ptSize.y, hdcObject, 0, 0,
              NOTSRCCOPY);

          // Copy the background of the main DC to the destination.
          BitBlt(hdcMem, 0, 0, ptSize.x, ptSize.y, hdc, img->rPos.left, img->rPos.top,
              SRCCOPY);

          // Mask out the places where the bitmap will be placed.
          BitBlt(hdcMem, 0, 0, ptSize.x, ptSize.y, hdcObject, 0, 0, SRCAND);

          // Mask out the transparent colored pixels on the bitmap.
          BitBlt(hdcTemp, 0, 0, ptSize.x, ptSize.y, hdcBack, 0, 0, SRCAND);

          // XOR the bitmap with the background on the destination DC.
          BitBlt(hdcMem, 0, 0, ptSize.x, ptSize.y, hdcTemp, 0, 0, SRCPAINT);

          // Copy the destination to the screen.
          BitBlt(hdc, img->rPos.left, img->rPos.top, ptSize.x, ptSize.y, hdcMem, 0, 0,
              SRCCOPY);

          // Place the original bitmap back into the bitmap sent here.
          BitBlt(hdcTemp, 0, 0, ptSize.x, ptSize.y, hdcSave, 0, 0, SRCCOPY);

          // Delete the memory bitmaps.
          DeleteObject(SelectObject(hdcBack, bmBackOld));
          DeleteObject(SelectObject(hdcObject, bmObjectOld));
          DeleteObject(SelectObject(hdcMem, bmMemOld));
          DeleteObject(SelectObject(hdcSave, bmSaveOld));

          // Delete the memory DCs.
          DeleteDC(hdcMem);
          DeleteDC(hdcBack);
          DeleteDC(hdcObject);
          DeleteDC(hdcSave);
          DeleteDC(hdcTemp);
        }
        img = img->next;
      }

      LCS();

      EndPaint(hwnd, &ps);
    }
    break;
    case WM_WINDOWPOSCHANGING:
      if (IsWindow(hwndParent))
      {
        LPWINDOWPOS wp = (LPWINDOWPOS) lParam;
        wp->flags |= SWP_NOACTIVATE;
        wp->hwndInsertAfter = hwndParent;
      }
      break;
    case WM_CLOSE:
      DestroyWindow(hwnd);
    break;
    default:
      return DefWindowProc(hwnd, message, wParam, lParam);
  }
Exemplo n.º 16
0
//-----------------------------------WinProc-----------------------------
//
//-----------------------------------------------------------------------
LRESULT CALLBACK WindowProc(HWND hWnd, 
						                UINT msg, 
                            WPARAM wparam, 
                            LPARAM lparam)
{
	//these hold the dimensions of the client window area
	static int cxClient, cyClient;

	//used to create the back buffer
	static HDC		  hdcBackBuffer;
	static HBITMAP	hBitmap;
	static HBITMAP	hOldBitmap; 


	switch(msg)
	{	
		case WM_CREATE: 
		{
			//seed the random number generator
			srand((unsigned) time(NULL));

			//get the size of the client window
			RECT rect;
			GetClientRect(hWnd, &rect);

			cxClient = rect.right;
			cyClient = rect.bottom;

			//create a surface for us to render to(backbuffer)
			hdcBackBuffer = CreateCompatibleDC(NULL);

			HDC hdc = GetDC(hWnd);

			hBitmap = CreateCompatibleBitmap(hdc,
											                 cxClient,
											                 cyClient);
			ReleaseDC(hWnd, hdc);

			hOldBitmap = (HBITMAP)SelectObject(hdcBackBuffer, hBitmap); 

		} 
			
		break;
		
		//check key press messages
		case WM_KEYUP:
		{
			switch(wparam)
			{

				case VK_ESCAPE:
				{
					PostQuitMessage(0);
				}

				break;

			}//end WM_KEYUP switch
		}

		break;

		case WM_PAINT: 
		{
      
      
      PAINTSTRUCT ps;
      
		  BeginPaint(hWnd, &ps);
		
			//fill our backbuffer with white
			BitBlt(hdcBackBuffer,
             0,
             0,
             cxClient,
             cyClient,
             NULL,
             NULL,
             NULL,
             WHITENESS);
			
      //render the gun
      g_Gun.Render(hdcBackBuffer);
			
			//now blit backbuffer to front
			BitBlt(ps.hdc, 0, 0, cxClient, cyClient, hdcBackBuffer, 0, 0, SRCCOPY); 

			EndPaint(hWnd, &ps);
		} 
			
		break;

		case WM_DESTROY: 
		{
			SelectObject(hdcBackBuffer, hOldBitmap);
			
			//clean up our backbuffer objects
			DeleteDC(hdcBackBuffer);
			DeleteObject(hBitmap); 

      // kill the application, this sends a WM_QUIT message 
			PostQuitMessage(0);
 		} 
			
		break;

		default:break;

	}//end switch

	// default msg handler 
	return (DefWindowProc(hWnd, msg, wparam, lparam));

}//end WinProc
Exemplo n.º 17
0
/*****************************************************************
 *		CreateCaret (USER32.@)
 */
BOOL WINAPI CreateCaret( HWND hwnd, HBITMAP bitmap, INT width, INT height )
{
    BOOL ret;
    RECT r;
    int old_state = 0;
    int hidden = 0;
    HBITMAP hBmp = 0;
    HWND prev = 0;

    TRACE("hwnd=%p\n", hwnd);

    if (!hwnd) return FALSE;

    if (bitmap && (bitmap != (HBITMAP)1))
    {
        BITMAP bmp;
        if (!GetObjectA( bitmap, sizeof(bmp), &bmp )) return FALSE;
        width = bmp.bmWidth;
        height = bmp.bmHeight;
	bmp.bmBits = NULL;
	hBmp = CreateBitmapIndirect(&bmp);
	if (hBmp)
	{
	    /* copy the bitmap */
	    LPBYTE buf = HeapAlloc(GetProcessHeap(), 0, bmp.bmWidthBytes * bmp.bmHeight);
	    GetBitmapBits(bitmap, bmp.bmWidthBytes * bmp.bmHeight, buf);
	    SetBitmapBits(hBmp, bmp.bmWidthBytes * bmp.bmHeight, buf);
	    HeapFree(GetProcessHeap(), 0, buf);
	}
    }
    else
    {
	HDC hdc;

        if (!width) width = GetSystemMetrics(SM_CXBORDER);
        if (!height) height = GetSystemMetrics(SM_CYBORDER);

	/* create the uniform bitmap on the fly */
	hdc = GetDC(hwnd);
	if (hdc)
	{
	    HDC hMemDC = CreateCompatibleDC(hdc);
	    if (hMemDC)
	    {
		if ((hBmp = CreateCompatibleBitmap(hMemDC, width, height )))
		{
		    HBITMAP hPrevBmp = SelectObject(hMemDC, hBmp);
                    SetRect( &r, 0, 0, width, height );
		    FillRect(hMemDC, &r, bitmap ? GetStockObject(GRAY_BRUSH) : GetStockObject(WHITE_BRUSH));
		    SelectObject(hMemDC, hPrevBmp);
		}
		DeleteDC(hMemDC);
	    }
	    ReleaseDC(hwnd, hdc);
	}
    }
    if (!hBmp) return FALSE;

    SERVER_START_REQ( set_caret_window )
    {
        req->handle = wine_server_user_handle( hwnd );
        req->width  = width;
        req->height = height;
        if ((ret = !wine_server_call_err( req )))
        {
            prev      = wine_server_ptr_handle( reply->previous );
            r.left    = reply->old_rect.left;
            r.top     = reply->old_rect.top;
            r.right   = reply->old_rect.right;
            r.bottom  = reply->old_rect.bottom;
            old_state = reply->old_state;
            hidden    = reply->old_hide;
        }
    }
    SERVER_END_REQ;
    if (!ret) return FALSE;

    if (prev && !hidden)  /* hide the previous one */
    {
        /* FIXME: won't work if prev belongs to a different process */
        KillSystemTimer( prev, TIMERID );
        if (old_state) CARET_DisplayCaret( prev, &r );
    }

    if (Caret.hBmp) DeleteObject( Caret.hBmp );
    Caret.hBmp = hBmp;
    Caret.timeout = GetProfileIntA( "windows", "CursorBlinkRate", 500 );
    return TRUE;
}
Exemplo n.º 18
0
EXTERN_C_BEGIN
#undef __FUNCT__  
#define __FUNCT__ "PetscDrawCreate_Win32" 
PetscErrorCode  PetscDrawCreate_Win32(PetscDraw draw)
{       
  PetscDraw_Win32 *windraw;
  HANDLE          hThread = NULL;
  PetscErrorCode ierr;
  WindowNode      newnode;
  
  PetscFunctionBegin;
  ierr        = PetscNew(PetscDraw_Win32,&windraw);CHKERRQ(ierr);
  draw->data  = windraw;
  
  /* the following is temporary fix for initializing a global datastructure */
  if(!g_hWindowListMutex) {
    g_hWindowListMutex = CreateMutex(NULL,FALSE,NULL);
  }
  ierr = PetscMemcpy(draw->ops,&DvOps,sizeof(DvOps));CHKERRQ(ierr);
  
  windraw->hReadyEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  /* makes call to MessageLoopThread to creat window and attach a thread */
  CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)MessageLoopThread_Win32,draw,0,(unsigned long*)hThread);
  CloseHandle(hThread);
  WaitForSingleObject(windraw->hReadyEvent,INFINITE);
  CloseHandle(windraw->hReadyEvent);
  WaitForSingleObject(g_hWindowListMutex,INFINITE);
  
  ierr                    = PetscNew(struct _p_WindowNode,&newnode);CHKERRQ(ierr);
  newnode->MouseListHead  = NULL;
  newnode->MouseListTail  = NULL;
  newnode->wnext          = WindowListHead;
  newnode->wprev          = NULL;
  newnode->hWnd           = windraw->hWnd;
  if(WindowListHead != NULL) {
    WindowListHead->wprev = newnode;
  }
  WindowListHead          = newnode;
  windraw->hdc            = GetDC(windraw->hWnd);
  
  windraw->stringheight   = 10; 
  windraw->stringwidth    = 6;
  windraw->linewidth      = 1;   /* default pixel sizes of graphics until user changes them */
  windraw->pointdiameter  = 1;
  windraw->node           = newnode;
  
  windraw->x = draw->x;
  windraw->y = draw->y;
  windraw->w = newnode->bitwidth    = draw->w;
  windraw->h = newnode->bitheight   = draw->h;  
  
  /* Create and initialize primary graphics buffer */
  newnode->Buffer = CreateCompatibleDC(windraw->hdc);
  newnode->BufferBit = CreateCompatibleBitmap(windraw->hdc,windraw->w,windraw->h);
  newnode->store = SelectObject(newnode->Buffer,newnode->BufferBit);
  ExtFloodFill(newnode->Buffer,0,0,COLOR_WINDOW,FLOODFILLBORDER);
  
  newnode->event          = CreateEvent(NULL,TRUE,FALSE,NULL);
  newnode->DoubleBuffered = PETSC_FALSE;
  
  ReleaseDC(windraw->hWnd,windraw->hdc);
  ReleaseMutex(g_hWindowListMutex);
  PetscFunctionReturn(0);
}
Exemplo n.º 19
0
bool Win32Window::takeScreenshot(uint8_t *pixelData)
{
    if (mIsVisible)
    {
        return false;
    }

    bool error = false;

    // Hack for DWM: There is no way to wait for DWM animations to finish, so we just have to wait
    // for a while before issuing screenshot if window was just made visible.
    {
        static const double WAIT_WINDOW_VISIBLE_MS = 0.5; // Half a second for the animation
        double timeSinceVisible = mSetVisibleTimer->getElapsedTime();

        if (timeSinceVisible < WAIT_WINDOW_VISIBLE_MS)
        {
            Sleep(static_cast<DWORD>((WAIT_WINDOW_VISIBLE_MS - timeSinceVisible) * 1000));
        }
    }

    HDC screenDC = nullptr;
    HDC windowDC = nullptr;
    HDC tmpDC = nullptr;
    HBITMAP tmpBitmap = nullptr;

    if (!error)
    {
        screenDC = GetDC(nullptr);
        error = screenDC == nullptr;
    }

    if (!error)
    {
        windowDC = GetDC(mNativeWindow);
        error = windowDC == nullptr;
    }

    if (!error)
    {
        tmpDC = CreateCompatibleDC(screenDC);
        error = tmpDC == nullptr;
    }

    if (!error)
    {
        tmpBitmap = CreateCompatibleBitmap(screenDC, mWidth, mHeight);
        error = tmpBitmap == nullptr;
    }

    RECT rect = {0, 0, 0, 0};
    if (!error)
    {
        MapWindowPoints(mNativeWindow, nullptr, reinterpret_cast<LPPOINT>(&rect), 0);

        error = SelectObject(tmpDC, tmpBitmap) == nullptr;
    }

    if (!error)
    {
        error = BitBlt(tmpDC, 0, 0, mWidth, mHeight, screenDC, rect.left, rect.top, SRCCOPY) == TRUE;
    }

    if (!error)
    {
        BITMAPINFOHEADER bitmapInfo;
        bitmapInfo.biSize = sizeof(BITMAPINFOHEADER);
        bitmapInfo.biWidth = mWidth;
        bitmapInfo.biHeight = -mHeight;
        bitmapInfo.biPlanes = 1;
        bitmapInfo.biBitCount = 32;
        bitmapInfo.biCompression = BI_RGB;
        bitmapInfo.biSizeImage = 0;
        bitmapInfo.biXPelsPerMeter = 0;
        bitmapInfo.biYPelsPerMeter = 0;
        bitmapInfo.biClrUsed = 0;
        bitmapInfo.biClrImportant = 0;
        int getBitsResult = GetDIBits(screenDC, tmpBitmap, 0, mHeight, pixelData,
            reinterpret_cast<BITMAPINFO*>(&bitmapInfo), DIB_RGB_COLORS);
        error = getBitsResult != 0;
    }

    if (tmpBitmap != nullptr)
    {
        DeleteObject(tmpBitmap);
    }
    if (tmpDC != nullptr)
    {
        DeleteDC(tmpDC);
    }
    if (screenDC != nullptr)
    {
        ReleaseDC(nullptr, screenDC);
    }
    if (windowDC != nullptr)
    {
        ReleaseDC(mNativeWindow, windowDC);
    }

    return !error;
}
Exemplo n.º 20
0
//
// InitWindowRegion
//
// We display the video in a window that has a region selected into it that
// matches the word we are passed in. By doing this we let Windows manage
// all the clipping and mouse technology. The trick is in creating a region
// that matches the word, which is done by using paths. We create a path for
// a temporary HDC, draw the word and then end the path. After that, we can then
// ask Windows for a region that describes that path. That gives us a region
// for the outside of the word, so we bitwise "not" it to get the word region.
//
HRESULT CVideoText::InitWindowRegion(TCHAR *pStringName)
{
    ASSERT(pStringName);

    OSVERSIONINFO VersionInfo;
    VersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    EXECUTE_ASSERT(GetVersionEx(&VersionInfo));

    // Set a window region according to the OS capabilities

    if ((VersionInfo.dwPlatformId & VER_PLATFORM_WIN32_NT) == 0) 
    {
        m_Size.cx = 320;
        m_Size.cy = 240;
        return NOERROR;
    }

    // Get the text extents the word passed in will require based on the
    // font and bitmap selected in the current device context. For it to
    // be displayed in a different font it must be selected into the HDC

    HDC hdc = CreateCompatibleDC(m_hdc);
    HFONT hFont = CreateVideoFont();
    SelectObject(hdc,hFont);

    GetTextExtentPoint32((HDC) hdc,             // The output device context
                         pStringName,           // The string we'll be using
                         lstrlen(pStringName),  // Number of characters in it
                         (LPSIZE) &m_Size);     // Filled in with the extents

    // Create a bitmap that matches the current format

    HBITMAP hMaskBitmap = CreateCompatibleBitmap(hdc,m_Size.cx,m_Size.cy);
    if (hMaskBitmap == NULL) {
        ASSERT(hMaskBitmap);
        return E_UNEXPECTED;
    }

    // Select the monochrome bitmap into the device context

    HBITMAP hBitmap = (HBITMAP) SelectObject(hdc,hMaskBitmap);
    EXECUTE_ASSERT(BeginPath(hdc));

    // Draw the string into the monochrome bitmap

    ExtTextOut((HDC) hdc,               // Target device context
               (int) 0,                 // x coordinate reference
               (int) 0,                 // Likewise y coordinate
               (DWORD) 0,               // No special flags to set
               NULL,                    // No clipping rectangle
               pStringName,             // Pointer to text words
               lstrlen(pStringName),    // Number of characters
               NULL);                   // Intercharacter spacing

    EXECUTE_ASSERT(EndPath(hdc));

    HRGN hOutside = PathToRegion(hdc);
    HRGN hFullWindow = CreateRectRgn(0,0,m_Size.cx,m_Size.cy);
    HRGN hWordRegion = CreateRectRgn(0,0,1,1);
    CombineRgn(hWordRegion,hFullWindow,hOutside,RGN_DIFF);
    SetWindowRgn(m_hwnd,hWordRegion,TRUE);

    // Clear up the regions we created

    DeleteObject(hWordRegion);
    DeleteObject(hOutside);
    DeleteObject(hFullWindow);

    // Delete the HDC and text bitmap

    SelectObject(hdc,hBitmap);
    HFONT hDefault = (HFONT) GetStockObject(SYSTEM_FONT);
    SelectObject(hdc,hDefault);

    DeleteObject(hFont);
    DeleteObject(hMaskBitmap);
    DeleteDC(hdc);

    return NOERROR;

} // InitWindowRegion
void DynamicFontGenerator::GenerateFont()
{
	if (!m_dirty)
		return;

	m_dirty = false;
	m_texture->createTexture(math::vector3di(m_textureSize.x,m_textureSize.y, 1), video::EPixel_Alpha8);

	bool m_mask = true;

	if (m_data->fontDirty)
	{
		m_data->Recreate(m_fontResolution, m_bold, m_italic,m_underline, m_fontName);
	}


	HBITMAP bmp = CreateCompatibleBitmap(m_data->dc, m_textureSize.x, m_textureSize.y);
	HDC bmpdc = CreateCompatibleDC(m_data->dc);

	HBRUSH brush = CreateSolidBrush(RGB(0, 0, 0));
	HPEN pen = CreatePen(PS_NULL, 0, RGB(0, 0, 0));

	HGDIOBJ oldbmp = SelectObject(bmpdc, bmp);
	HGDIOBJ oldbmppen = SelectObject(bmpdc, pen);
	HGDIOBJ oldbmpbrush = SelectObject(bmpdc, brush);
	HGDIOBJ oldbmpFont = SelectObject(bmpdc, m_data->font);


	SetBkMode(bmpdc, OPAQUE);
	SetBkColor(bmpdc, RGB(0,0,0));
	SetTextColor(bmpdc, RGB(255, 255, 255));
	Rectangle(bmpdc, 0, 0, m_textureSize.x, m_textureSize.y);

	core::stringw text = L"";

	// prepare characters 
	std::vector<wchar_t> sorted;
	std::vector<math::vector2d> rectSize;
	std::vector< core::BinPackerOutRect > packs;
	{
		for (int i = 0; i < m_charsAttr.size(); ++i)
			delete m_charsAttr[i];
		m_charsAttr.clear();
		FontCharacterRange* range = 0;
		std::set<wchar_t>::iterator it = m_chars.begin();
		sorted.resize(m_chars.size());
		std::vector<int> rangeMap;
		wchar_t lastID = -1;
		wchar_t minID = -1;
		int firstIdx = 0;
		
		for (int i=0; it != m_chars.end(); ++it,++i)
		{
			sorted[i] = *it;
		}

		std::sort(sorted.begin(), sorted.end());
		for (int i = 0; i < sorted.size();++i)
		{
			wchar_t c = sorted[i];
			if (lastID == -1)
			{
				minID = c;
				lastID = c;
			}
			else
			{
				if (c!=lastID+1)
				{
					if (!range)
					{
						range = new FontCharacterRange();
					}
					range->SetMinMax(minID,lastID);
					m_charsAttr.push_back(range);
					range = new FontCharacterRange();

					minID = c;
					firstIdx = i;
				}
				lastID = c;
				rangeMap.push_back(m_charsAttr.size());
			}
			text.append(1,c);
			//calculate character size
			SIZE sz;
			GetTextExtentPoint32W(bmpdc, &c, 1, &sz);

			rectSize.push_back(math::vector2d(sz.cx, sz.cy));
		}
		if (range != 0){
			range->SetMinMax(minID, lastID);
			m_charsAttr.push_back(range);
		}

		core::BinPacker packer;
		packer.Pack(rectSize, packs, math::vector2d(m_textureSize.x, m_textureSize.y), false);
		math::vector2d invSize(1.0f / m_textureSize.x, 1.0f / m_textureSize.y);
		float invRes = 1.0f / (float)m_fontResolution;
		for (int i = 0; i < packs.size();++i)
		{
			int id = packs[i].ID;
			FontCharacterRange* range= m_charsAttr[rangeMap[id]];
			FontCharAttr* attr = range->GetCharacterInfo(sorted[id]);
			attr->rectSize = rectSize[id] * invRes;
			attr->texID = 0;
			attr->texcoords.ULPoint = packs[i].pos*invSize;
			attr->texcoords.BRPoint = attr->texcoords.ULPoint + rectSize[id] * invSize;

		}
	}
	for (int i = 0; i < packs.size(); ++i)
	{
		core::BinPackerOutRect& p = packs[i];
		TextOutW(bmpdc, p.pos.x, p.pos.y, &sorted[p.ID], 1);

	}

	BITMAP bmpInfo;

	//get image info
	GetObject(bmp, sizeof(BITMAP), &bmpInfo);
	uchar *buffer;
	int pixel = m_mask ? 4 : 3;

	int line = (bmpInfo.bmWidth*pixel + pixel) & 0xfffffffc;
	int dataSize = line*(bmpInfo.bmHeight);
	//get image data
	buffer = new uchar[dataSize];

	video::IHardwarePixelBuffer* pixBuff= m_texture->getSurface(0);
	video::LockedPixelBox lbox = pixBuff->lock(math::box3d(0, 0, 0, m_textureSize.x, m_textureSize.y, 1), video::IHardwareBuffer::ELO_Discard);
	uchar* dstPixels = (uchar*)lbox.data;

	GetBitmapBits(bmp, dataSize, buffer);
	for (int i = 0; i < m_textureSize.x*m_textureSize.y; ++i)
	{
		dstPixels[i] = buffer[i * 4];
	}
	pixBuff->unlock();

	delete[] buffer;

	SelectObject(bmpdc, oldbmp);
	SelectObject(bmpdc, oldbmppen);
	SelectObject(bmpdc, oldbmpbrush);


	DeleteDC(bmpdc);
	DeleteObject(brush);
	DeleteObject(pen);
	DeleteObject(bmp);
}
Exemplo n.º 22
0
HBITMAP CopyScreenToBitmap(LPRECT lpRect, BYTE *pData, BITMAPINFO *pHeader,
BOOL blLogo)	// ロゴの有無
{
    HDC         hScrDC, hMemDC;         // screen DC and memory DC
    HBITMAP     hBitmap, hOldBitmap;    // handles to deice-dependent bitmaps
    int         nX, nY, nX2, nY2;       // coordinates of rectangle to grab
    int         nWidth, nHeight;        // DIB width and height
    int         xScrn, yScrn;           // screen resolution

    // check for an empty rectangle
    if (IsRectEmpty(lpRect))
      return NULL;

    // create a DC for the screen and create
    // a memory DC compatible to screen DC   
    hScrDC = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
    hMemDC = CreateCompatibleDC(hScrDC);

    // get points of rectangle to grab
    nX  = lpRect->left;
    nY  = lpRect->top;
    nX2 = lpRect->right;
    nY2 = lpRect->bottom;

    // get screen resolution
    xScrn = GetDeviceCaps(hScrDC, HORZRES);
    yScrn = GetDeviceCaps(hScrDC, VERTRES);

    //make sure bitmap rectangle is visible
    if (nX < 0)
        nX = 0;
    if (nY < 0)
        nY = 0;
    if (nX2 > xScrn)
        nX2 = xScrn;
    if (nY2 > yScrn)
        nY2 = yScrn;

    nWidth  = nX2 - nX;
    nHeight = nY2 - nY;

    // create a bitmap compatible with the screen DC
    hBitmap = CreateCompatibleBitmap(hScrDC, nWidth, nHeight);

    // select new bitmap into memory DC
    hOldBitmap = (HBITMAP) SelectObject(hMemDC, hBitmap);

    // bitblt screen DC to memory DC
    BitBlt(hMemDC, 0, 0, nWidth, nHeight, hScrDC, nX, nY, SRCCOPY);

	// Text impose
	if (blLogo) {
		AddText(hMemDC);
	}

	// select old bitmap back into memory DC and get handle to
    // bitmap of the screen   
    hBitmap = (HBITMAP)  SelectObject(hMemDC, hOldBitmap);

    // Copy the bitmap data into the provided BYTE buffer
    GetDIBits(hScrDC, hBitmap, 0, nHeight, pData, pHeader, DIB_RGB_COLORS);

    // clean up
    DeleteDC(hScrDC);
    DeleteDC(hMemDC);

    // return handle to the bitmap
    return hBitmap;
}
Exemplo n.º 23
0
VOID vTestPal3(HDC hdc)
{
    HBRUSH   hbrR, hbrG, hbrB;
    HDC hdc8;
    HBITMAP hbm8;

    if (GetDeviceCaps(hdc,BITSPIXEL) > 8)
        return;

    hbm8 = CreateCompatibleBitmap(hdc, 64, 64);
    hdc8 = CreateCompatibleDC(hdc);
    SelectObject(hdc8, hbm8);

    hbrR = CreateSolidBrush(RGB(255,0,0));
    hbrG = CreateSolidBrush(RGB(0,255,0));
    hbrB = CreateSolidBrush(RGB(0,0,255));

    SelectObject(hdc8, hbrR);
    PatBlt(hdc8, 0, 0, 64, 64, PATCOPY);
    SelectObject(hdc8, hbrG);
    PatBlt(hdc8, 16, 16, 32, 32, PATCOPY);
    SelectObject(hdc8, hbrB);
    PatBlt(hdc8, 24, 24, 16, 16, PATCOPY);

// See what the bitmap looks like.

    BitBlt(hdc, 0, 100, 64, 64, hdc8, 0, 0, SRCCOPY);

// Get the header

    bmi256.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmi256.bmiHeader.biBitCount = 0;

    GetDIBits(hdc8, hbm8, 0, 64, (PBYTE) NULL, (LPBITMAPINFO) &bmi256, DIB_RGB_COLORS);

// Get the color table

    GetDIBits(hdc8, hbm8, 0, 64, (PBYTE) NULL, (LPBITMAPINFO) &bmi256, DIB_RGB_COLORS);

// Get the bits

    if (64 != GetDIBits(hdc8, hbm8, 0, 64, (PBYTE) ajBuffer, (LPBITMAPINFO) &bmi256, DIB_RGB_COLORS))
	DbgPrint("The GetDIBits failed vTestPal3\n");

// Look at the bits.

    SetDIBitsToDevice(hdc, 64, 100, 64, 64, 0, 0, 0, 64,
		      (PBYTE) ajBuffer, (LPBITMAPINFO) &bmi256, DIB_RGB_COLORS);

// Do them left half right half

    SetDIBitsToDevice(hdc, 128, 100, 32, 64, 0, 0, 0, 64,
		      (PBYTE) ajBuffer, (LPBITMAPINFO) &bmi256, DIB_RGB_COLORS);

    SetDIBitsToDevice(hdc, 160, 100, 32, 64, 32, 0, 0, 64,
		      (PBYTE) ajBuffer, (LPBITMAPINFO) &bmi256, DIB_RGB_COLORS);

    DeleteDC(hdc8);
    DeleteObject(hbm8);
    DeleteObject(hbrR);
    DeleteObject(hbrG);
    DeleteObject(hbrB);
}
Exemplo n.º 24
0
VOID CRenoBuffer::OnPaint()
{
	CPaintDC dc(this);

	CRect clipRect;
	dc.GetClipBox(clipRect);

	CRect clientRect;
	GetClientRect(clientRect);

	// Start doublebuffering
	HDC hCompatibleDC = CreateCompatibleDC(dc.GetSafeHdc());
	HBITMAP hBackbuffer = CreateCompatibleBitmap(dc.GetSafeHdc(),clientRect.Width(),clientRect.Height());
	HBITMAP hOldBitmap  = (HBITMAP)SelectObject(hCompatibleDC,hBackbuffer);

	SetBoundsRect(hCompatibleDC,clipRect,NULL);

	FillRect(hCompatibleDC,clientRect,(HBRUSH)CBrush(BACKGROUND_COLOR).GetSafeHandle());

	HGDIOBJ hOldFont = SelectObject(hCompatibleDC,theApp.GetFont());
	SetBkMode(hCompatibleDC,TRANSPARENT);

	CRect boundsRect;
	GetClientRect(boundsRect);
	boundsRect.DeflateRect(RENO_BUFFER_MARGIN_HORIZONTAL,RENO_BUFFER_MARGIN_VERTICAL);

	COLORREF colorDefault = GetTextColor(hCompatibleDC);
	COLORREF colorSystem = RGB(44,88,222);

	SIZE size;
	TEXTMETRIC textmetrics;

	for(LONG i = m_BufferScrollLine; i < m_Buffer.GetCount(); ++i)
	{
		if(!m_Buffer[i].GetLength())
		{
			GetTextExtentPoint32(hCompatibleDC,TEXT(" "),1,&size);
			boundsRect.bottom -= size.cy;
			continue;
		}

		// Currently only color system messages
		if(m_Buffer[i].GetAt(0) == TEXT('*'))
			SetTextColor(hCompatibleDC,colorSystem);
		else
			SetTextColor(hCompatibleDC,colorDefault);

		// Set a fixed stack size
		ULONG stack[32];
		ULONG stackTop = 0;

		// Put the default font at the bottom of the stack
		stack[stackTop++] = RENO_FONT_NORMAL;

		LONG x = boundsRect.left;
		LONG index = 0;

		while(index < m_Buffer[i].GetLength())
		{
			LONG control = -1;

			// Find a control character
			for(LONG j = index + 1; j < m_Buffer[i].GetLength(); ++j)
			{
				if(m_Buffer[i].GetAt(j) == IRC_CONTROL_BOLD || 
					m_Buffer[i].GetAt(j) == IRC_CONTROL_UNDERLINE || 
					m_Buffer[i].GetAt(j) == IRC_CONTROL_ITALIC || 
					m_Buffer[i].GetAt(j) == IRC_CONTROL_NORMAL)
				{
					// Found one
					control = j;
					break;
				}
			}

			if(control == -1)
			{
				// We are going to the end of the line
				control = m_Buffer[i].GetLength();
			}

			// Colors

			// "black"			: "\x0301",
			// "dark blue"		: "\x0302",
			// "dark green"		: "\x0303",
			// "green"			: "\x0303",
			// "red"			: "\x0304",
			// "light red"		: "\x0304",
			// "dark red"		: "\x0305",
			// "purple"			: "\x0306",
			// "brown"			: "\x0307",	// On some clients this is orange, others it is brown
			// "orange"			: "\x0307",
			// "yellow"			: "\x0308",
			// "light green"	: "\x0309",
			// "aqua"			: "\x0310",
			// "light blue"		: "\x0311",
			// "blue"			: "\x0312",
			// "violet"			: "\x0313",
			// "grey"			: "\x0314",
			// "gray"			: "\x0314",
			// "light grey"		: "\x0315",
			// "light gray"		: "\x0315",
			// "white"			: "\x0316",

			// Other formatting

			// "normal"			: "\x0F",
			// "bold"			: "\x02",
			// "reverse"		: "\x16",
			// "underline"		: "\x1F",

			switch(m_Buffer[i].GetAt(index))
			{
			case IRC_CONTROL_BOLD:
				if(stack[stackTop-1] == RENO_FONT_BOLD)
					--stackTop;	// Pop the top
				else
					stack[stackTop++] = RENO_FONT_BOLD;	// Push

				++index;	// Skip the control character
				break;

			case IRC_CONTROL_ITALIC:
				if(stack[stackTop-1] ==RENO_FONT_ITALIC)
					--stackTop;	// Pop the top
				else
					stack[stackTop++] = RENO_FONT_ITALIC;	// Push

				++index;	// Skip the control character
				break;

			case IRC_CONTROL_UNDERLINE:
				if(stack[stackTop-1] == RENO_FONT_UNDERLINE)
					--stackTop;	// Pop the top
				else
					stack[stackTop++] = RENO_FONT_UNDERLINE;	// Push

				++index;	// Skip the control character
				break;

			case IRC_CONTROL_NORMAL:
				if(stack[stackTop-1] == RENO_FONT_NORMAL && stackTop > 1)
					--stackTop;	// Pop the top
				else
					stack[stackTop++] = RENO_FONT_NORMAL;	// Push

				++index;	// Skip the control character
				break;
			}

			if(control - index)
			{
				SelectObject(hCompatibleDC,theApp.GetFont(stack[stackTop-1]));

				GetTextExtentPoint32(hCompatibleDC,m_Buffer[i].GetBuffer() + index,control - index,&size);

				TextOut(hCompatibleDC,x,boundsRect.bottom - size.cy,m_Buffer[i].GetBuffer() + index,control - index);
				
				x += size.cx;

				// Retrieve the overhang value from the TEXTMETRIC structure and subtract it from the x-increment (This is only necessary for non-TrueType raster fonts)
				GetTextMetrics(hCompatibleDC,&textmetrics);
				x -= textmetrics.tmOverhang;
			}

			index = control;
		}

		GetTextExtentPoint32(hCompatibleDC,TEXT(" "),1,&size);	// TODO Maybe not necessary, the size struct will already be set from some above call
		boundsRect.bottom -= size.cy;

		if(boundsRect.bottom < -size.cy)
			break;	// No point in painting further cause everything would get clipped
	}

	// Update the scrollbar
	if(m_Buffer.GetCount() > 1)
	{
		SelectObject(hCompatibleDC,theApp.GetFont());
		GetTextMetrics(hCompatibleDC,&textmetrics);

		SCROLLINFO info;
		info.cbSize = sizeof(info);

		info.fMask = SIF_ALL;
		info.nMin = 0;
		info.nMax = m_Buffer.GetCount()-1 + clientRect.Height()/textmetrics.tmHeight-1;
		info.nPos = m_Buffer.GetCount()-1 - m_BufferScrollLine;
		info.nPage = clientRect.Height()/textmetrics.tmHeight;

		SetScrollInfo(SB_VERT,&info);
		EnableScrollBar(SB_VERT,ESB_ENABLE_BOTH);
	}
	else
	{
		EnableScrollBar(SB_VERT,ESB_DISABLE_BOTH);
	}

	SelectObject(hCompatibleDC,hOldFont);

	// End doublebuffering
	BitBlt(dc.GetSafeHdc(),0,0,clientRect.Width(),clientRect.Height(),hCompatibleDC,0,0,SRCCOPY);
	SelectObject(hCompatibleDC,hOldBitmap);
	DeleteObject(hBackbuffer);
	DeleteDC(hCompatibleDC);
}
Exemplo n.º 25
0
//
//  函数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
//  目的: 处理主窗口的消息。
//
//  WM_COMMAND	- 处理应用程序菜单
//  WM_PAINT	- 绘制主窗口
//  WM_DESTROY	- 发送退出消息并返回
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;
	PAINTSTRUCT ps;
	HDC hdc;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// 分析菜单选择:
		switch (wmId)
		{
		case IDM_ABOUT:
			DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
			break;
		case IDM_EXIT:
			DestroyWindow(hWnd);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
		}
		break;
	case WM_PAINT:
    {
		hdc = BeginPaint(hWnd, &ps);
		HDC comDC = CreateCompatibleDC(hdc);

        RECT rect;
        GetClientRect(hWnd, &rect);//这时还不能绘图,因为没有地方画 ^_^
        //下面建立一个与屏幕显示兼容的位图,至于位图的大小嘛,可以用窗口的大小,也可以自己定义(如:有滚动条时就要大于当前窗口的大小,在BitBlt时决定拷贝内存的哪部分到屏幕上
        HBITMAP comBitmap = CreateCompatibleBitmap(hdc, 
            rect.right - rect.left, rect.bottom-rect.top);
        //将位图选入到内存显示设备中
        //只有选入了位图的内存显示设备才有地方绘图,画到指定的位图上
        HBITMAP oldBitmap = (HBITMAP)SelectObject(comDC, comBitmap);

        //先用背景色将位图清除干净,这里我用的是白色作为背景(否则会为黑色)
        //你也可以用自己应该用的颜色
        HBRUSH brush = CreateSolidBrush(RGB(255, 255, 255));
        FillRect(comDC, &rect, brush);
        DeleteObject(brush);

        //进行绘图操作
        LineTo(comDC, 100, 100);
        LineTo(comDC, 300, 300);
        TextOut(comDC, 200, 200, L"兼容DC测试", 6);
        Rectangle(comDC, 500, 100, 800, 300);

        //将内存中的图拷贝到屏幕上进行显示
        BitBlt(hdc, 0, 0, rect.right - rect.left, rect.bottom -rect.top, comDC,
            0, 0, SRCCOPY);

        //绘图完成后的清理
        DeleteObject(comBitmap);
        DeleteObject(comDC);
		EndPaint(hWnd, &ps);
		break;
    }
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return DefWindowProc(hWnd, message, wParam, lParam);
	}
	return 0;
}
Exemplo n.º 26
0
BOOL
vncDesktop::InitBitmap()
{
	// Get the device context for the whole screen and find it's size
	m_hrootdc = ::GetDC(NULL);
	if (m_hrootdc == NULL) {
		//vnclog.Print(LL_INTERR, VNCLOG("failed to get display context\n"));
		return FALSE;
	}

	m_bmrect = rfb::Rect(0, 0,
		GetDeviceCaps(m_hrootdc, HORZRES),
		GetDeviceCaps(m_hrootdc, VERTRES));
	//vnclog.Print(LL_INTINFO, VNCLOG("bitmap dimensions are %d x %d\n"), m_bmrect.br.x, m_bmrect.br.y);

	// Create a compatible memory DC
	m_hmemdc = CreateCompatibleDC(m_hrootdc);
	if (m_hmemdc == NULL) {
		//vnclog.Print(LL_INTERR, VNCLOG("failed to create compatibleDC(%d)\n"), GetLastError());
		return FALSE;
	}

	// Check that the device capabilities are ok
	if ((GetDeviceCaps(m_hrootdc, RASTERCAPS) & RC_BITBLT) == 0)
	{
		MessageBox(
			NULL,
			"vncDesktop : root device doesn't support BitBlt\n"
			"WinVNC cannot be used with this graphic device driver",
			szAppName,
			MB_ICONSTOP | MB_OK
			);
		return FALSE;
	}
	if ((GetDeviceCaps(m_hmemdc, RASTERCAPS) & RC_DI_BITMAP) == 0)
	{
		MessageBox(
			NULL,
			"vncDesktop : memory device doesn't support GetDIBits\n"
			"WinVNC cannot be used with this graphics device driver",
			szAppName,
			MB_ICONSTOP | MB_OK
			);
		return FALSE;
	}

	// Create the bitmap to be compatible with the ROOT DC!!!
	m_membitmap = CreateCompatibleBitmap(m_hrootdc, m_bmrect.br.x, m_bmrect.br.y);
	if (m_membitmap == NULL) {
		//vnclog.Print(LL_INTERR, VNCLOG("failed to create memory bitmap(%d)\n"), GetLastError());
		return FALSE;
	}
	//vnclog.Print(LL_INTINFO, VNCLOG("created memory bitmap\n"));

	// Get the bitmap's format and colour details
	int result;
	memset(&m_bminfo, 0, sizeof(m_bminfo));
	m_bminfo.bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	m_bminfo.bmi.bmiHeader.biBitCount = 0;
	result = ::GetDIBits(m_hmemdc, m_membitmap, 0, 1, NULL, &m_bminfo.bmi, DIB_RGB_COLORS);
	if (result == 0) {
		//vnclog.Print(LL_INTERR, VNCLOG("unable to get display format\n"));
		return FALSE;
	}
	result = ::GetDIBits(m_hmemdc, m_membitmap,  0, 1, NULL, &m_bminfo.bmi, DIB_RGB_COLORS);
	if (result == 0) {
		//vnclog.Print(LL_INTERR, VNCLOG("unable to get display colour info\n"));
		return FALSE;
	}
	//vnclog.Print(LL_INTINFO, VNCLOG("got bitmap format\n"));

  // Henceforth we want to use a top-down scanning representation
	m_bminfo.bmi.bmiHeader.biHeight = - abs(m_bminfo.bmi.bmiHeader.biHeight);

	// Is the bitmap palette-based or truecolour?
	m_bminfo.truecolour = (GetDeviceCaps(m_hmemdc, RASTERCAPS) & RC_PALETTE) == 0;

	return TRUE;
}
Exemplo n.º 27
0
// Creation de bitmap coche
HBITMAP GetMyCheckBitmaps(UINT fuCheck) 
{ 
    COLORREF crBackground;  // background color                  
    HBRUSH hbrBackground;   // background brush                  
    HBRUSH hbrTargetOld;    // original background brush         
    HDC hdcSource;          // source device context             
    HDC hdcTarget;          // target device context             
    HBITMAP hbmpCheckboxes; // handle to check-box bitmap        
    BITMAP bmCheckbox;      // structure for bitmap data         
    HBITMAP hbmpSourceOld;  // handle to original source bitmap  
    HBITMAP hbmpTargetOld;  // handle to original target bitmap  
    HBITMAP hbmpCheck;      // handle to check-mark bitmap       
    RECT rc;                // rectangle for check-box bitmap    
    WORD wBitmapX;          // width of check-mark bitmap        
    WORD wBitmapY;          // height of check-mark bitmap       
 
    // Get the menu background color and create a solid brush 
    // with that color. 
 
    crBackground = GetSysColor(COLOR_MENU); 
    hbrBackground = CreateSolidBrush(crBackground); 
 
    // Create memory device contexts for the source and 
    // destination bitmaps. 
 
    hdcSource = CreateCompatibleDC((HDC) NULL); 
    hdcTarget = CreateCompatibleDC(hdcSource); 
 
    // Get the size of the system default check-mark bitmap and 
    // create a compatible bitmap of the same size. 
 
    wBitmapX = GetSystemMetrics(SM_CXMENUCHECK); 
    wBitmapY = GetSystemMetrics(SM_CYMENUCHECK); 
 
    hbmpCheck = CreateCompatibleBitmap(hdcSource, wBitmapX, 
        wBitmapY); 
 
    // Select the background brush and bitmap into the target DC. 
 
    hbrTargetOld = SelectObject(hdcTarget, hbrBackground); 
    hbmpTargetOld = SelectObject(hdcTarget, hbmpCheck); 
 
    // Use the selected brush to initialize the background color 
    // of the bitmap in the target device context. 
 
    PatBlt(hdcTarget, 0, 0, wBitmapX, wBitmapY, PATCOPY); 
 
    // Load the predefined check box bitmaps and select it 
    // into the source DC. 
 
    hbmpCheckboxes = LoadBitmap((HINSTANCE) NULL, 
        (LPTSTR) OBM_CHECKBOXES); 
 
    hbmpSourceOld = SelectObject(hdcSource, hbmpCheckboxes); 
 
    // Fill a BITMAP structure with information about the 
    // check box bitmaps, and then find the upper-left corner of 
    // the unchecked check box or the checked check box. 
 
    GetObject(hbmpCheckboxes, sizeof(BITMAP), &bmCheckbox); 
 
    if (fuCheck == 2 /*UNCHECK*/) 
    { 
        rc.left = 0; 
        rc.right = (bmCheckbox.bmWidth / 4); 
    } 
    else 
    { 
        rc.left = (bmCheckbox.bmWidth / 4); 
        rc.right = (bmCheckbox.bmWidth / 4) * 2; 
    } 
 
    rc.top = 0; 
    rc.bottom = (bmCheckbox.bmHeight / 3); 
 
    // Copy the appropriate bitmap into the target DC. If the 
    // check-box bitmap is larger than the default check-mark 
    // bitmap, use StretchBlt to make it fit; otherwise, just 
    // copy it. 
 
    if (((rc.right - rc.left) > (int) wBitmapX) || 
            ((rc.bottom - rc.top) > (int) wBitmapY)) 
    {
        StretchBlt(hdcTarget, 0, 0, wBitmapX, wBitmapY, 
            hdcSource, rc.left, rc.top, rc.right - rc.left, 
            rc.bottom - rc.top, SRCCOPY); 
    }
 
    else 
    {
        BitBlt(hdcTarget, 0, 0, rc.right - rc.left, 
            rc.bottom - rc.top, 
            hdcSource, rc.left, rc.top, SRCCOPY); 
    }
 
    // Select the old source and destination bitmaps into the 
    // source and destination DCs, and then delete the DCs and 
    // the background brush. 
 
    SelectObject(hdcSource, hbmpSourceOld); 
    SelectObject(hdcTarget, hbrTargetOld); 
    hbmpCheck = SelectObject(hdcTarget, hbmpTargetOld); 
 
    DeleteObject(hbrBackground); 
    DeleteObject(hdcSource); 
    DeleteObject(hdcTarget); 
 
    // Return a handle to the new check-mark bitmap.  
 
    return hbmpCheck; 
} 
Exemplo n.º 28
0
void CtrlDisAsmView::onPaint(WPARAM wParam, LPARAM lParam)
{
	if (!debugger->isAlive()) return;

	PAINTSTRUCT ps;
	HDC actualHdc = BeginPaint(wnd, &ps);
	HDC hdc = CreateCompatibleDC(actualHdc);
	HBITMAP hBM = CreateCompatibleBitmap(actualHdc, rect.right-rect.left, rect.bottom-rect.top);
	SelectObject(hdc, hBM);

	SetBkMode(hdc, TRANSPARENT);

	HPEN nullPen=CreatePen(0,0,0xffffff);
	HBRUSH nullBrush=CreateSolidBrush(0xffffff);
	HBRUSH currentBrush=CreateSolidBrush(0xffefe8);

	HPEN oldPen=(HPEN)SelectObject(hdc,nullPen);
	HBRUSH oldBrush=(HBRUSH)SelectObject(hdc,nullBrush);
	HFONT oldFont = (HFONT)SelectObject(hdc,(HGDIOBJ)font);
	HICON breakPoint = (HICON)LoadIcon(GetModuleHandle(0),(LPCWSTR)IDI_STOP);
	HICON breakPointDisable = (HICON)LoadIcon(GetModuleHandle(0),(LPCWSTR)IDI_STOPDISABLE);

	unsigned int address = windowStart;
	std::map<u32,int> addressPositions;

	const std::set<std::string> currentArguments = getSelectedLineArguments();
	DisassemblyLineInfo line;
	for (int i = 0; i < visibleRows; i++)
	{
		manager.getLine(address,displaySymbols,line);

		int rowY1 = rowHeight*i;
		int rowY2 = rowHeight*(i+1);

		addressPositions[address] = rowY1;

		// draw background
		COLORREF backgroundColor = whiteBackground ? 0xFFFFFF : debugger->getColor(address);
		COLORREF textColor = 0x000000;

		if (isInInterval(address,line.totalSize,debugger->getPC()))
		{
			backgroundColor = scaleColor(backgroundColor,1.05f);
		}

		if (address >= selectRangeStart && address < selectRangeEnd && searching == false)
		{
			if (hasFocus)
			{
				backgroundColor = address == curAddress ? 0xFF8822 : 0xFF9933;
				textColor = 0xFFFFFF;
			} else {
				backgroundColor = 0xC0C0C0;
			}
		}
		
		HBRUSH backgroundBrush = CreateSolidBrush(backgroundColor);
		HPEN backgroundPen = CreatePen(0,0,backgroundColor);
		SelectObject(hdc,backgroundBrush);
		SelectObject(hdc,backgroundPen);
		Rectangle(hdc,0,rowY1,rect.right,rowY1+rowHeight);

		SelectObject(hdc,currentBrush);
		SelectObject(hdc,nullPen);

		DeleteObject(backgroundBrush);
		DeleteObject(backgroundPen);

		// display address/symbol
		bool enabled;
		if (CBreakPoints::IsAddressBreakPoint(address,&enabled))
		{
			if (enabled) textColor = 0x0000FF;
			int yOffset = max(-1,(rowHeight-14+1)/2);
			if (!enabled) yOffset++;
			DrawIconEx(hdc,2,rowY1+1+yOffset,enabled ? breakPoint : breakPointDisable,32,32,0,0,DI_NORMAL);
		}
		SetTextColor(hdc,textColor);

		char addressText[64];
		getDisasmAddressText(address,addressText,true,line.type == DISTYPE_OPCODE);
		TextOutA(hdc,pixelPositions.addressStart,rowY1+2,addressText,(int)strlen(addressText));
		
		if (isInInterval(address,line.totalSize,debugger->getPC()))
		{
			TextOut(hdc,pixelPositions.opcodeStart-8,rowY1,L"■",1);
		}

		// display whether the condition of a branch is met
		if (line.info.isConditional && address == debugger->getPC())
		{
			line.params += line.info.conditionMet ? "  ; true" : "  ; false";
		}

		drawArguments(hdc, line, pixelPositions.argumentsStart, rowY1 + 2, textColor, currentArguments);
			
		SelectObject(hdc,boldfont);
		TextOutA(hdc,pixelPositions.opcodeStart,rowY1+2,line.name.c_str(),(int)line.name.size());
		SelectObject(hdc,font);

		address += line.totalSize;
	}

	std::vector<BranchLine> branchLines = manager.getBranchLines(windowStart,address-windowStart);
	for (size_t i = 0; i < branchLines.size(); i++)
	{
		drawBranchLine(hdc,addressPositions,branchLines[i]);
	}

	SelectObject(hdc,oldFont);
	SelectObject(hdc,oldPen);
	SelectObject(hdc,oldBrush);

	// copy bitmap to the actual hdc
	BitBlt(actualHdc, 0, 0, rect.right, rect.bottom, hdc, 0, 0, SRCCOPY);
	DeleteObject(hBM);
	DeleteDC(hdc);

	DeleteObject(nullPen);

	DeleteObject(nullBrush);
	DeleteObject(currentBrush);
	
	DestroyIcon(breakPoint);
	DestroyIcon(breakPointDisable);
	
	EndPaint(wnd, &ps);
}
Exemplo n.º 29
0
/* Функция обработки сообщения окна.
 * АРГУМЕНТЫ:
 *   - дескриптор окна:
 *       HWND hWnd;
 *   - номер сообщения (см. WM_***):
 *       UINT Msg;
 *   - параметр сообшения ('word parameter'):
 *       WPARAM wParam;
 *   - параметр сообшения ('long parameter'):
 *       LPARAM lParam;
 * ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ:
 *   (LRESULT) - в зависимости от сообщения.
 */
LRESULT CALLBACK MyWindowFunc( HWND hWnd, UINT Msg,
                               WPARAM wParam, LPARAM lParam )
{ 
  HDC hDC;
  PAINTSTRUCT ps;
  SYSTEMTIME st;
  static INT w, h;
  static BITMAP bm;
  static HDC hMemDC, hMemDCClock;
  static HBITMAP hBm, hBmClock;

  switch (Msg)
  {
  case WM_CREATE:
    SetTimer(hWnd, 1, 100, NULL);
    hBmClock = LoadImage(NULL, "clock2.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
    GetObject(hBmClock, sizeof(bm), &bm);

    hDC = GetDC(hWnd);
    hMemDC = CreateCompatibleDC(hDC);
    hMemDCClock = CreateCompatibleDC(hDC);
    ReleaseDC(hWnd, hDC);

    SelectObject(hMemDCClock, hBmClock);
    return 0;

  case WM_SIZE:
    w = LOWORD(lParam);
    h = HIWORD(lParam);

    if(hBm != NULL)
      DeleteObject(hBm);

    hDC = GetDC(hWnd);
    hBm = CreateCompatibleBitmap(hDC, w, h);
    ReleaseDC(hWnd, hDC);

    SelectObject(hMemDC, hBm);
    SendMessage(hWnd, WM_TIMER, 1, 0);
    return 0;
  
  case WM_TIMER:
    //SelectObject(hMemDC, GetStockObject(NULL_PEN));
    SelectObject(hMemDC, GetStockObject(DC_BRUSH));
    SetDCBrushColor(hMemDC, RGB(255, 255, 255));
    Rectangle(hMemDC, 0, 0, w + 1, h + 1);

    StretchBlt(hMemDC, 0, 0, w, h,
      hMemDCClock, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY);

    Ellipse(hMemDC, 10, 10, h / 2, h / 2);
    
    GetLocalTime(&st);
    DrawArrow(hMemDC, w / 2, h / 2, 300, st.wSecond * 6);
    DrawArrow(hMemDC, w / 2, h / 2, 250, st.wMinute * 6);
    DrawArrow(hMemDC, w / 2, h / 2, 150, (st.wHour % 12) * 30);



    InvalidateRect(hWnd, NULL, TRUE);
    return 0;

  case WM_PAINT:
    hDC = BeginPaint(hWnd, &ps);
    BitBlt(hDC, 0, 0, w, h, hMemDC, 0, 0, SRCCOPY);
    EndPaint(hWnd, &ps);
    return 0;

  case WM_ERASEBKGND:
    BitBlt((HDC)wParam, 0, 0, w, h, hMemDC, 0, 0, SRCCOPY);
    return 0;

  /*case WM_CLOSE:
    if (MessageBox(hWnd, "Are you shure to exit from program?",
          "Exit", MB_YESNO | MB_ICONQUESTION) == IDNO)
      return 0;
    break;  */
  
  case WM_DESTROY:
    DeleteObject(hBm);
    DeleteDC(hMemDC);
    DeleteDC(hMemDCClock);
    DeleteObject(hBmClock);
    KillTimer(hWnd, 1);
    PostQuitMessage(0);
    return 0;
  }
  return DefWindowProc(hWnd, Msg, wParam, lParam);
} /* End of 'MyWindowFunc' function */
Exemplo n.º 30
0
void VSyncWin::VSyncInit()
{
	Self = this;

	CoInitialize(NULL);

	HRESULT hr;
	//hr = CreateDXGIFactory2(__uuidof(IDXGIFactory1), (void**)(&pFactory));

	//if (FAILED(hr))
	//{
	//	exit(0);
	//}
	//UINT i = 0;
	////IDXGIAdapter1*> vAdapters;

	//while (pFactory->EnumAdapters1(i, &m_pAdapter) != DXGI_ERROR_NOT_FOUND)
	//{
	//	//vAdapters.push_back(pAdapter);
	//	//pAdapter->EnumOutputs()
	//	++i;
	//	break; //we want the first adapter
	//}

	//if (m_pAdapter->EnumOutputs(0, &m_pOutput) == DXGI_ERROR_NOT_FOUND)
	//{
	//	//error
	//	exit(0);
	//}

	RECT rc;
	GetClientRect(gHwnd, &rc);
	UINT width = rc.right - rc.left;
	UINT height = rc.bottom - rc.top;

	// for d2d support.. make it 0 not work
	UINT createDeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;


	D3D_DRIVER_TYPE driverTypes[] =
	{
		D3D_DRIVER_TYPE_HARDWARE,
		D3D_DRIVER_TYPE_WARP,
		D3D_DRIVER_TYPE_REFERENCE,
	};
	UINT numDriverTypes = ARRAYSIZE(driverTypes);

	D3D_FEATURE_LEVEL featureLevels[] =
	{
		D3D_FEATURE_LEVEL_11_1,
		D3D_FEATURE_LEVEL_11_0,
		D3D_FEATURE_LEVEL_10_1,
		D3D_FEATURE_LEVEL_10_0,
		D3D_FEATURE_LEVEL_9_3,
		D3D_FEATURE_LEVEL_9_2,
		D3D_FEATURE_LEVEL_9_1
	};
	UINT numFeatureLevels = ARRAYSIZE(featureLevels);

	for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
	{
		mDriverType = driverTypes[driverTypeIndex];
		hr = D3D11CreateDevice(nullptr, mDriverType, nullptr, createDeviceFlags, featureLevels, numFeatureLevels,
			D3D11_SDK_VERSION, &m_pD3dDevice, &mFeatureLevel, &m_pImmediateContext);

		if (hr == E_INVALIDARG)
		{
			// DirectX 11.0 platforms will not recognize D3D_FEATURE_LEVEL_11_1 so we need to retry without it
			hr = D3D11CreateDevice(nullptr, mDriverType, nullptr, createDeviceFlags, &featureLevels[1], numFeatureLevels - 1,
				D3D11_SDK_VERSION, &m_pD3dDevice, &mFeatureLevel, &m_pImmediateContext);
		}

		if (SUCCEEDED(hr))
			break;
	}
	if (FAILED(hr))
		exit(0);
	
	
	const double rate = 1000 / 60.0;
	mSoftwareVsyncRate = FromMilliseconds(rate);
	mPrevVsync = Now();

	/*hr = pFactory->CreateSwapChain(m_pD3dDevice, &scd, &m_pSwapChain);

	if ( FAILED(hr) )
		exit(0);
*/
	
	hr = m_pD3dDevice->QueryInterface(__uuidof(IDXGIDevice2), (void **)&m_pDXGIDevice);

	if (FAILED(hr))
	{
		exit(0);
	}

	IDXGIAdapter * pDXGIAdapter;
	hr = m_pDXGIDevice->GetParent(__uuidof(IDXGIAdapter), (void **)&pDXGIAdapter);

	if (FAILED(hr))
	{
		exit(0);
	}

	pDXGIAdapter->GetParent(__uuidof(IDXGIFactory2), (void **)&	pFactory);


	if (FAILED(hr))
	{
		exit(0);
	}


	hr = pFactory->EnumAdapters1(0, &m_pAdapter);
	if (FAILED(hr))
		exit(0);

	hr = m_pAdapter->EnumOutputs(0, &m_pOutput);
	if (FAILED(hr))
		exit(0);

	DXGI_OUTPUT_DESC desc;
	hr = m_pOutput->GetDesc(&desc);
	if (FAILED(hr))
		exit(0);

	RECT r;
	GetClientRect(gHwnd, &r);

	gHeight = r.bottom - r.top;
	gWidth = r.right - r.left;
	DXGI_SWAP_CHAIN_DESC1 scd = { 0 };
	//scd.BufferDesc.Width = gWidth;
	//scd.BufferDesc.Height = gHeight;
	//scd.BufferDesc.RefreshRate.Numerator = 60;
	//scd.BufferDesc.RefreshRate.Denominator = 1;
	//scd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
	//scd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	//scd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	//scd.SampleDesc.Count = 1;
	//scd.SampleDesc.Quality = 0;

	//scd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	//scd.BufferCount = 3; //1
	//scd.OutputWindow = gHwnd;
	//scd.Windowed = true;
	//scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;// DXGI_SWAP_EFFECT_SEQUENTIAL;//DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
	//scd.Flags = DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE;
	scd.BufferUsage = DXGI_USAGE_BACK_BUFFER | DXGI_USAGE_RENDER_TARGET_OUTPUT;    // how the swap chain should be used
	scd.BufferCount = 3;                                  // a front buffer and a back buffer
	scd.Format = DXGI_FORMAT_B8G8R8A8_UNORM;              // the most common swap chain format
	scd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;    // the recommended flip mode
	scd.SampleDesc.Count = 1;
	scd.Scaling = DXGI_SCALING_NONE;
	scd.Flags = DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE;
	scd.Width = gWidth;
	scd.Height = gHeight;
	hr = pFactory->CreateSwapChainForHwnd(m_pD3dDevice, gHwnd, &scd, NULL, NULL, &m_pSwapChain);

	if (FAILED(hr))
	{
		exit(0);
	}

	hr = m_pSwapChain->GetBuffer(0, __uuidof(m_pBackBuffer), reinterpret_cast<void**>(&m_pBackBuffer));
	if (FAILED(hr))
		exit(0);

	hr = m_pD3dDevice->CreateRenderTargetView(m_pBackBuffer, NULL, &m_pRenderTarget ); 
	if (FAILED(hr))
		exit(0);

	m_pImmediateContext->OMSetRenderTargets(1, &m_pRenderTarget, NULL);

	DXGI_MODE_DESC requestedMode;
	requestedMode.Width = gWidth;
	requestedMode.Height = gHeight;
	requestedMode.RefreshRate.Numerator = 0;
	requestedMode.RefreshRate.Denominator = 0;
	requestedMode.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
	requestedMode.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
	requestedMode.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

	DXGI_MODE_DESC mode;
	hr = m_pOutput->FindClosestMatchingMode(&requestedMode, &mode, m_pD3dDevice);
	if (FAILED(hr))
		throw - 1;
	
	hr = m_pSwapChain->ResizeTarget(&mode);
	if (FAILED(hr))
		throw -1; 


	mode.RefreshRate.Numerator = 0; 
	mode.RefreshRate.Denominator = 0;
	hr = m_pSwapChain->ResizeTarget(&mode);
	if (FAILED(hr))
		throw - 1;


	D2D1_FACTORY_OPTIONS options;
	ZeroMemory(&options, sizeof(D2D1_FACTORY_OPTIONS));
	hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED,&m_pD2D1Factory);

	if (FAILED(hr))
	{
		exit(0);
	}

	hr = m_pD2D1Factory->CreateDevice(m_pDXGIDevice, &m_pD2D1Device);
	if (FAILED(hr))
	{
		exit(0);
	}

	
	hr = m_pD2D1Device->CreateDeviceContext(
		D2D1_DEVICE_CONTEXT_OPTIONS_NONE,
		&m_pD2DContext
		);
	
	if (FAILED(hr))
	{
		exit(0);
	}
	
	

	// Direct2D needs the dxgi version of the backbuffer surface pointer.

	hr = m_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&m_pDxgiBackBuffer));

	if (FAILED(hr))
		exit(0);

	auto d2dRTProps = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED), 96.0, 96.0);


	/*D2D1_BITMAP_PROPERTIES1 bitmapProperties = D2D1::BitmapProperties1(
		D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
		D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED),
		96.0,
		96.0
		);*/


	// Get a D2D surface from the DXGI back buffer to use as the D2D render target.
	/*hr = m_pD2DContext->CreateBitmapFromDxgiSurface(
		m_pDxgiBackBuffer,
		d2dRTProps,
		&m_pD2DTargetBitmap
		);
	if (FAILED(hr))
		exit(0);*/

	hr = m_pD2D1Factory->CreateDxgiSurfaceRenderTarget(m_pDxgiBackBuffer, &d2dRTProps, &m_pD2DRenderTarget);
	
	if (FAILED(hr))
		exit(0);
	//m_pD2DContext->SetTarget(m_pD2DTargetBitmap);

	//m_pDXGIDevice->SetMaximumFrameLatency(3);

#if 0//VSYNC
	//Creating a thread
	std::thread vsync([this] { this->VSyncLoop(); });
	vsync.detach();
#endif

#if 0//USING_DWM_FLUSH
	std::thread VSyncBlit([this] { this->BlittingThread(); });
	VSyncBlit.detach();
#endif

	HDC hdc = GetDC(gHwnd);

	mDCBitmap1 = CreateCompatibleDC(hdc);
	mDCBitmap2 = CreateCompatibleDC(hdc);
	mDCBitmap3 = CreateCompatibleDC(hdc);

	//HDC hdc = GetDC(hWnd);

	RECT rect;
	GetWindowRect(gHwnd, &rect);

	gWidth = rect.right - rect.left;
	gHeight = rect.bottom - rect.top;
	mBitmap1 = CreateCompatibleBitmap(hdc, gWidth, gHeight);
	mBitmap2 = CreateCompatibleBitmap(hdc, gWidth, gHeight);
	mBitmap3 = CreateCompatibleBitmap(hdc, gWidth, gHeight);

	SelectObject(mDCBitmap1, mBitmap1);
	SelectObject(mDCBitmap2, mBitmap2);
	SelectObject(mDCBitmap3, mBitmap3);

	DeleteDC(hdc);


	InitializeThreadpoolEnvironment(&mCallBackEnviron);

	mPool = CreateThreadpool(NULL);

	if (NULL == mPool) {
		OutputDebugStringA("CreateThreadpool failed. LastError: %u\n");
		exit(0);
	}

	//SetThreadpoolThreadMaximum(mPool, 1);
	//SetThreadpoolCallbackPool(&mCallBackEnviron, mPool);

}