コード例 #1
1
bool WindowsCursorShapeGrabber::grabPixels(const PixelFormat *pixelFormat)
{
  HCURSOR hCursor = getHCursor();
  if (hCursor == 0) {
    return false;
  }
  m_lastHCursor = hCursor;

  // Get bitmap mask
  ICONINFO iconInfo;
  if (!GetIconInfo(hCursor, &iconInfo)) {
    return false;
  }

  if (iconInfo.hbmMask == NULL) {
    return false;
  }

  bool isColorShape = (iconInfo.hbmColor != NULL);

  BITMAP bmMask;
  if (!GetObject(iconInfo.hbmMask, sizeof(BITMAP), (LPVOID)&bmMask)) {
    DeleteObject(iconInfo.hbmMask);
    return false;
  }

  if (bmMask.bmPlanes != 1 || bmMask.bmBitsPixel != 1) {
    DeleteObject(iconInfo.hbmMask);
    return false;
  }

  m_cursorShape.setHotSpot(iconInfo.xHotspot, iconInfo.yHotspot);

  int width = bmMask.bmWidth;
  int height = isColorShape ? bmMask.bmHeight : bmMask.bmHeight/2;
  int widthBytes = bmMask.bmWidthBytes;

  const FrameBuffer *pixels= m_cursorShape.getPixels();

  m_cursorShape.setProperties(&Dimension(width, height), pixelFormat);

  std::vector<char> maskBuff(widthBytes * bmMask.bmHeight);
  if (maskBuff.empty()) {
    DeleteObject(iconInfo.hbmMask);
    return true;
  }
  char *mask = &maskBuff.front();

  // FIXME: Use try-catch block to escape code duplication
  // and free resources on an error.

  bool result = GetBitmapBits(iconInfo.hbmMask,
                              widthBytes * bmMask.bmHeight,
                              mask) != 0;

  DeleteObject(iconInfo.hbmMask);
  if (!result) {
    return false;
  }

  // Get cursor pixels
  HDC screenDC = GetDC(0);
  if (screenDC == NULL) {
    return false;
  }

  Screen::BMI bmi;
  try {
    m_screen.getBMI(&bmi, screenDC);
  } catch (...) {
    return false;
  }

  bmi.bmiHeader.biBitCount = pixelFormat->bitsPerPixel;
  bmi.bmiHeader.biWidth = width;
  bmi.bmiHeader.biHeight = -height;
  bmi.bmiHeader.biCompression = BI_BITFIELDS;
  bmi.red   = pixelFormat->redMax   << pixelFormat->redShift;
  bmi.green = pixelFormat->greenMax << pixelFormat->greenShift;
  bmi.blue  = pixelFormat->blueMax  << pixelFormat->blueShift;

  HDC destDC = CreateCompatibleDC(NULL);
  if (destDC == NULL) {
    DeleteDC(screenDC);
    return false;
  }

  void *buffer;
  HBITMAP hbmDIB = CreateDIBSection(destDC, (BITMAPINFO *) &bmi, DIB_RGB_COLORS, &buffer, NULL, NULL);
  if (hbmDIB == 0) {
    DeleteDC(destDC);
    DeleteDC(screenDC);
    return false;
  }

  HBITMAP hbmOld = (HBITMAP)SelectObject(destDC, hbmDIB);

  result = DrawIconEx(destDC, 0, 0, hCursor, 0, 0, 0, NULL, DI_IMAGE) != 0;

  memcpy(pixels->getBuffer(), buffer, pixels->getBufferSize());

  if (!isColorShape) {
    WinCursorShapeUtils::winMonoShapeToRfb(pixels, mask, mask + widthBytes * height);
  } else {
    if (pixels->getBitsPerPixel() == 32) {
      if (WinCursorShapeUtils::winColorShapeToRfb<UINT32>(pixels, mask)) {
        // If the alpha channel is presented.
        WinCursorShapeUtils::fixAlphaChannel(pixels, mask, false);
      }
    } else if (pixels->getBitsPerPixel() == 16) {
      WinCursorShapeUtils::winColorShapeToRfb<UINT16>(pixels, mask);
    }
  }

  m_cursorShape.assignMaskFromWindows(mask);

  SelectObject(destDC, hbmOld);
  DeleteObject(hbmDIB);
  DeleteDC(destDC);
  DeleteDC(screenDC);

  return result;
}
コード例 #2
0
ファイル: nsGLPbufferWGL.cpp プロジェクト: AllenDou/firefox
PRBool
nsGLPbufferWGL::Init(nsCanvasRenderingContextGLPrivate *priv)
{
    // XXX lookup SYSTEM32 path!
    char *opengl32 = "C:\\WINDOWS\\SYSTEM32\\OPENGL32.DLL";

    if (!gWGLWrap.OpenLibrary(opengl32))
        return PR_FALSE;

    gWGLWrap.SetLookupFunc((LibrarySymbolLoader::PlatformLookupFunction) wglGetProcAddress);

    mPriv = priv;
    
    WNDCLASS wc;
    PIXELFORMATDESCRIPTOR pfd;

    if (!GetClassInfo(GetModuleHandle(NULL), "GLEW", &wc)) {
        ZeroMemory(&wc, sizeof(WNDCLASS));
        wc.hInstance = GetModuleHandle(NULL);
        wc.lpfnWndProc = DefWindowProc;
        wc.lpszClassName = "GLEW";

        if (!RegisterClass(&wc)) {
            LogMessage(NS_LITERAL_CSTRING("Canvas 3D: RegisterClass failed"));
            return PR_FALSE;
        }
    }

    // create window
    mGlewWindow = CreateWindow("GLEW", "GLEW", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 
                               CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL);
    if (!mGlewWindow) {
        LogMessage(NS_LITERAL_CSTRING("Canvas 3D: CreateWindow failed"));
        return PR_FALSE;
    }

    // get the device context
    mGlewDC = GetDC(mGlewWindow);
    if (!mGlewDC) {
        LogMessage(NS_LITERAL_CSTRING("Canvas 3D: GetDC failed"));
        return PR_FALSE;
    }

    // find default pixel format
    ZeroMemory(&pfd, sizeof(PIXELFORMATDESCRIPTOR));
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL;
    int pixelformat = ChoosePixelFormat(mGlewDC, &pfd);

    // set the pixel format for the dc
    if (!SetPixelFormat(mGlewDC, pixelformat, &pfd)) {
        LogMessage(NS_LITERAL_CSTRING("Canvas 3D: SetPixelFormat failed"));
        return PR_FALSE;
    }

    // create rendering context
    mGlewWglContext = wglCreateContext(mGlewDC);
    if (!mGlewWglContext) {
        LogMessage(NS_LITERAL_CSTRING("Canvas 3D: wglCreateContext failed"));
        return PR_FALSE;
    }

    if (!wglMakeCurrent(mGlewDC, (HGLRC) mGlewWglContext)) {
        LogMessage(NS_LITERAL_CSTRING("Canvas 3D: wglMakeCurrent failed"));
        return PR_FALSE;
    }

    // grab all the wgl extension pieces that we couldn't grab before
    // we had a context
    if (!gWGLWrap.Init())
        return PR_FALSE;

    // XXX look up system32 dir
    if (!mGLWrap.OpenLibrary(opengl32)) {
        LogMessage(NS_LITERAL_CSTRING("Canvas 3D: Failed to open opengl32.dll (only looked in c:\\windows\\system32, fixme)"));
        return PR_FALSE;
    }

    mGLWrap.SetLookupFunc((LibrarySymbolLoader::PlatformLookupFunction) wglGetProcAddress);

    if (!mGLWrap.Init(GLES20Wrap::TRY_NATIVE_GL)) {
        LogMessage(NS_LITERAL_CSTRING("Canvas 3D: GLWrap init failed"));
        return PR_FALSE;
    }

    return PR_TRUE;
}
コード例 #3
0
ファイル: font.c プロジェクト: pstrealer/wine
static void test_logfont(void)
{
    LOGFONTA lfa, lfa2;
    GpFont *font;
    GpStatus stat;
    GpGraphics *graphics;
    HDC hdc = GetDC(0);
    INT style;

    GdipCreateFromHDC(hdc, &graphics);
    memset(&lfa, 0, sizeof(LOGFONTA));
    memset(&lfa2, 0xff, sizeof(LOGFONTA));

    /* empty FaceName */
    lfa.lfFaceName[0] = 0;
    stat = GdipCreateFontFromLogfontA(hdc, &lfa, &font);
    expect(NotTrueTypeFont, stat);

    lstrcpyA(lfa.lfFaceName, "Arial");

    stat = GdipCreateFontFromLogfontA(hdc, &lfa, &font);
    if (stat == FileNotFound)
    {
        skip("Arial not installed.\n");
        return;
    }
    expect(Ok, stat);
    stat = GdipGetLogFontA(font, graphics, &lfa2);
    expect(Ok, stat);

    ok(lfa2.lfHeight < 0, "Expected negative height\n");
    expect(0, lfa2.lfWidth);
    expect(0, lfa2.lfEscapement);
    expect(0, lfa2.lfOrientation);
    ok((lfa2.lfWeight >= 100) && (lfa2.lfWeight <= 900), "Expected weight to be set\n");
    expect(0, lfa2.lfItalic);
    expect(0, lfa2.lfUnderline);
    expect(0, lfa2.lfStrikeOut);
    expect(GetTextCharset(hdc), lfa2.lfCharSet);
    expect(0, lfa2.lfOutPrecision);
    expect(0, lfa2.lfClipPrecision);
    expect(0, lfa2.lfQuality);
    expect(0, lfa2.lfPitchAndFamily);

    GdipDeleteFont(font);

    memset(&lfa, 0, sizeof(LOGFONTA));
    lfa.lfHeight = 25;
    lfa.lfWidth = 25;
    lfa.lfEscapement = lfa.lfOrientation = 50;
    lfa.lfItalic = lfa.lfUnderline = lfa.lfStrikeOut = TRUE;

    memset(&lfa2, 0xff, sizeof(LOGFONTA));
    lstrcpyA(lfa.lfFaceName, "Arial");

    stat = GdipCreateFontFromLogfontA(hdc, &lfa, &font);
    expect(Ok, stat);
    stat = GdipGetLogFontA(font, graphics, &lfa2);
    expect(Ok, stat);

    ok(lfa2.lfHeight < 0, "Expected negative height\n");
    expect(0, lfa2.lfWidth);
    expect(0, lfa2.lfEscapement);
    expect(0, lfa2.lfOrientation);
    ok((lfa2.lfWeight >= 100) && (lfa2.lfWeight <= 900), "Expected weight to be set\n");
    expect(TRUE, lfa2.lfItalic);
    expect(TRUE, lfa2.lfUnderline);
    expect(TRUE, lfa2.lfStrikeOut);
    expect(GetTextCharset(hdc), lfa2.lfCharSet);
    expect(0, lfa2.lfOutPrecision);
    expect(0, lfa2.lfClipPrecision);
    expect(0, lfa2.lfQuality);
    expect(0, lfa2.lfPitchAndFamily);

    stat = GdipGetFontStyle(font, &style);
    expect(Ok, stat);
    ok (style == (FontStyleItalic | FontStyleUnderline | FontStyleStrikeout),
        "Expected , got %d\n", style);

    GdipDeleteFont(font);

    GdipDeleteGraphics(graphics);
    ReleaseDC(0, hdc);
}
コード例 #4
0
ファイル: Wbrwline.old.c プロジェクト: azulae/Gestool
CLIPPER WBRWPANE( PARAMS ) // ( hWnd, hDC, Self, bLine, aSizes, nFirstItem,
                   //   nClrFore, nClrBack, hFont, aJustify, nStyle
                   //   lCellStyle, lFocused ) -> nRowsSkipped
                   //   bTextColor, bBkColor, nClrLine, nColorFondo, bFont ) // New's by CesoTech
{
   HWND hWnd        = _parni( 1 );
   HDC hDC          = _parni( 2 );
   WORD wRows;
   WORD wLastBottom = 0;
   WORD wRow        = 1;
   WORD wSkipped    = 1;
   PCLIPVAR Self    = _param( 3, -1 );
   PCLIPVAR bLine   = _param( 4, -1 );
   PCLIPVAR pASizes = _param( 5, -1 );
   HFONT hFont      = _parni( 9 );
   HFONT hOldFont;
   BOOL bDestroyDC  = FALSE;
   WORD wHeight ;
   RECT rct, box, client;
   WORD wIndex      = _parni( 6 );
   PCLIPVAR bClrFore = 0, bClrBack = 0;
   COLORREF clrFore = 0;
   COLORREF clrBack = 0;
   HPEN hGrayPen    = CreatePen( PS_SOLID, 1, GetSysColor( COLOR_BTNSHADOW ) ) ; // RGB( 128, 128, 128 ) );
   HPEN hWhitePen   = CreatePen( PS_SOLID, 1, GetSysColor( COLOR_BTNHIGHLIGHT ) ); // GetStockObject( WHITE_PEN );
   BOOL bColBlock   = pASizes->wType & BLOCK;
   PCLIPVAR pAJustify = ISARRAY( 10 ) ? _param( 10, -1 ): 0;
   WORD nHeightCtrl ; // by CeSoTech
   WORD nStyle = _parni( 11 );



   if( PCOUNT() > 6 )
   {
      if( ISBLOCK( 7 ) )
         bClrFore = _param( 7, -1 );
      else
         clrFore = _parnl( 7 );
   }

   if( PCOUNT() > 7 )
   {
      if( ISBLOCK( 8 ) )
      {
         bClrBack = _param( 8, -1 );
         _cEval0( bClrBack );
         clrBack = _parnl( -1 );
      }
      else
         clrBack = _parnl( 8 );
   }

   if( ! hDC )
   {
      bDestroyDC = TRUE;
      hDC = GetDC( hWnd );
   }

   if( ! pSkip )
       pSkip = _Get_Sym( "SKIP" );

   if( hFont )
      hOldFont = SelectObject( hDC, hFont );

   /////////////////////////
   // Borremos el Area de la derecha no coubierta
   if ( !bAdjBrowse && !bAdjLastCol )
   {
       GetClientRect( hWnd, &rct );
       SetBkColor( hDC, _parnl( 17 ) ) ;

       for( wIndex=wIndex ; wIndex <= _parinfa( 5, NULL); wIndex++ )
       {
            rct.left += _parni( 5, wIndex ) ;
       }

       if ( !(nStyle == 0 || nStyle == 7 || nStyle == 8 || nStyle == 3) )
          rct.left++;

       ExtTextOut( hDC, rct.left, rct.top, ETO_OPAQUE | ETO_CLIPPED,
                   &rct, "", 0, 0 );

       wIndex = _parni( 6 );
       GetClientRect( hWnd, &rct );
   }
   /////////////////////////

   GetClientRect( hWnd, &client );

   nHeightCtrl = client.bottom-client.top ; // by CeSoTech

   wHeight = wLineHeight + 1 ;

   wRows = WBrwRowsC( hWnd, hDC, hFont );

   if( ! bClrFore )
      SetTextColor( hDC, clrFore );
      SetBkColor( hDC, clrBack );

   while( wRow <= wRows && wSkipped == 1 )
   {
      rct.top    = client.top + ( bDrawHeaders ? wHeaderHeight+1 : 0 ) +
                   (wHeight * (wRow-1) ) ;

      rct.bottom = rct.top + wHeight;
      rct.left   = 0;
      rct.right  = client.right;

      _cEval0( bLine );
      _xPushM( _eval );

      if( bClrFore )
      {
         _cEval0( bClrFore );
         SetTextColor( hDC, _parnl( -1 ) );
      }

      if( bClrBack )
      {
         _cEval0( bClrBack );
         SetBkColor( hDC, _parnl( -1 ) );
      }


      if( bColBlock )
         _cEval0( pASizes );

      PaintTheLine( hDC, &rct, wIndex, _tos, //// _eval,
                    ( bColBlock ? _eval : pASizes ),
                    hWhitePen, hGrayPen,
                    bColBlock, pAJustify, 0, FALSE, _parni( 11 ),
                    _parni ( 12 ), _parl( 13 ),
                    ISBLOCK( 14 ) ? _param( 14, -1 ) : 0,   // CeSoTech
                    ISBLOCK( 15 ) ? _param( 15, -1 ) : 0,   // CeSoTech
                    wRow, nHeightCtrl,                      // CeSoTech
                    ISNUM( 16 ) ? _parnl( 16 ) : -1,        // CeSoTech
                    FALSE, FALSE,                           // CeSoTech
                    ISBLOCK( 18 ) ? _param( 18, -1 ) : 0,   // CeSoTech
                    FALSE ) ;

      wLastBottom = rct.bottom ;

      _tos--;

      _PutSym( pSkip );
      _xPushM( Self );
      _PutQ( 1 );
      _xSend( 1 );
      wSkipped = _parni( -1 );

      if( wSkipped == 1 )
          wRow++;
   }

   ////////////////////////
   // Borremos el Area de Abajo no cubierta
   GetClientRect( hWnd, &rct );
   SetBkColor( hDC, _parnl( 17 ) ) ;

   rct.top = wLastBottom + 1 ;
   if ( wLastBottom == 0 ) // No Mostro Registros
      rct.top = ( bDrawHeaders ? wHeaderHeight+1 : 0 ) ;
   
   rct.bottom-=  1 + ( bDrawFooters ? wFooterHeight+1 : 0 ) ;

   if (nStyle == 0 || nStyle == 5 || nStyle == 6 ||
       nStyle == 9 || nStyle == 10 || nStyle == 3 )
      rct.top--;

   if ( !bDrawFooters )
      rct.bottom++;


   if ( rct.top < rct.bottom )
   {
      ExtTextOut( hDC, rct.left, rct.top, ETO_OPAQUE | ETO_CLIPPED,
                  &rct, "", 0, 0 );
   }
   ////////////////////////

   DeleteObject( hGrayPen );
   DeleteObject( hWhitePen );

   if( hFont )
      SelectObject( hDC, hOldFont );

   if( bDestroyDC )
       ReleaseDC( hWnd, hDC );

   _retni( wRow );

}
コード例 #5
0
ファイル: Wbrwline.old.c プロジェクト: azulae/Gestool
CLIPPER WBRWLINE( PARAMS ) // ( hWnd, hDC, nRow, aText, aSizes, nFirstItem, ;
                   // nClrFore, nClrBack, hFont, lTree, aJustify, nPressed,
                   // nStyle, nColAct, lFocused )
                   // bTextColor, bBkColor, nClrLine, lFooter, lSelect,
                   // bFont, lDrawFocusRect ) // New's by CesoTech
{
   HWND hWnd        = _parni( 1 );
   HDC hDC          = _parni( 2 );
   WORD wRow        = _parni( 3 );
   BOOL bDestroyDC  = FALSE;
   WORD wHeight;
   RECT rct, box;
   PCLIPVAR bClrFore, bClrBack;
   COLORREF clrFore = 0;
   COLORREF clrBack = 0;
   HPEN hGrayPen    ;
   HPEN hWhitePen   ;
   HFONT hFont      = _parni( 9 );
   HFONT hOldFont;
   BOOL bTree      = _parl( 10 );
   BOOL bFooter = ISLOGICAL( 19 ) ? _parl( 19 ) : FALSE ;  // CeSoTech

   WORD nHeightCtrl ; // by CeSoTech

   hGrayPen    = CreatePen( PS_SOLID, 1, GetSysColor( COLOR_BTNSHADOW ) ) ; // RGB( 128, 128, 128 ) );
   hWhitePen   = CreatePen( PS_SOLID, 1, GetSysColor( COLOR_BTNHIGHLIGHT ) ); // GetStockObject( WHITE_PEN );


   if( PCOUNT() > 6 )
   {
      if( ISBLOCK( 7 ) )
      {
         bClrFore = _param( 7, -1 );
         _cEval0( bClrFore );
         clrFore = _parnl( -1 );
      }
      else
         clrFore = _parnl( 7 );
   }

   if( PCOUNT() > 7 )
   {
      if( ISBLOCK( 8 ) )
      {
         bClrBack = _param( 8, -1 );
         _cEval0( bClrBack );
         clrBack = _parnl( -1 );
      }
      else
         clrBack = _parnl( 8 );
   }

   if( ! hDC )
   {
      bDestroyDC = TRUE;
      hDC = GetDC( hWnd );
   }

   if( hFont )
      hOldFont = SelectObject( hDC, hFont );

   GetClientRect( hWnd, &rct );

   nHeightCtrl = rct.bottom-rct.top ; // by CeSoTech

   SetTextColor( hDC, clrFore );
   SetBkColor( hDC, clrBack );

   wHeight = wLineHeight + 1 ;

   if ( ( wRow == 0 ) && bDrawHeaders )  // Es una Cabecera
      wHeight = wHeaderHeight + 1 ;

   if ( ! bFooter )
   {
      if ( ( wRow == 0 ) && bDrawHeaders )  // Es una Cabecera
      {
         rct.top    = 0 ;
         rct.bottom = wHeaderHeight + 1 ;
      }
      else
      {
        rct.top    = ( bDrawHeaders ? wHeaderHeight+1 : 0 ) + (wHeight * (wRow-1) )  ;
        rct.bottom = ( bDrawHeaders ? wHeaderHeight+1 : 0 ) + (wHeight * wRow)  ;
      }

   } else {
      rct.top    = rct.bottom - (wFooterHeight+1) ;
   }

   rct.left   = 0;

   PaintTheLine( hDC, &rct, _parni( 6 ), _param( 4, -1 ), _param( 5, -1 ),
                 hWhitePen, hGrayPen, bTree,
                 ISARRAY(11) ? _param( 11, -1 ) : 0, _parni( 12 ),
                 (wRow == 0), _parni( 13 ),
                 _parni( 14 ), _parl( 15 ),
                 ISBLOCK( 16 ) ? _param( 16, -1 ) : 0,   // CeSoTech
                 ISBLOCK( 17 ) ? _param( 17, -1 ) : 0,   // CeSoTech
                 wRow, nHeightCtrl,                      // CeSoTech
                 ISNUM( 18 ) ? _parnl( 18 ) : -1,        // CeSoTech
                 bFooter,                                // CeSoTech
                 ISLOGICAL( 20 ) ? _parl( 20 ) : FALSE,  // CeSoTech
                 ISBLOCK( 21 ) ? _param( 21, -1 ) : 0,   // CeSoTech
                 ISLOGICAL( 22 ) ? _parl( 22 ) : FALSE );// CeSoTech

   DeleteObject( hGrayPen );
   DeleteObject( hWhitePen );

   if( hFont )
      SelectObject( hDC, hOldFont );

   if( bDestroyDC )
       ReleaseDC( hWnd, hDC );

   _reta( 2 );
   _storni( rct.top,    -1, 1 );
   _storni( rct.bottom, -1, 2 );

}
コード例 #6
0
ファイル: progress.cpp プロジェクト: Seldom/miranda-ng
INT_PTR CALLBACK ProgressDlgProc(HWND hdlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	static int fontHeight, listWidth;
	static int manualAbort;
	static HFONT hBoldFont = NULL;

	INT_PTR bReturn;
	if (DoMyControlProcessing(hdlg, message, wParam, lParam, &bReturn))
		return bReturn;

	switch (message) {
	case WM_INITDIALOG:
		EnableWindow(GetDlgItem(GetParent(hdlg), IDOK), FALSE);
		hdlgProgress = hdlg;
		hwndStatus = GetDlgItem(hdlg, IDC_STATUS);
		errorCount = 0;
		bShortModeDone = false;
		hwndBar = GetDlgItem(hdlg, IDC_PROGRESS);
		SendMessage(hwndBar, PBM_SETRANGE, 0, MAKELPARAM(0, 1000));
		{
			HDC hdc;
			HFONT hFont, hoFont;
			SIZE s;
			hdc = GetDC(NULL);
			hFont = (HFONT)SendMessage(hdlg, WM_GETFONT, 0, 0);
			hoFont = (HFONT)SelectObject(hdc, hFont);
			GetTextExtentPoint32(hdc, _T("x"), 1, &s);
			SelectObject(hdc, hoFont);
			ReleaseDC(NULL, hdc);
			fontHeight = s.cy;

			RECT rc;
			GetClientRect(GetDlgItem(hdlg, IDC_STATUS), &rc);
			listWidth = rc.right;

			LOGFONT lf;
			GetObject((HFONT)SendDlgItemMessage(hdlg, IDC_STATUS, WM_GETFONT, 0, 0), sizeof(lf), &lf);
			lf.lfWeight = FW_BOLD;
			hBoldFont = CreateFontIndirect(&lf);
		}
		manualAbort = 0;
		hEventRun = CreateEvent(NULL, TRUE, TRUE, NULL);
		hEventAbort = CreateEvent(NULL, TRUE, FALSE, NULL);
		TranslateDialogDefault(hdlg);
		_beginthread(WorkerThread, 0, NULL);
		return TRUE;

	case WM_MEASUREITEM:
		{
			LPMEASUREITEMSTRUCT mis = (LPMEASUREITEMSTRUCT)lParam;
			mis->itemWidth = listWidth;
			mis->itemHeight = fontHeight;
		}
		return TRUE;

	case WM_DRAWITEM:
		TCHAR str[256];
		{
			LPDRAWITEMSTRUCT dis = (LPDRAWITEMSTRUCT)lParam;
			int bold = 0;
			HFONT hoFont = NULL;
			if ((int)dis->itemID == -1) break;
			SendMessage(dis->hwndItem, LB_GETTEXT, dis->itemID, (LPARAM)str);
			switch (dis->itemData & STATUS_CLASSMASK) {
			case STATUS_MESSAGE:
				SetTextColor(dis->hDC, RGB(0, 0, 0));
				break;
			case STATUS_WARNING:
				SetTextColor(dis->hDC, RGB(192, 128, 0));
				break;
			case STATUS_ERROR:
				SetTextColor(dis->hDC, RGB(192, 0, 0));
				break;
			case STATUS_FATAL:
				bold = 1;
				SetTextColor(dis->hDC, RGB(192, 0, 0));
				break;
			case STATUS_SUCCESS:
				bold = 1;
				SetTextColor(dis->hDC, RGB(0, 192, 0));
				break;
			}
			if (bold) hoFont = (HFONT)SelectObject(dis->hDC, hBoldFont);
			ExtTextOut(dis->hDC, dis->rcItem.left, dis->rcItem.top, ETO_CLIPPED | ETO_OPAQUE, &dis->rcItem, str, (UINT)mir_tstrlen(str), NULL);
			if (bold) SelectObject(dis->hDC, hoFont);
		}
		return TRUE;

	case WM_PROCESSINGDONE:
		SetProgressBar(1000);
		if (bShortMode) {
			EnableWindow(GetDlgItem(GetParent(hdlg), IDC_BACK), FALSE);
			EnableWindow(GetDlgItem(GetParent(hdlg), IDOK), FALSE);
			SetDlgItemText(GetParent(hdlg), IDCANCEL, TranslateT("&Finish"));
			bShortModeDone = true;
			if (bAutoExit)
				PostMessage(GetParent(hdlg), WM_COMMAND, IDCANCEL, 0);
		}
		else {
			AddToStatus(STATUS_SUCCESS, TranslateT("Click Next to continue"));
			EnableWindow(GetDlgItem(GetParent(hdlg), IDOK), TRUE);
		}

		if (manualAbort == 1)
			EndDialog(GetParent(hdlg), 0);
		else if (manualAbort == 2) {
			if (opts.bCheckOnly)
				PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_FILEACCESS, (LPARAM)FileAccessDlgProc);
			else {
				PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_CLEANING, (LPARAM)CleaningDlgProc);
				CloseHandle(opts.hOutFile);
				opts.hOutFile = NULL;
			}
			break;
		}
		break;

	case WZN_CANCELCLICKED:
		if (bShortModeDone) {
			if (!errorCount) {
				if (bLaunchMiranda)
					CallService(MS_DB_SETDEFAULTPROFILE, (WPARAM)opts.filename, 0);
				wizardResult = 1;
			}
			return TRUE;
		}

		ResetEvent(hEventRun);
		if (IsWindowEnabled(GetDlgItem(GetParent(hdlg), IDOK)))
			break;

		if (MessageBox(hdlg, TranslateT("Processing has not yet completed, if you cancel now then the changes that have currently been made will be rolled back and the original database will be restored. Do you still want to cancel?"), TranslateT("Miranda Database Tool"), MB_YESNO) == IDYES) {
			manualAbort = 1;
			SetEvent(hEventAbort);
		}
		SetEvent(hEventRun);
		SetWindowLongPtr(hdlg, DWLP_MSGRESULT, TRUE);
		return TRUE;

	case WM_COMMAND:
		switch (LOWORD(wParam)) {
		case IDC_BACK:
			ResetEvent(hEventRun);
			if (!IsWindowEnabled(GetDlgItem(GetParent(hdlg), IDOK))) {
				if (MessageBox(hdlg, TranslateT("Processing has not yet completed, if you go back now then the changes that have currently been made will be rolled back and the original database will be restored. Do you still want to go back?"), TranslateT("Miranda Database Tool"), MB_YESNO) == IDYES) {
					manualAbort = 2;
					SetEvent(hEventAbort);
				}
				SetEvent(hEventRun);
				break;
			}
			SetEvent(hEventRun);
			if (opts.bCheckOnly)
				PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_FILEACCESS, (LPARAM)FileAccessDlgProc);
			else
				PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_CLEANING, (LPARAM)CleaningDlgProc);
			break;

		case IDOK:
			PostMessage(GetParent(hdlg), WZM_GOTOPAGE, IDD_FINISHED, (LPARAM)FinishedDlgProc);
			break;
		}
		break;

	case WM_DESTROY:
		if (hEventAbort) {
			CloseHandle(hEventAbort);
			hEventAbort = NULL;
		}
		if (hEventRun) {
			CloseHandle(hEventRun);
			hEventRun = NULL;
		}
		if (hBoldFont) {
			DeleteObject(hBoldFont);
			hBoldFont = NULL;
		}
		break;
	}
	return FALSE;
}
コード例 #7
0
ファイル: win_glimp.cpp プロジェクト: 469486139/DOOM-3-BFG
/*
====================
GLW_InitDriver

Set the pixelformat for the window before it is
shown, and create the rendering context
====================
*/
static bool GLW_InitDriver( glimpParms_t parms ) {
    PIXELFORMATDESCRIPTOR src = 
	{
		sizeof(PIXELFORMATDESCRIPTOR),	// size of this pfd
		1,								// version number
		PFD_DRAW_TO_WINDOW |			// support window
		PFD_SUPPORT_OPENGL |			// support OpenGL
		PFD_DOUBLEBUFFER,				// double buffered
		PFD_TYPE_RGBA,					// RGBA type
		32,								// 32-bit color depth
		0, 0, 0, 0, 0, 0,				// color bits ignored
		8,								// 8 bit destination alpha
		0,								// shift bit ignored
		0,								// no accumulation buffer
		0, 0, 0, 0, 					// accum bits ignored
		24,								// 24-bit z-buffer	
		8,								// 8-bit stencil buffer
		0,								// no auxiliary buffer
		PFD_MAIN_PLANE,					// main layer
		0,								// reserved
		0, 0, 0							// layer masks ignored
    };

	common->Printf( "Initializing OpenGL driver\n" );

	//
	// get a DC for our window if we don't already have one allocated
	//
	if ( win32.hDC == NULL ) {
		common->Printf( "...getting DC: " );

		if ( ( win32.hDC = GetDC( win32.hWnd ) ) == NULL ) {
			common->Printf( "^3failed^0\n" );
			return false;
		}
		common->Printf( "succeeded\n" );
	}

	// the multisample path uses the wgl 
	if ( wglChoosePixelFormatARB ) {
		win32.pixelformat = GLW_ChoosePixelFormat( win32.hDC, parms.multiSamples, parms.stereo );
	} else {
		// this is the "classic" choose pixel format path
		common->Printf( "Using classic ChoosePixelFormat\n" );

		// eventually we may need to have more fallbacks, but for
		// now, ask for everything
		if ( parms.stereo ) {
			common->Printf( "...attempting to use stereo\n" );
			src.dwFlags |= PFD_STEREO;
		}

		//
		// choose, set, and describe our desired pixel format.  If we're
		// using a minidriver then we need to bypass the GDI functions,
		// otherwise use the GDI functions.
		//
		if ( ( win32.pixelformat = ChoosePixelFormat( win32.hDC, &src ) ) == 0 ) {
			common->Printf( "...^3GLW_ChoosePFD failed^0\n");
			return false;
		}
		common->Printf( "...PIXELFORMAT %d selected\n", win32.pixelformat );
	}

	// get the full info
	DescribePixelFormat( win32.hDC, win32.pixelformat, sizeof( win32.pfd ), &win32.pfd );
	glConfig.colorBits = win32.pfd.cColorBits;
	glConfig.depthBits = win32.pfd.cDepthBits;
	glConfig.stencilBits = win32.pfd.cStencilBits;

	// XP seems to set this incorrectly
	if ( !glConfig.stencilBits ) {
		glConfig.stencilBits = 8;
	}

	// the same SetPixelFormat is used either way
	if ( SetPixelFormat( win32.hDC, win32.pixelformat, &win32.pfd ) == FALSE ) {
		common->Printf( "...^3SetPixelFormat failed^0\n", win32.hDC );
		return false;
	}

	//
	// startup the OpenGL subsystem by creating a context and making it current
	//
	common->Printf( "...creating GL context: " );
	win32.hGLRC = CreateOpenGLContextOnDC( win32.hDC, r_debugContext.GetBool() );
	if ( win32.hGLRC == 0 ) {
		common->Printf( "^3failed^0\n" );
		return false;
	}
	common->Printf( "succeeded\n" );

	common->Printf( "...making context current: " );
	if ( !qwglMakeCurrent( win32.hDC, win32.hGLRC ) ) {
		qwglDeleteContext( win32.hGLRC );
		win32.hGLRC = NULL;
		common->Printf( "^3failed^0\n" );
		return false;
	}
	common->Printf( "succeeded\n" );

	return true;
}
コード例 #8
0
ファイル: palette.c プロジェクト: rmallof/reactos
LRESULT CALLBACK
PalWinProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
        case WM_PAINT:
        {
            RECT rc = { 0, 0, 31, 32 };
            HDC hDC = GetDC(hwnd);
            HPEN oldPen;
            HBRUSH oldBrush;
            int i, a, b;

            DefWindowProc(hwnd, message, wParam, lParam);

            for(b = 2; b < 30; b++)
                for(a = 2; a < 29; a++)
                    if ((a + b) % 2 == 1)
                        SetPixel(hDC, a, b, GetSysColor(COLOR_BTNHILIGHT));

            DrawEdge(hDC, &rc, EDGE_RAISED, BF_TOPLEFT);
            DrawEdge(hDC, &rc, BDR_SUNKENOUTER, BF_TOPLEFT | BF_BOTTOMRIGHT);
            SetRect(&rc, 11, 12, 26, 27);
            DrawEdge(hDC, &rc, BDR_RAISEDINNER, BF_RECT | BF_MIDDLE);
            oldPen = SelectObject(hDC, CreatePen(PS_NULL, 0, 0));
            oldBrush = SelectObject(hDC, CreateSolidBrush(bgColor));
            Rectangle(hDC, rc.left, rc.top + 2, rc.right - 1, rc.bottom - 1);
            DeleteObject(SelectObject(hDC, oldBrush));
            SetRect(&rc, 4, 5, 19, 20);
            DrawEdge(hDC, &rc, BDR_RAISEDINNER, BF_RECT | BF_MIDDLE);
            oldBrush = SelectObject(hDC, CreateSolidBrush(fgColor));
            Rectangle(hDC, rc.left + 2, rc.top + 2, rc.right - 1, rc.bottom - 1);
            DeleteObject(SelectObject(hDC, oldBrush));
            DeleteObject(SelectObject(hDC, oldPen));

            for(i = 0; i < 28; i++)
            {
                SetRect(&rc, 31 + (i % 14) * 16,
                        0 + (i / 14) * 16, 16 + 31 + (i % 14) * 16, 16 + 0 + (i / 14) * 16);
                DrawEdge(hDC, &rc, EDGE_RAISED, BF_TOPLEFT);
                DrawEdge(hDC, &rc, BDR_SUNKENOUTER, BF_RECT);
                oldPen = SelectObject(hDC, CreatePen(PS_NULL, 0, 0));
                oldBrush = SelectObject(hDC, CreateSolidBrush(palColors[i]));
                Rectangle(hDC, rc.left + 2, rc.top + 2, rc.right - 1, rc.bottom - 1);
                DeleteObject(SelectObject(hDC, oldBrush));
                DeleteObject(SelectObject(hDC, oldPen));
            }
            ReleaseDC(hwnd, hDC);
            break;
        }
        case WM_LBUTTONDOWN:
            if (GET_X_LPARAM(lParam) >= 31)
            {
                fgColor = palColors[(GET_X_LPARAM(lParam) - 31) / 16 + (GET_Y_LPARAM(lParam) / 16) * 14];
                InvalidateRect(hwnd, NULL, FALSE);
            }
            break;
        case WM_RBUTTONDOWN:
            if (GET_X_LPARAM(lParam) >= 31)
            {
                bgColor = palColors[(GET_X_LPARAM(lParam) - 31) / 16 + (GET_Y_LPARAM(lParam) / 16) * 14];
                InvalidateRect(hwnd, NULL, FALSE);
            }
            break;
        case WM_LBUTTONDBLCLK:
            if (GET_X_LPARAM(lParam) >= 31)
                if (ChooseColor(&choosecolor))
                {
                    palColors[(GET_X_LPARAM(lParam) - 31) / 16 + (GET_Y_LPARAM(lParam) / 16) * 14] =
                        choosecolor.rgbResult;
                    fgColor = choosecolor.rgbResult;
                    InvalidateRect(hwnd, NULL, FALSE);
                }
            break;
        case WM_RBUTTONDBLCLK:
            if (GET_X_LPARAM(lParam) >= 31)
                if (ChooseColor(&choosecolor))
                {
                    palColors[(GET_X_LPARAM(lParam) - 31) / 16 + (GET_Y_LPARAM(lParam) / 16) * 14] =
                        choosecolor.rgbResult;
                    bgColor = choosecolor.rgbResult;
                    InvalidateRect(hwnd, NULL, FALSE);
                }
            break;

        default:
            return DefWindowProc(hwnd, message, wParam, lParam);
    }

    return 0;
}
コード例 #9
0
static LONG WINAPI WindowFunc(HWND hWnd,UINT msg,WPARAM wp,LPARAM lp)
{
	switch(msg)
	{
	case WM_QUERYNEWPALETTE:
	case WM_PALETTECHANGED:
		if(NULL!=fsWin32Internal.hPlt)
		{
			SelectPalette(fsWin32Internal.hDC,fsWin32Internal.hPlt,FALSE);
			RealizePalette(fsWin32Internal.hDC);
		}
		return DefWindowProc(hWnd,msg,wp,lp);
	case WM_CREATE:
		fsWin32Internal.hDC=GetDC(hWnd);
		YsSetPixelFormat(fsWin32Internal.hDC);
		fsWin32Internal.hRC=wglCreateContext(fsWin32Internal.hDC);
		wglMakeCurrent(fsWin32Internal.hDC,fsWin32Internal.hRC);
		if(0==doubleBuffer)
		{
			glDrawBuffer(GL_FRONT);
		}
		InitializeOpenGL(hWnd);
		break;
	case WM_SIZE:
		wglMakeCurrent(fsWin32Internal.hDC,fsWin32Internal.hRC);
		break;
	case WM_PAINT:
		wglMakeCurrent(fsWin32Internal.hDC,fsWin32Internal.hRC);
		exposure=1;
		return DefWindowProc(hWnd,msg,wp,lp);
	case WM_COMMAND:
		break;
	case WM_DESTROY:
		exit(1);
		break;
	case WM_MOUSEWHEEL:
		{
			int step;
			step=HIWORD(wp);
			if(step>=0x8000)
			{
				step-=0x10000;
			}
			step/=WHEEL_DELTA;
			if(step>0)
			{
				while(step>0)
				{
					if(nKeyBufUsed<NKEYBUF)
					{
						keyBuffer[nKeyBufUsed++]=FSKEY_WHEELUP;
					}
					step--;
				}
			}
			else if(step<0)
			{
				while(step<0)
				{
					if(nKeyBufUsed<NKEYBUF)
					{
						keyBuffer[nKeyBufUsed++]=FSKEY_WHEELDOWN;
					}
					step++;
				}
			}
		}
		break;
	case WM_SYSKEYDOWN:
		if((lp & (1<<29))!=0 && // Alt
		  (wp==VK_MENU ||
		   wp==VK_OEM_1 ||
		   wp==VK_OEM_PLUS ||
		   wp==VK_OEM_COMMA ||
		   wp==VK_OEM_MINUS ||
		   wp==VK_OEM_PERIOD ||
		   wp==VK_OEM_2 ||
		   wp==VK_OEM_3 ||
		   wp==VK_OEM_4 ||
		   wp==VK_OEM_5 ||
		   wp==VK_OEM_6 ||
		   wp==VK_OEM_7 ||
		   wp==VK_OEM_8 ||
#ifdef VK_OEM_AX
		   wp==VK_OEM_AX ||
#endif
		   wp==VK_OEM_102 ||
		   wp=='0' ||
		   wp=='1' ||
		   wp=='2' ||
		   wp=='3' ||
		   wp=='4' ||
		   wp=='5' ||
		   wp=='6' ||
		   wp=='7' ||
		   wp=='8' ||
		   wp=='9' ||
		   wp=='A' ||
		   wp=='B' ||
		   wp=='C' ||
		   wp=='D' ||
		   wp=='E' ||
		   wp=='F' ||
		   wp=='G' ||
		   wp=='H' ||
		   wp=='I' ||
		   wp=='J' ||
		   wp=='K' ||
		   wp=='L' ||
		   wp=='M' ||
		   wp=='N' ||
		   wp=='O' ||
		   wp=='P' ||
		   wp=='Q' ||
		   wp=='R' ||
		   wp=='S' ||
		   wp=='T' ||
		   wp=='U' ||
		   wp=='V' ||
		   wp=='W' ||
		   wp=='X' ||
		   wp=='Y' ||
		   wp=='Z' ||
		   wp==VK_ESCAPE ||
		   wp==VK_F1 ||
		   wp==VK_F2 ||
		   wp==VK_F3 ||
		   /* wp==VK_F4 || */
		   wp==VK_F5 ||
		   wp==VK_F6 ||
		   wp==VK_F7 ||
		   wp==VK_F8 ||
		   wp==VK_F9 ||
		   wp==VK_F10 ||
		   wp==VK_F11 ||
		   wp==VK_F12 ||
		   wp==VK_RETURN ||
		   wp==VK_NUMLOCK ||
		   wp==VK_NUMPAD0 ||
		   wp==VK_NUMPAD1 ||
		   wp==VK_NUMPAD2 ||
		   wp==VK_NUMPAD3 ||
		   wp==VK_NUMPAD4 ||
		   wp==VK_NUMPAD5 ||
		   wp==VK_NUMPAD6 ||
		   wp==VK_NUMPAD7 ||
		   wp==VK_NUMPAD8 ||
		   wp==VK_NUMPAD9 ||
		   wp==VK_DECIMAL ||
		   wp==VK_DIVIDE ||
		   wp==VK_MULTIPLY ||
		   wp==VK_SUBTRACT ||
		   wp==VK_ADD))
		{
			int keyCode;
			keyCode=fsKeyMapper.VkToFsKey(wp);
			if(keyCode!=0 && nKeyBufUsed<NKEYBUF)
			{
				keyBuffer[nKeyBufUsed++]=keyCode;
			}
			return 0;
		}
		return DefWindowProc(hWnd,msg,wp,lp);
	case WM_SYSKEYUP:
		return 0;
	case WM_KEYDOWN:
		if(nKeyBufUsed<NKEYBUF)
		{
			int keyCode;
			keyCode=fsKeyMapper.VkToFsKey(wp);
			if(keyCode!=0)
			{
				keyBuffer[nKeyBufUsed++]=keyCode;
			}
		}
		break;
	case WM_CHAR:
		if(nCharBufUsed<NKEYBUF)
		{
			charBuffer[nCharBufUsed++]=wp;
		}
		break;
	case WM_ERASEBKGND:
		return 1;

	case WM_LBUTTONDOWN:
	case WM_LBUTTONUP:
	case WM_MBUTTONDOWN:
	case WM_MBUTTONUP:
	case WM_RBUTTONDOWN:
	case WM_RBUTTONUP:
	case WM_MOUSEMOVE:
		if(nMosBufUsed<NKEYBUF)
		{
			int eventType;
			switch(msg)
			{
			default:
				eventType=FSMOUSEEVENT_NONE;
				break;
			case WM_LBUTTONDOWN:
				eventType=FSMOUSEEVENT_LBUTTONDOWN;
				break;
			case WM_LBUTTONUP:
				eventType=FSMOUSEEVENT_LBUTTONUP;
				break;
			case WM_MBUTTONDOWN:
				eventType=FSMOUSEEVENT_MBUTTONDOWN;
				break;
			case WM_MBUTTONUP:
				eventType=FSMOUSEEVENT_MBUTTONUP;
				break;
			case WM_RBUTTONDOWN:
				eventType=FSMOUSEEVENT_RBUTTONDOWN;
				break;
			case WM_RBUTTONUP:
				eventType=FSMOUSEEVENT_RBUTTONUP;
				break;
			case WM_MOUSEMOVE:
				eventType=FSMOUSEEVENT_MOVE;
				break;
			}

			int lb=((wp & MK_LBUTTON)!=0);
			int mb=((wp & MK_MBUTTON)!=0);
			int rb=((wp & MK_RBUTTON)!=0);
			unsigned int shift=((wp & MK_SHIFT)!=0);
			unsigned int ctrl=((wp & MK_CONTROL)!=0);
			int mx=LOWORD(lp);
			int my=HIWORD(lp);

			if(eventType==FSMOUSEEVENT_MOVE &&
			   0<nMosBufUsed &&
			   mosBuffer[nMosBufUsed-1].eventType==FSMOUSEEVENT_MOVE &&
			   mosBuffer[nMosBufUsed-1].lb==lb &&
			   mosBuffer[nMosBufUsed-1].mb==mb &&
			   mosBuffer[nMosBufUsed-1].rb==rb &&
			   mosBuffer[nMosBufUsed-1].shift==shift &&
			   mosBuffer[nMosBufUsed-1].ctrl==ctrl)
			{
				mosBuffer[nMosBufUsed-1].mx=mx;
				mosBuffer[nMosBufUsed-1].my=my;
				break;
			}

			mosBuffer[nMosBufUsed].eventType=eventType;
			mosBuffer[nMosBufUsed].lb=lb;
			mosBuffer[nMosBufUsed].mb=mb;
			mosBuffer[nMosBufUsed].rb=rb;
			mosBuffer[nMosBufUsed].shift=shift;
			mosBuffer[nMosBufUsed].ctrl=ctrl;
			mosBuffer[nMosBufUsed].mx=mx;
			mosBuffer[nMosBufUsed].my=my;
			nMosBufUsed++;
		}
		break;

	default:
		return DefWindowProc(hWnd,msg,wp,lp);
	}
	return 1;
}
コード例 #10
0
ファイル: win_glimp.cpp プロジェクト: Hasimir/jedi-outcast-1
/*
** GLW_InitDriver
**
** - get a DC if one doesn't exist
** - create an HGLRC if one doesn't exist
*/
static qboolean GLW_InitDriver( int colorbits )
{
	int		tpfd;
	int		depthbits, stencilbits;
    static PIXELFORMATDESCRIPTOR pfd;		// save between frames since 'tr' gets cleared

	ri.Printf( PRINT_ALL, "Initializing OpenGL driver\n" );

	//
	// get a DC for our window if we don't already have one allocated
	//
	if ( glw_state.hDC == NULL )
	{
		ri.Printf( PRINT_ALL, "...getting DC: " );

		if ( ( glw_state.hDC = GetDC( g_wv.hWnd ) ) == NULL )
		{
			ri.Printf( PRINT_ALL, "failed\n" );
			return qfalse;
		}
		ri.Printf( PRINT_ALL, "succeeded\n" );
	}

	if ( colorbits == 0 )
	{
		colorbits = glw_state.desktopBitsPixel;
	}

	//
	// implicitly assume Z-buffer depth == desktop color depth
	//
	if ( r_depthbits->integer == 0 ) {
		if ( colorbits > 16 ) {
			depthbits = 24;
		} else {
			depthbits = 16;
		}
	} else {
		depthbits = r_depthbits->integer;
	}

	//
	// do not allow stencil if Z-buffer depth likely won't contain it
	//
	stencilbits = r_stencilbits->integer;
	if ( depthbits < 24 )
	{
		stencilbits = 0;
	}

	//
	// make two attempts to set the PIXELFORMAT
	//

	//
	// first attempt: r_colorbits, depthbits, and r_stencilbits
	//
	if ( !glw_state.pixelFormatSet )
	{
		GLW_CreatePFD( &pfd, colorbits, depthbits, stencilbits, (qboolean)r_stereo->integer );
		if ( ( tpfd = GLW_MakeContext( &pfd ) ) != TRY_PFD_SUCCESS )
		{
			if ( tpfd == TRY_PFD_FAIL_HARD )
			{
				ri.Printf( PRINT_WARNING, "...failed hard\n" );
				return qfalse;
			}

			//
			// punt if we've already tried the desktop bit depth and no stencil bits
			//
			if ( ( r_colorbits->integer == glw_state.desktopBitsPixel ) &&
				 ( stencilbits == 0 ) )
			{
				ReleaseDC( g_wv.hWnd, glw_state.hDC );
				glw_state.hDC = NULL;

				ri.Printf( PRINT_ALL, "...failed to find an appropriate PIXELFORMAT\n" );

				return qfalse;
			}

			//
			// second attempt: desktop's color bits and no stencil
			//
			if ( colorbits > glw_state.desktopBitsPixel )
			{
				colorbits = glw_state.desktopBitsPixel;
			}
			GLW_CreatePFD( &pfd, colorbits, depthbits, 0, (qboolean)r_stereo->integer );
			if ( GLW_MakeContext( &pfd ) != TRY_PFD_SUCCESS )
			{
				if ( glw_state.hDC )
				{
					ReleaseDC( g_wv.hWnd, glw_state.hDC );
					glw_state.hDC = NULL;
				}

				ri.Printf( PRINT_ALL, "...failed to find an appropriate PIXELFORMAT\n" );

				return qfalse;
			}
		}

		/*
		** report if stereo is desired but unavailable
		*/
		if ( !( pfd.dwFlags & PFD_STEREO ) && ( r_stereo->integer != 0 ) ) 
		{
			ri.Printf( PRINT_ALL, "...failed to select stereo pixel format\n" );
			glConfig.stereoEnabled = qfalse;
		}
	}

	/*
	** store PFD specifics 
	*/
	glConfig.colorBits = ( int ) pfd.cColorBits;
	glConfig.depthBits = ( int ) pfd.cDepthBits;
	glConfig.stencilBits = ( int ) pfd.cStencilBits;

	return qtrue;
}
コード例 #11
0
ファイル: win_glimp.cpp プロジェクト: Hasimir/jedi-outcast-1
/*
** GLW_SetMode
*/
static rserr_t GLW_SetMode( int mode, 
							int colorbits, 
							qboolean cdsFullscreen )
{
	HDC hDC;
	const char *win_fs[] = { "W", "FS" };
	int		cdsRet;
	DEVMODE dm;
		
	//
	// print out informational messages
	//
	ri.Printf( PRINT_ALL, "...setting mode %d:", mode );
	if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) )
	{
		ri.Printf( PRINT_ALL, " invalid mode\n" );
		return RSERR_INVALID_MODE;
	}
	ri.Printf( PRINT_ALL, " %d %d %s\n", glConfig.vidWidth, glConfig.vidHeight, win_fs[cdsFullscreen] );

	//
	// check our desktop attributes
	//
	hDC = GetDC( GetDesktopWindow() );
	glw_state.desktopBitsPixel = GetDeviceCaps( hDC, BITSPIXEL );
	glw_state.desktopWidth = GetDeviceCaps( hDC, HORZRES );
	glw_state.desktopHeight = GetDeviceCaps( hDC, VERTRES );
	ReleaseDC( GetDesktopWindow(), hDC );

	//
	// verify desktop bit depth
	//
	if ( glw_state.desktopBitsPixel < 15 || glw_state.desktopBitsPixel == 24 )
	{
		if ( colorbits == 0 || ( !cdsFullscreen && colorbits >= 15 ) )
		{
			// since I can't be bothered trying to mess around with asian codepages and MBCS stuff for a windows
			//	error box that'll only appear if something's seriously f****d then I'm going to fallback to
			//	english text when these would otherwise be used...
			//
			char sErrorHead[1024];	// ott

			extern qboolean Language_IsAsian(void);
			Q_strncpyz(sErrorHead, Language_IsAsian() ? "Low Desktop Color Depth" : SP_GetStringTextString("CON_TEXT_LOW_DESKTOP_COLOUR_DEPTH"), sizeof(sErrorHead) );

			const char *psErrorBody = Language_IsAsian() ?
												"It is highly unlikely that a correct windowed\n"
												"display can be initialized with the current\n"
												"desktop display depth.  Select 'OK' to try\n"
												"anyway.  Select 'Cancel' to try a fullscreen\n"
												"mode instead."
												:
												SP_GetStringTextString("CON_TEXT_TRY_ANYWAY");

			if ( MessageBox( NULL, 							
						psErrorBody,
						sErrorHead,
						MB_OKCANCEL | MB_ICONEXCLAMATION ) != IDOK )
			{
				return RSERR_INVALID_MODE;
			}
		}
	}

	// do a CDS if needed
	if ( cdsFullscreen )
	{
		memset( &dm, 0, sizeof( dm ) );
		
		dm.dmSize = sizeof( dm );
		
		dm.dmPelsWidth  = glConfig.vidWidth;
		dm.dmPelsHeight = glConfig.vidHeight;
		dm.dmFields     = DM_PELSWIDTH | DM_PELSHEIGHT;

		if ( r_displayRefresh->integer != 0 )
		{
			dm.dmDisplayFrequency = r_displayRefresh->integer;
			dm.dmFields |= DM_DISPLAYFREQUENCY;
		}
		
		// try to change color depth if possible
		if ( colorbits != 0 )
		{
			if ( glw_state.allowdisplaydepthchange )
			{
				dm.dmBitsPerPel = colorbits;
				dm.dmFields |= DM_BITSPERPEL;
				ri.Printf( PRINT_ALL, "...using colorsbits of %d\n", colorbits );
			}
			else
			{
				ri.Printf( PRINT_ALL, "WARNING:...changing depth not supported on Win95 < pre-OSR 2.x\n" );
			}
		}
		else
		{
			ri.Printf( PRINT_ALL, "...using desktop display depth of %d\n", glw_state.desktopBitsPixel );
		}

		//
		// if we're already in fullscreen then just create the window
		//
		if ( glw_state.cdsFullscreen )
		{
			ri.Printf( PRINT_ALL, "...already fullscreen, avoiding redundant CDS\n" );

			if ( !GLW_CreateWindow ( glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue ) )
			{
				ri.Printf( PRINT_ALL, "...restoring display settings\n" );
				ChangeDisplaySettings( 0, 0 );
				return RSERR_INVALID_MODE;
			}
		}
		//
		// need to call CDS
		//
		else
		{
			ri.Printf( PRINT_ALL, "...calling CDS: " );
			
			// try setting the exact mode requested, because some drivers don't report
			// the low res modes in EnumDisplaySettings, but still work
			if ( ( cdsRet = ChangeDisplaySettings( &dm, CDS_FULLSCREEN ) ) == DISP_CHANGE_SUCCESSFUL )
			{
				ri.Printf( PRINT_ALL, "ok\n" );

				if ( !GLW_CreateWindow ( glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue) )
				{
					ri.Printf( PRINT_ALL, "...restoring display settings\n" );
					ChangeDisplaySettings( 0, 0 );
					return RSERR_INVALID_MODE;
				}
				
				glw_state.cdsFullscreen = qtrue;
			}
			else
			{
				//
				// the exact mode failed, so scan EnumDisplaySettings for the next largest mode
				//
				DEVMODE		devmode;
				int			modeNum;

				ri.Printf( PRINT_ALL, "failed, " );
				
				PrintCDSError( cdsRet );
			
				ri.Printf( PRINT_ALL, "...trying next higher resolution:" );
				
				// we could do a better matching job here...
				for ( modeNum = 0 ; ; modeNum++ ) {
					if ( !EnumDisplaySettings( NULL, modeNum, &devmode ) ) {
						modeNum = -1;
						break;
					}
					if ( devmode.dmPelsWidth >= glConfig.vidWidth
						&& devmode.dmPelsHeight >= glConfig.vidHeight
						&& devmode.dmBitsPerPel >= 15 ) {
						break;
					}
				}

				if ( modeNum != -1 && ( cdsRet = ChangeDisplaySettings( &devmode, CDS_FULLSCREEN ) ) == DISP_CHANGE_SUCCESSFUL )
				{
					ri.Printf( PRINT_ALL, " ok\n" );
					if ( !GLW_CreateWindow( glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue) )
					{
						ri.Printf( PRINT_ALL, "...restoring display settings\n" );
						ChangeDisplaySettings( 0, 0 );
						return RSERR_INVALID_MODE;
					}
					
					glw_state.cdsFullscreen = qtrue;
				}
				else
				{
					ri.Printf( PRINT_ALL, " failed, " );
					
					PrintCDSError( cdsRet );
					
					ri.Printf( PRINT_ALL, "...restoring display settings\n" );
					ChangeDisplaySettings( 0, 0 );
					
/*				jfm:  i took out the following code to allow fallback to mode 3, with this code it goes half windowed and just doesn't work.
					glw_state.cdsFullscreen = qfalse;
					glConfig.isFullscreen = qfalse;
					if ( !GLW_CreateWindow( glConfig.vidWidth, glConfig.vidHeight, colorbits, qfalse) )
					{
						return RSERR_INVALID_MODE;
					}
*/
					return RSERR_INVALID_FULLSCREEN;
				}
			}
		}
	}
	else
	{
		if ( glw_state.cdsFullscreen )
		{
			ChangeDisplaySettings( 0, 0 );
		}

		glw_state.cdsFullscreen = qfalse;
		if ( !GLW_CreateWindow( glConfig.vidWidth, glConfig.vidHeight, colorbits, qfalse ) )
		{
			return RSERR_INVALID_MODE;
		}
	}

	//
	// success, now check display frequency, although this won't be valid on Voodoo(2)
	//
	memset( &dm, 0, sizeof( dm ) );
	dm.dmSize = sizeof( dm );
	if ( EnumDisplaySettings( NULL, ENUM_CURRENT_SETTINGS, &dm ) )
	{
		glConfig.displayFrequency = dm.dmDisplayFrequency;
	}

	// NOTE: this is overridden later on standalone 3Dfx drivers
	glConfig.isFullscreen = cdsFullscreen;

	return RSERR_OK;
}
コード例 #12
0
static int window_init(WININFO *info, bool use_custom_pixel_format = false, int custom_pixel_format = 0)
{
    unsigned int	PixelFormat;
    DWORD			dwExStyle, dwStyle;
    DEVMODE			dmScreenSettings;
    RECT			rec;

    WNDCLASS		wc;

    ZeroMemory(&wc, sizeof(WNDCLASS));
    wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WndProc;
    wc.hInstance = info->hInstance;
    wc.lpszClassName = info->wndclass;

    if (!RegisterClass(&wc))
        return(0);

    if (info->full)
    {
        dmScreenSettings.dmSize = sizeof(DEVMODE);
        dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
        dmScreenSettings.dmBitsPerPel = 24;
        dmScreenSettings.dmPelsWidth = XRES;
        dmScreenSettings.dmPelsHeight = YRES;
        if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
            return(0);
        dwExStyle = WS_EX_APPWINDOW;
        dwStyle = WS_VISIBLE | WS_POPUP;// | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
        ShowCursor(0);
    }
    else
    {
        dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
        dwStyle = WS_VISIBLE | WS_CAPTION | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_SYSMENU;
    }

    rec.left = 0;
    rec.top = 0;
    rec.right = XRES;
    rec.bottom = YRES;
    AdjustWindowRect(&rec, dwStyle, 0);
    windowRect.left = 0;
    windowRect.top = 0;
    windowRect.right = XRES;
    windowRect.bottom = YRES;

    info->hWnd = CreateWindowEx(dwExStyle, wc.lpszClassName, "live coding", dwStyle,
        (GetSystemMetrics(SM_CXSCREEN) - rec.right + rec.left) >> 1,
        (GetSystemMetrics(SM_CYSCREEN) - rec.bottom + rec.top) >> 1,
        rec.right - rec.left, rec.bottom - rec.top, 0, 0, info->hInstance, 0);
    if (!info->hWnd)
        return(0);

    if (!(info->hDC = GetDC(info->hWnd)))
        return(0);

    if (!use_custom_pixel_format) {
        if (!(PixelFormat = ChoosePixelFormat(info->hDC, &pfd)))
            return(0);

        if (!SetPixelFormat(info->hDC, PixelFormat, &pfd))
            return(0);
    } else {
        if (!SetPixelFormat(info->hDC, custom_pixel_format, &pfd))
            return(0);
    }

    if (!(info->hRC = wglCreateContext(info->hDC)))
        return(0);

    if (!wglMakeCurrent(info->hDC, info->hRC))
        return(0);

    return(1);
}
コード例 #13
0
ファイル: catacurse.cpp プロジェクト: Gremour/Cataclysm
//Basic Init, create the font, backbuffer, etc
WINDOW *initscr(void)
{
   // _windows = new WINDOW[20];         //initialize all of our variables
    BITMAPINFO bmi;
    lastchar=-1;
    inputdelay=-1;
    std::string typeface;
char * typeface_c;
std::ifstream fin;
fin.open("data\\FONTDATA");
 if (!fin.is_open()){
     MessageBox(WindowHandle, "Failed to open FONTDATA, loading defaults.",
                NULL, NULL);
     fontheight=16;
     fontwidth=8;
 } else {
     getline(fin, typeface);
     typeface_c= new char [typeface.size()+1];
     strcpy (typeface_c, typeface.c_str());
     fin >> fontwidth;
     fin >> fontheight;
     if ((fontwidth <= 4) || (fontheight <=4)){
         MessageBox(WindowHandle, "Invalid font size specified!",
                    NULL, NULL);
        fontheight=16;
        fontwidth=8;
     }
 }
    halfwidth=fontwidth / 2;
    halfheight=fontheight / 2;
    WindowWidth=80*fontwidth;
    WindowHeight=25*fontheight;
    WindowX=(GetSystemMetrics(SM_CXSCREEN) / 2)-WindowWidth/2;    //center this
    WindowY=(GetSystemMetrics(SM_CYSCREEN) / 2)-WindowHeight/2;   //sucker
    WinCreate();    //Create the actual window, register it, etc
    CheckMessages();    //Let the message queue handle setting up the window
    WindowDC = GetDC(WindowHandle);
    backbuffer = CreateCompatibleDC(WindowDC);
    ZeroMemory(&bmi, sizeof(BITMAPINFO));
    bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
    bmi.bmiHeader.biWidth = WindowWidth;
    bmi.bmiHeader.biHeight = -WindowHeight;
    bmi.bmiHeader.biPlanes = 1;
    bmi.bmiHeader.biBitCount=8;
    bmi.bmiHeader.biCompression = BI_RGB;   //store it in uncompressed bytes
    bmi.bmiHeader.biSizeImage = WindowWidth * WindowHeight * 1;
    bmi.bmiHeader.biClrUsed=16;         //the number of colors in our palette
    bmi.bmiHeader.biClrImportant=16;    //the number of colors in our palette
    backbit = CreateDIBSection(0, &bmi, DIB_RGB_COLORS, (void**)&dcbits, NULL, 0);
    DeleteObject(SelectObject(backbuffer, backbit));//load the buffer into DC

 int nResults = AddFontResourceExA("data\\termfont",FR_PRIVATE,NULL);
   if (nResults>0){
    font = CreateFont(fontheight, fontwidth, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
                      ANSI_CHARSET, OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,
                      PROOF_QUALITY, FF_MODERN, typeface_c);   //Create our font

  } else {
      MessageBox(WindowHandle, "Failed to load default font, using FixedSys.",
                NULL, NULL);
       font = CreateFont(fontheight, fontwidth, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
                      ANSI_CHARSET, OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,
                      PROOF_QUALITY, FF_MODERN, "FixedSys");   //Create our font
   }
    //FixedSys will be user-changable at some point in time??
    SetBkMode(backbuffer, TRANSPARENT);//Transparent font backgrounds
    SelectObject(backbuffer, font);//Load our font into the DC
//    WindowCount=0;

    delete typeface_c;
    mainwin = newwin(25,80,0,0);
    return mainwin;   //create the 'stdscr' window and return its ref
};
コード例 #14
0
ファイル: wgdi.c プロジェクト: dodamn/pkg-allegro4.2
/* render_proc:
 *  Timer proc that updates the window.
 */
static void render_proc(void)
{
   int top_line, bottom_line;
   HDC hdc = NULL;
   HWND allegro_wnd = win_get_window();

   /* to prevent reentrant calls */
   if (render_semaphore)
      return;

   render_semaphore = TRUE;

   /* to prevent the drawing threads and the rendering proc
    * from concurrently accessing the dirty lines array.
    */
   _enter_gfx_critical();

   if (!gdi_screen) {
      _exit_gfx_critical();
      render_semaphore = FALSE;
      return;
   }

   /* pseudo dirty rectangles mechanism:
    *  at most only one GDI call is performed for each frame,
    *  a true dirty rectangles mechanism makes the demo game
    *  unplayable in 640x480 on my system.
    */

   /* find the first dirty line */
   top_line = 0;

   while (!gdi_dirty_lines[top_line])
      top_line++;

   if (top_line < gfx_gdi.h) {
      /* find the last dirty line */
      bottom_line = gfx_gdi.h-1;

      while (!gdi_dirty_lines[bottom_line])
         bottom_line--;

      hdc = GetDC(allegro_wnd);

      if (_color_depth == 8)
         set_palette_to_hdc(hdc, palette);

      blit_to_hdc(gdi_screen, hdc, 0, top_line, 0, top_line,
                  gfx_gdi.w, bottom_line - top_line + 1);

      /* update mouse pointer if needed */
      if (mouse_on) {
         if ((mouse_ypos+wgdi_mouse_sprite->h > top_line) && (mouse_ypos <= bottom_line)) {
            blit(gdi_screen, mouse_backbuffer, mouse_xpos, mouse_ypos, 0, 0,
                 mouse_backbuffer->w, mouse_backbuffer->h);

            update_mouse_pointer(mouse_xpos, mouse_ypos, TRUE);
         }
      }
      
      /* clean up the dirty lines */
      while (top_line <= bottom_line)
         gdi_dirty_lines[top_line++] = 0;

      ReleaseDC(allegro_wnd, hdc);
   }

   _exit_gfx_critical();

   /* simulate vertical retrace */
   PulseEvent(vsync_event);

   render_semaphore = FALSE;
}
コード例 #15
0
ファイル: main.cpp プロジェクト: andrebonner/Deckers
//---------------------------------------------------------------------------
LRESULT CALLBACK DlgProc(HWND hWndDlg, UINT Msg,
	WPARAM wParam, LPARAM lParam)
{
	HDC hdc;

	HWND hWndDateTimePicker, hWndOK;

	LONG ptrStyles = GetWindowLong(hWndDlg, GWL_STYLE);
	// This will represent the dimensions of the whole screen
	RECT rctClient;

	// Create a black brush
	HBRUSH BlackBrush;
	// Select the black brush
	HBRUSH oldBrush =(HBRUSH) GetSysColor(COLOR_BACKGROUND);

	hWndDateTimePicker = GetDlgItem(hWndDlg, IDC_TIMETOWAKEUP);
	hWndOK = GetDlgItem(hWndDlg, IDOK);

	SYSTEMTIME tmeCurrent;


	switch (Msg)
	{
	case WM_INITDIALOG:
		return TRUE;

	case WM_COMMAND:
		switch (wParam)
		{
		case IDCANCEL:
			EndDialog(hWndDlg, 0);
			return TRUE;
		case IDC_SET_BTN:
			// Get the time that the user had set and store it
			// in the tmeSet variable
			DateTime_GetSystemtime(hWndDateTimePicker, &tmeSet);
			
			TCHAR str[20];
			GetTimeFormat(
				MAKELCID(LANG_USER_DEFAULT, SORT_DEFAULT),
				0,
				&tmeSet,
				NULL,
				str,
				20);
			MessageBox(hWndDlg, str, _T("System Time"), MB_OK);

			hdc = GetDC(hWndDlg);
			BlackBrush = CreateSolidBrush(RGB(0, 0, 0));

			SelectObject(hdc, BlackBrush);
			// TODO: Add your control notification handler code here
			// Get the screen dimensions
			DialogWidth = GetSystemMetrics(SM_CXSCREEN);
			DialogHeight = GetSystemMetrics(SM_CYSCREEN);

			// When sets the clock wave sound, remove the title bar and the borders

			ptrStyles &= ~WS_TILEDWINDOW;
			SetWindowLong(hWndDlg, GWL_STYLE, ptrStyles);

			// Occupy the whole screen
			SetWindowPos(hWndDlg, HWND_TOPMOST, 0, 0, DialogWidth, DialogHeight, SWP_SHOWWINDOW);

			// Get the dimension of the current dialog box
			GetWindowRect(hWndDlg, &rctClient);

			// Paint the dialog box in black
			Rectangle(hdc, rctClient.left, rctClient.top, rctClient.right, rctClient.bottom);

			// Restore the original brush
			//SelectObject(hdc, oldBrush);
			// Start the timer control

			SetTimer(hWndDlg, IDC_CHECKTIME, 2000, 0);
			// We don't need to see the cursor
			ShowCursor(FALSE);
			ReleaseDC(hWndDlg, hdc);


			return TRUE;
		}
		break;

	case WM_TIMER:
		// Get the current time on the computer
		GetLocalTime(&tmeCurrent);

		// Compare the current time with the time the user had set
		// If they are the same, then start playing the CD
		if ((tmeCurrent.wYear == tmeSet.wYear) &&
			(tmeCurrent.wMonth == tmeSet.wMonth) &&
			//(tmeCurrent.wDayOfWeek == tmeSet.wDayOfWeek) &&
			(tmeCurrent.wDay == tmeSet.wDay) &&
			(tmeCurrent.wHour == tmeSet.wHour) &&
			(tmeCurrent.wMinute == tmeSet.wMinute) /* &&
												   (tmeCurrent.wSecond == tmeSet.wSecond) &&
												   (tmeCurrent.wMilliseconds == tmeSet.wMilliseconds) */)
		{
			//mciSendString(_T("play waveaudio!Audio/click.wav"), NULL, 0, NULL);
			PlaySound(MAKEINTRESOURCE(IDR_SOUND), hInst, SND_RESOURCE | SND_ASYNC);
		}
		break;

	case WM_CLOSE:
		PostQuitMessage(WM_QUIT);
		break;

	case WM_DESTROY:
		// However the user decides to close the dialog box,
		// stop playing the audio file
		//mciSendString(_T("stop waveaudio"), NULL, 0, NULL);
		PlaySound(NULL, 0, 0);
		KillTimer(hWndDlg, IDC_CHECKTIME);
		break;

	}

	return FALSE;
}
コード例 #16
0
ファイル: VolumeMeter.cpp プロジェクト: AndrewHolder/OBS
LRESULT CALLBACK VolumeMeterProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    VolumeMeterData *meter;

    switch(message)
    {
        case WM_NCCREATE:
            {
                CREATESTRUCT *pCreateData = (CREATESTRUCT*)lParam;

                meter = (VolumeMeterData*)malloc(sizeof(VolumeMeterData));
                zero(meter, sizeof(VolumeMeterData));
                SetWindowLongPtr(hwnd, 0, (LONG_PTR)meter);

                meter->curVolume = VOL_MIN;
                meter->curMax = VOL_MIN;
                meter->curPeak = VOL_MIN;
                
                meter->cx = pCreateData->cx;
                meter->cy = pCreateData->cy;

                for(int i = 0; i < 16; i++)
                {
                    meter->graduations[i] = (DBtoLog(-96.0f + 6.0f * (i+1)) - minLinear) / (maxLinear - minLinear);
                }

                /*create color brushes*/
                meter->hRed  = CreateSolidBrush(0x2929f4);
                meter->hGreen  = CreateSolidBrush(0x2bf13e);
                meter->hGreenDark  = CreateSolidBrush(0x177d20);
                meter->hBlack = CreateSolidBrush(0x000000);
                meter->hGray = CreateSolidBrush(0x777777);
                meter->hLightGray = CreateSolidBrush(0xCCCCCC);
                
                return TRUE;
            }

        case WM_DESTROY:
            {
                meter = GetVolumeMeterData(hwnd);
                
                DeleteObject(meter->hRed);
                DeleteObject(meter->hGreen);
                DeleteObject(meter->hGreenDark);
                DeleteObject(meter->hBlack);
                DeleteObject(meter->hGray);
                DeleteObject(meter->hLightGray);
                
                if(meter)
                    free(meter);

                break;
            }

        case WM_PAINT:
            {
                meter = GetVolumeMeterData(hwnd);

                PAINTSTRUCT ps;

                HDC hDC = BeginPaint(hwnd, &ps);
                meter->DrawVolumeMeter(hDC);
                EndPaint(hwnd, &ps);

                break;
            }

        case WM_SIZE:
            {
                meter = GetVolumeMeterData(hwnd);
                meter->cx = LOWORD(lParam);
                meter->cy = HIWORD(lParam);

                HDC hDC = GetDC(hwnd);
                meter->DrawVolumeMeter(hDC);
                ReleaseDC(hwnd, hDC);
                break;
            }

        default:
            return DefWindowProc(hwnd, message, wParam, lParam);
    }

    return 0;
}
コード例 #17
0
void CMuleToolbarCtrl::SetAllButtonsWidth()
{
	if (GetButtonCount() == 0)
		return;

	if (m_eLabelType == LabelsBelow)
	{
		CDC *pDC = GetDC();
		CFont *pFnt = GetFont();
		CFont *pOldFnt = pDC->SelectObject(pFnt);
		CRect r(0,0,0,0);

		// calculate the max. possible button-size
		int iCalcSize = 0;
		for (int i = 0; i < m_buttoncount ; i++)
		{
			if (!IsButtonHidden(IDC_TOOLBARBUTTON + i))
			{
				pDC->DrawText(TBStrings[i], -1, r, DT_SINGLELINE | DT_CALCRECT);
 				if (r.Width() > iCalcSize)
					iCalcSize = r.Width();
			}
		}
		iCalcSize += 10;

		pDC->SelectObject(pOldFnt);
		ReleaseDC(pDC);

		if (!thePrefs.GetUseReBarToolbar())
		{
			GetClientRect(&r);
			int bc = GetButtonCount();
			if (bc == 0)
				bc = 1;
			int iMaxPossible = r.Width() / bc;

			// if the buttons are to big, reduze their size
			if (iCalcSize > iMaxPossible)
				iCalcSize = iMaxPossible;
		}
		else
		{
			if (iCalcSize < 56)
				iCalcSize = 56;
			else if (iCalcSize > 72)
				iCalcSize = 72;
		}
		SetButtonWidth(iCalcSize, iCalcSize);
	}
	else
	{
		int iSmallIconsButtonHeight;
		if (theApp.m_ullComCtrlVer < MAKEDLLVERULL(6, 0, 0, 0)) {
			// Win98,WinME,Win2000: Comtrl32 prior to 6.0 cannot make a toolbar smaller than 22 pixels
			// in height and if it gets larger than 22 pixels the icons do not get centered vertically.
			iSmallIconsButtonHeight = 22;
		}
		else
			iSmallIconsButtonHeight = GetSystemMetrics(SM_CYSCREEN) <= 600 ? 16 : 28;

		if (m_eLabelType == NoLabels)
		{
			DWORD dwSize = GetButtonSize();
			int iFixedButtonWidth;
			int iFixedButtonHeight = HIWORD(dwSize);
			if (m_sizBtnBmp.cx == 16)
			{
				iFixedButtonWidth = 28;
				iFixedButtonHeight = iSmallIconsButtonHeight;
			}
			else
			{
				iFixedButtonWidth = 56;
			}

			// it seems that the control updates itself more properly, if 'SetButtonWidth' id called *before* 'SetButtonSize'
			SetButtonWidth(iFixedButtonWidth, iFixedButtonWidth);
			SetButtonSize(CSize(iFixedButtonWidth, iFixedButtonHeight));
		}
		else
		{
			int iFixedButtonHeight = 0;
			if (m_sizBtnBmp.cx == 16)
				iFixedButtonHeight = iSmallIconsButtonHeight;

			// it seems that the control updates itself more properly, if 'SetButtonWidth' id called *before* 'SetButtonSize'
			SetButtonWidth(0, 0);
			SetButtonSize(CSize(0, iFixedButtonHeight));
		}
	}
}
コード例 #18
0
ファイル: openGLControl.cpp プロジェクト: Derongan/ecs175HW5
bool COpenGLControl::initOpenGL(HINSTANCE hInstance, HWND* a_hWnd, int iMajorVersion, int iMinorVersion, void (*a_initScene)(LPVOID), void (*a_renderScene)(LPVOID), void(*a_releaseScene)(LPVOID), LPVOID lpParam)
{
	if(!initGLEW(hInstance))return false;

	hWnd = a_hWnd;
	hDC = GetDC(*hWnd);

	bool bError = false;
	PIXELFORMATDESCRIPTOR pfd;

	if(iMajorVersion <= 2)
	{
		memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
		pfd.nSize		= sizeof(PIXELFORMATDESCRIPTOR);
		pfd.nVersion   = 1;
		pfd.dwFlags    = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
		pfd.iPixelType = PFD_TYPE_RGBA;
		pfd.cColorBits = 32;
		pfd.cDepthBits = 32;
		pfd.iLayerType = PFD_MAIN_PLANE;
 
		int iPixelFormat = ChoosePixelFormat(hDC, &pfd);
		if (iPixelFormat == 0)return false;

		if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false;

		// Create the old style context (OpenGL 2.1 and before)
		hRC = wglCreateContext(hDC);
		if(hRC)wglMakeCurrent(hDC, hRC);
		else bError = true;
	}
	else if(WGLEW_ARB_create_context && WGLEW_ARB_pixel_format)
	{
		const int iPixelFormatAttribList[] =
		{
			WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
			WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
			WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
			WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
			WGL_COLOR_BITS_ARB, 32,
			WGL_DEPTH_BITS_ARB, 24,
			WGL_STENCIL_BITS_ARB, 8,
			0 // End of attributes list
		};
		int iContextAttribs[] =
		{
			WGL_CONTEXT_MAJOR_VERSION_ARB, iMajorVersion,
			WGL_CONTEXT_MINOR_VERSION_ARB, iMinorVersion,
			WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
			0 // End of attributes list
		};

		int iPixelFormat, iNumFormats;
		wglChoosePixelFormatARB(hDC, iPixelFormatAttribList, NULL, 1, &iPixelFormat, (UINT*)&iNumFormats);

		// PFD seems to be only redundant parameter now
		if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false;

		hRC = wglCreateContextAttribsARB(hDC, 0, iContextAttribs);
		// If everything went OK
		if(hRC) wglMakeCurrent(hDC, hRC);
		else bError = true;

	}
	else bError = true;
	
	if(bError)
	{
		// Generate error messages
		char sErrorMessage[255], sErrorTitle[255];
		sprintf(sErrorMessage, "OpenGL %d.%d is not supported! Please download latest GPU drivers!", iMajorVersion, iMinorVersion);
		sprintf(sErrorTitle, "OpenGL %d.%d Not Supported", iMajorVersion, iMinorVersion);
		MessageBox(*hWnd, sErrorMessage, sErrorTitle, MB_ICONINFORMATION);
		return false;
	}

	renderScene = a_renderScene;
	initScene = a_initScene;
	releaseScene = a_releaseScene;

	if(initScene != NULL)initScene(lpParam);

	return true;
}
コード例 #19
0
ファイル: win_glimp.cpp プロジェクト: 469486139/DOOM-3-BFG
/*
===================
GLimp_Init

This is the platform specific OpenGL initialization function.  It
is responsible for loading OpenGL, initializing it,
creating a window of the appropriate size, doing
fullscreen manipulations, etc.  Its overall responsibility is
to make sure that a functional OpenGL subsystem is operating
when it returns to the ref.

If there is any failure, the renderer will revert back to safe
parameters and try again.
===================
*/
bool GLimp_Init( glimpParms_t parms ) {
	const char	*driverName;
	HDC		hDC;

	cmdSystem->AddCommand( "testSwapBuffers", GLimp_TestSwapBuffers, CMD_FL_SYSTEM, "Times swapbuffer options" );

	common->Printf( "Initializing OpenGL subsystem with multisamples:%i stereo:%i fullscreen:%i\n", 
		parms.multiSamples, parms.stereo, parms.fullScreen );

	// check our desktop attributes
	hDC = GetDC( GetDesktopWindow() );
	win32.desktopBitsPixel = GetDeviceCaps( hDC, BITSPIXEL );
	win32.desktopWidth = GetDeviceCaps( hDC, HORZRES );
	win32.desktopHeight = GetDeviceCaps( hDC, VERTRES );
	ReleaseDC( GetDesktopWindow(), hDC );

	// we can't run in a window unless it is 32 bpp
	if ( win32.desktopBitsPixel < 32 && parms.fullScreen <= 0 ) {
		common->Printf("^3Windowed mode requires 32 bit desktop depth^0\n");
		return false;
	}

	// save the hardware gamma so it can be
	// restored on exit
	GLimp_SaveGamma();

	// create our window classes if we haven't already
	GLW_CreateWindowClasses();

	// this will load the dll and set all our qgl* function pointers,
	// but doesn't create a window

	// r_glDriver is only intended for using instrumented OpenGL
	// dlls.  Normal users should never have to use it, and it is
	// not archived.
	driverName = r_glDriver.GetString()[0] ? r_glDriver.GetString() : "opengl32";
	if ( !QGL_Init( driverName ) ) {
		common->Printf( "^3GLimp_Init() could not load r_glDriver \"%s\"^0\n", driverName );
		return false;
	}

	// getting the wgl extensions involves creating a fake window to get a context,
	// which is pretty disgusting, and seems to mess with the AGP VAR allocation
	GLW_GetWGLExtensionsWithFakeWindow();



	// Optionally ChangeDisplaySettings to get a different fullscreen resolution.
	if ( !GLW_ChangeDislaySettingsIfNeeded( parms ) ) {
		GLimp_Shutdown();
		return false;
	}

	// try to create a window with the correct pixel format
	// and init the renderer context
	if ( !GLW_CreateWindow( parms ) ) {
		GLimp_Shutdown();
		return false;
	}

	glConfig.isFullscreen = parms.fullScreen;
	glConfig.isStereoPixelFormat = parms.stereo;
	glConfig.nativeScreenWidth = parms.width;
	glConfig.nativeScreenHeight = parms.height;
	glConfig.multisamples = parms.multiSamples;

	glConfig.pixelAspect = 1.0f;	// FIXME: some monitor modes may be distorted
									// should side-by-side stereo modes be consider aspect 0.5?

	// get the screen size, which may not be reliable...
	// If we use the windowDC, I get my 30" monitor, even though the window is
	// on a 27" monitor, so get a dedicated DC for the full screen device name.
	const idStr deviceName = GetDeviceName( Max( 0, parms.fullScreen - 1 ) );

	HDC deviceDC = CreateDC( deviceName.c_str(), deviceName.c_str(), NULL, NULL );
	const int mmWide = GetDeviceCaps( win32.hDC, HORZSIZE );
	DeleteDC( deviceDC );

	if ( mmWide == 0 ) {
		glConfig.physicalScreenWidthInCentimeters = 100.0f;
	} else {
		glConfig.physicalScreenWidthInCentimeters = 0.1f * mmWide;
	}


	// wglSwapinterval, etc
	GLW_CheckWGLExtensions( win32.hDC );

	// check logging
	GLimp_EnableLogging( ( r_logFile.GetInteger() != 0 ) );

	return true;
}
コード例 #20
0
ファイル: control.c プロジェクト: powentan/darktable
// Get the display ICC profile of the monitor associated with the widget.
// For X display, uses the ICC profile specifications version 0.2 from
// http://burtonini.com/blog/computers/xicc
// Based on code from Gimp's modules/cdisplay_lcms.c
void dt_ctl_set_display_profile()
{
  if(!dt_control_running()) return;
  // make sure that no one gets a broken profile
  // FIXME: benchmark if the try is really needed when moving/resizing the window. Maybe we can just lock it
  // and block
  if(pthread_rwlock_trywrlock(&darktable.control->xprofile_lock))
    return; // we are already updating the profile. Or someone is reading right now. Too bad we can't
            // distinguish that. Whatever ...

  GtkWidget *widget = dt_ui_center(darktable.gui->ui);
  guint8 *buffer = NULL;
  gint buffer_size = 0;
  gchar *profile_source = NULL;

#if defined GDK_WINDOWING_X11

  // we will use the xatom no matter what configured when compiled without colord
  gboolean use_xatom = TRUE;
#if defined USE_COLORDGTK
  gboolean use_colord = TRUE;
  gchar *display_profile_source = dt_conf_get_string("ui_last/display_profile_source");
  if(display_profile_source)
  {
    if(!strcmp(display_profile_source, "xatom"))
      use_colord = FALSE;
    else if(!strcmp(display_profile_source, "colord"))
      use_xatom = FALSE;
    g_free(display_profile_source);
  }
#endif

  /* let's have a look at the xatom, just in case ... */
  if(use_xatom)
  {
    GdkScreen *screen = gtk_widget_get_screen(widget);
    if(screen == NULL) screen = gdk_screen_get_default();
    int monitor = gdk_screen_get_monitor_at_window(screen, gtk_widget_get_window(widget));
    char *atom_name;
    if(monitor > 0)
      atom_name = g_strdup_printf("_ICC_PROFILE_%d", monitor);
    else
      atom_name = g_strdup("_ICC_PROFILE");

    profile_source = g_strdup_printf("xatom %s", atom_name);

    GdkAtom type = GDK_NONE;
    gint format = 0;
    gdk_property_get(gdk_screen_get_root_window(screen), gdk_atom_intern(atom_name, FALSE), GDK_NONE, 0,
                     64 * 1024 * 1024, FALSE, &type, &format, &buffer_size, &buffer);
    g_free(atom_name);
  }

#ifdef USE_COLORDGTK
  /* also try to get the profile from colord. this will set the value asynchronously! */
  if(use_colord)
  {
    CdWindow *window = cd_window_new();
    GtkWidget *center_widget = dt_ui_center(darktable.gui->ui);
    cd_window_get_profile(window, center_widget, NULL, dt_ctl_get_display_profile_colord_callback, NULL);
  }
#endif

#elif defined GDK_WINDOWING_QUARTZ
  GdkScreen *screen = gtk_widget_get_screen(widget);
  if(screen == NULL) screen = gdk_screen_get_default();
  int monitor = gdk_screen_get_monitor_at_window(screen, gtk_widget_get_window(widget));

  CGDirectDisplayID ids[monitor + 1];
  uint32_t total_ids;
  CMProfileRef prof = NULL;
  if(CGGetOnlineDisplayList(monitor + 1, &ids[0], &total_ids) == kCGErrorSuccess && total_ids == monitor + 1)
    CMGetProfileByAVID(ids[monitor], &prof);
  if(prof != NULL)
  {
    CFDataRef data;
    data = CMProfileCopyICCData(NULL, prof);
    CMCloseProfile(prof);

    UInt8 *tmp_buffer = (UInt8 *)g_malloc(CFDataGetLength(data));
    CFDataGetBytes(data, CFRangeMake(0, CFDataGetLength(data)), tmp_buffer);

    buffer = (guint8 *)tmp_buffer;
    buffer_size = CFDataGetLength(data);

    CFRelease(data);
  }
  profile_source = g_strdup("osx color profile api");
#elif defined G_OS_WIN32
  (void)widget;
  HDC hdc = GetDC(NULL);
  if(hdc != NULL)
  {
    DWORD len = 0;
    GetICMProfile(hdc, &len, NULL);
    gchar *path = g_new(gchar, len);

    if(GetICMProfile(hdc, &len, path))
    {
      gsize size;
      g_file_get_contents(path, (gchar **)&buffer, &size, NULL);
      buffer_size = size;
    }
    g_free(path);
    ReleaseDC(NULL, hdc);
  }
  profile_source = g_strdup("windows color profile api");
#endif

  int profile_changed = buffer_size > 0
                        && (darktable.control->xprofile_size != buffer_size
                            || memcmp(darktable.control->xprofile_data, buffer, buffer_size) != 0);
  if(profile_changed)
  {
    cmsHPROFILE profile = NULL;
    char name[512] = { 0 };
    // thanks to ufraw for this!
    g_free(darktable.control->xprofile_data);
    darktable.control->xprofile_data = buffer;
    darktable.control->xprofile_size = buffer_size;
    profile = cmsOpenProfileFromMem(buffer, buffer_size);
    if(profile)
    {
      dt_colorspaces_get_profile_name(profile, "en", "US", name, sizeof(name));
      cmsCloseProfile(profile);
    }
    dt_print(DT_DEBUG_CONTROL, "[color profile] we got a new screen profile `%s' from the %s (size: %d)\n",
             *name ? name : "(unknown)", profile_source, buffer_size);
  }
  pthread_rwlock_unlock(&darktable.control->xprofile_lock);
  if(profile_changed) dt_control_signal_raise(darktable.signals, DT_SIGNAL_CONTROL_PROFILE_CHANGED);
  g_free(profile_source);
}
コード例 #21
0
ファイル: win_glimp.cpp プロジェクト: 469486139/DOOM-3-BFG
/*
=======================
GLW_CreateWindow

Responsible for creating the Win32 window.
If fullscreen, it won't have a border
=======================
*/
static bool GLW_CreateWindow( glimpParms_t parms ) {
	int				x, y, w, h;
	if ( !GLW_GetWindowDimensions( parms, x, y, w, h ) ) {
		return false;
	}

	int				stylebits;
	int				exstyle;
	if ( parms.fullScreen != 0 ) {
		exstyle = WS_EX_TOPMOST;
		stylebits = WS_POPUP|WS_VISIBLE|WS_SYSMENU;
	} else {
		exstyle = 0;
		stylebits = WINDOW_STYLE|WS_SYSMENU;
	}

	win32.hWnd = CreateWindowEx (
		 exstyle, 
		 WIN32_WINDOW_CLASS_NAME,
		 GAME_NAME,
		 stylebits,
		 x, y, w, h,
		 NULL,
		 NULL,
		 win32.hInstance,
		 NULL);

	if ( !win32.hWnd ) {
		common->Printf( "^3GLW_CreateWindow() - Couldn't create window^0\n" );
		return false;
	}

	::SetTimer( win32.hWnd, 0, 100, NULL );

	ShowWindow( win32.hWnd, SW_SHOW );
	UpdateWindow( win32.hWnd );
	common->Printf( "...created window @ %d,%d (%dx%d)\n", x, y, w, h );

	// makeCurrent NULL frees the DC, so get another
	win32.hDC = GetDC( win32.hWnd );
	if ( !win32.hDC ) {
		common->Printf( "^3GLW_CreateWindow() - GetDC()failed^0\n" );
		return false;
	}

	// Check to see if we can get a stereo pixel format, even if we aren't going to use it,
	// so the menu option can be 
	if ( GLW_ChoosePixelFormat( win32.hDC, parms.multiSamples, true ) != -1 ) {
		glConfig.stereoPixelFormatAvailable = true;
	} else {
		glConfig.stereoPixelFormatAvailable = false;
	}

	if ( !GLW_InitDriver( parms ) ) {
		ShowWindow( win32.hWnd, SW_HIDE );
		DestroyWindow( win32.hWnd );
		win32.hWnd = NULL;
		return false;
	}

	SetForegroundWindow( win32.hWnd );
	SetFocus( win32.hWnd );

	glConfig.isFullscreen = parms.fullScreen;

	return true;
}
コード例 #22
0
void
nsThebesDeviceContext::CalcPrintingSize()
{
    if (!mPrintingSurface)
        return;

    PRBool inPoints = PR_TRUE;

    gfxSize size;
    switch (mPrintingSurface->GetType()) {
    case gfxASurface::SurfaceTypeImage:
        inPoints = PR_FALSE;
        size = reinterpret_cast<gfxImageSurface*>(mPrintingSurface.get())->GetSize();
        break;

#if defined(MOZ_ENABLE_GTK2) || defined(XP_WIN) || defined(XP_OS2)
    case gfxASurface::SurfaceTypePDF:
        inPoints = PR_TRUE;
        size = reinterpret_cast<gfxPDFSurface*>(mPrintingSurface.get())->GetSize();
        break;
#endif

#ifdef MOZ_ENABLE_GTK2
    case gfxASurface::SurfaceTypePS:
        inPoints = PR_TRUE;
        size = reinterpret_cast<gfxPSSurface*>(mPrintingSurface.get())->GetSize();
        break;
#endif

#ifdef XP_MACOSX
    case gfxASurface::SurfaceTypeQuartz:
        inPoints = PR_TRUE; // this is really only true when we're printing
        size = reinterpret_cast<gfxQuartzSurface*>(mPrintingSurface.get())->GetSize();
        break;
#endif

#ifdef XP_WIN
    case gfxASurface::SurfaceTypeWin32:
    case gfxASurface::SurfaceTypeWin32Printing:
    {
        inPoints = PR_FALSE;
        HDC dc =  GetPrintHDC();
        if (!dc)
            dc = GetDC((HWND)mWidget->GetNativeData(NS_NATIVE_WIDGET));
        size.width = NSFloatPixelsToAppUnits(::GetDeviceCaps(dc, HORZRES)/mPrintingScale, AppUnitsPerDevPixel());
        size.height = NSFloatPixelsToAppUnits(::GetDeviceCaps(dc, VERTRES)/mPrintingScale, AppUnitsPerDevPixel());
        mDepth = (PRUint32)::GetDeviceCaps(dc, BITSPIXEL);
        if (dc != (HDC)GetPrintHDC())
            ReleaseDC((HWND)mWidget->GetNativeData(NS_NATIVE_WIDGET), dc);
        break;
    }
#endif

#ifdef XP_OS2
    case gfxASurface::SurfaceTypeOS2:
    {
        inPoints = PR_FALSE;
        // we already set the size in the surface constructor we set for
        // printing, so just get those values here
        size = reinterpret_cast<gfxOS2Surface*>(mPrintingSurface.get())->GetSize();
        // as they are in pixels we need to scale them to app units
        size.width = NSFloatPixelsToAppUnits(size.width, AppUnitsPerDevPixel());
        size.height = NSFloatPixelsToAppUnits(size.height, AppUnitsPerDevPixel());
        // still need to get the depth from the device context
        HDC dc = GetPrintHDC();
        LONG value;
        if (DevQueryCaps(dc, CAPS_COLOR_BITCOUNT, 1, &value))
            mDepth = value;
        else
            mDepth = 8; // default to 8bpp, should be enough for printers
        break;
    }
#endif
    default:
        NS_ERROR("trying to print to unknown surface type");
    }

    if (inPoints) {
        // For printing, CSS inches and physical inches are identical
        // so it doesn't matter which we use here
        mWidth = NSToCoordRound(float(size.width) * AppUnitsPerPhysicalInch() / 72);
        mHeight = NSToCoordRound(float(size.height) * AppUnitsPerPhysicalInch() / 72);
    } else {
        mWidth = NSToIntRound(size.width);
        mHeight = NSToIntRound(size.height);
    }
}
コード例 #23
0
ファイル: main.c プロジェクト: GYGit/reactos
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
    WNDCLASSEX wcFrame = {
        sizeof(WNDCLASSEX),
        CS_HREDRAW | CS_VREDRAW/*style*/,
        FrameWndProc,
        0/*cbClsExtra*/,
        0/*cbWndExtra*/,
        hInstance,
        LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MDI_APP)),
        LoadCursor(0, IDC_ARROW),
        0/*hbrBackground*/,
        0/*lpszMenuName*/,
        szFrameClass,
        (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDI_MDI_APP), IMAGE_ICON,
            GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED)
    };
    ATOM hFrameWndClass = RegisterClassEx(&wcFrame); // register frame window class
#if 0
    WNDCLASS wcChild = {
        CS_CLASSDC|CS_DBLCLKS|CS_VREDRAW,
        ChildWndProc,
        0/*cbClsExtra*/,
        0/*cbWndExtra*/,
        hInstance,
        0/*hIcon*/,
        LoadCursor(0, IDC_ARROW),
        0/*hbrBackground*/,
        0/*lpszMenuName*/,
        szChildClass
    };
    ATOM hChildWndClass = RegisterClass(&wcChild); // register child windows class
#else
    // WNDCLASSEX wcChild = {
    //     sizeof(WNDCLASSEX),
    //     CS_HREDRAW | CS_VREDRAW/*style*/,
    //     ChildWndProc,
    //     0/*cbClsExtra*/,
    //     sizeof(HANDLE)/*cbWndExtra*/,
    //     hInstance,
    //     LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MDI_APP)),
    //     LoadCursor(0, IDC_ARROW),
    //     0/*hbrBackground*/,
    //     0/*lpszMenuName*/,
    //     szChildClass,
    //     (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDC_MDI_APP), IMAGE_ICON,
    //         GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED)
    // };
    // ATOM hChildWndClass = RegisterClassEx(&wcChild); // register child windows class
#endif

    HMENU hMenu = LoadMenu(hInstance, MAKEINTRESOURCE(IDC_MDI_APP));
    HMENU hMenuOptions = GetSubMenu(hMenu, ID_OPTIONS_MENU);
    // HMENU hChildMenu = LoadMenu(hInstance, MAKEINTRESOURCE(IDC_MDI_APP_CHILD));

    INITCOMMONCONTROLSEX icc = {
        sizeof(INITCOMMONCONTROLSEX),
        ICC_BAR_CLASSES
    };

    HDC hdc = GetDC(0);

    hMenuFrame = hMenu;
//  hMenuView = GetSubMenu(hMenuFrame, ID_VIEW_MENU);
    hAccel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MDI_APP));
    hFont = CreateFont(-MulDiv(8,GetDeviceCaps(hdc,LOGPIXELSY),72), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, _T("MS Sans Serif"));
    ReleaseDC(0, hdc);

    hFrameWnd = CreateWindowEx(0, (LPCTSTR)(int)hFrameWndClass, szTitle,
//  hFrameWnd = CreateWindow(szFrameClass, szTitle,
                    WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
                    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                    NULL/*hWndParent*/, hMenuFrame, hInstance, NULL/*lpParam*/);
    if (!hFrameWnd) {
        return FALSE;
    }

    if (InitCommonControlsEx(&icc))
    {
        int nParts[3];
        TBBUTTON toolbarBtns[] = {
            {0, 0, 0, TBSTYLE_SEP},
            {0, ID_WINDOW_NEW_WINDOW, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {1, ID_WINDOW_CASCADE, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {2, ID_WINDOW_TILE_HORZ, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {3, ID_WINDOW_TILE_VERT, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {4, 2/*TODO: ID_...*/, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {5, 2/*TODO: ID_...*/, TBSTATE_ENABLED, TBSTYLE_BUTTON},
        };

        hToolBar = CreateToolbarEx(hFrameWnd, WS_CHILD|WS_VISIBLE,
            IDC_TOOLBAR, 2, hInstance, IDB_TOOLBAR, toolbarBtns,
            sizeof(toolbarBtns)/sizeof(TBBUTTON), 16, 15, 16, 15, sizeof(TBBUTTON));
        CheckMenuItem(hMenuOptions, ID_OPTIONS_TOOLBAR, MF_BYCOMMAND|MF_CHECKED);

        // Create the status bar
        hStatusBar = CreateStatusWindow(WS_VISIBLE|WS_CHILD|WS_CLIPSIBLINGS|SBT_NOBORDERS,
                                        "", hFrameWnd, IDC_STATUSBAR);
        if (!hStatusBar)
            return FALSE;
        CheckMenuItem(hMenuOptions, ID_OPTIONS_STATUSBAR, MF_BYCOMMAND|MF_CHECKED);

        // Create the status bar panes
        nParts[0] = 100;
        nParts[1] = 210;
        nParts[2] = 400;
        SendMessage(hStatusBar, SB_SETPARTS, 3, (long)nParts);
    } else {
        CheckMenuItem(hMenuOptions, ID_OPTIONS_TOOLBAR, MF_BYCOMMAND|MF_GRAYED);
        CheckMenuItem(hMenuOptions, ID_OPTIONS_STATUSBAR, MF_BYCOMMAND|MF_GRAYED);
	}

    ShowWindow(hFrameWnd, nCmdShow);
    UpdateWindow(hFrameWnd);
    UpdateStatusBar();
    return TRUE;
}
コード例 #24
0
CPUTResult CPUT_OGL::CreateOGLContext(CPUTContextCreation ContextParams )
{
	HWND hWnd;

	hWnd = CreateDummyWindow( GetModuleHandle(NULL));
    // Create dummy window to gather information about OpenGL
    if ( ! hWnd) 
    {
        return CPUT_ERROR;
    }

    // To get list of supported extensions, this 
    // code should be used since OpenGL 3.0 Core:
    //
    // uint32 count = 0;
    // glGetIntegerv(GL_NUM_EXTENSIONS, (GLint*)&count);
    // for(uint16 i=0; i<count; i++)
    //    support.m_extensions.insert(support.m_extensions.end(),string((char*)glGetStringi(GL_EXTENSIONS,i));
    //
    // But data about gpu, are gathered in dummy
    // OpenGL context which works in deprecaded
    // mode. This forces implementation in old
    // deprecated way:
    
    // Creates table of supported extensions strings
    extensions.clear();
    string tmp;
    sint32 begin, end;
    tmp   = string( (char*)glGetString( GL_EXTENSIONS ) );
    begin = 0;
    end   = tmp.find( ' ', 0 );
    while( end != string::npos )
    {
        extensions.insert( extensions.end(), tmp.substr( begin, end-begin ) );
        begin = end + 1;
        end   = tmp.find( ' ', begin );
    }
    
    // This extension together with WGL_EXT_swap_interval
    // should be returned in list of supported extensions
    // after calling glGetString(GL_EXTENSIONS);
    // Because NVidia drivers don't follow this rule it's
    // specification says as follow:
    // 
    // "Applications should call wglGetProcAddress to see 
    // whether or not wglGetExtensionsStringARB is supported."
    // ( http://www.opengl.org/registry/specs/ARB/wgl_extensions_string.txt )
    //
    bool wglexts = false;
    wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress( "wglGetExtensionsStringARB" );  
    if ( wglGetExtensionsStringARB != NULL )
    {
        tmp = string( (char*)wglGetExtensionsStringARB( mhDC ) );
        wglexts = true;
    }
    else
    {
        wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress( "wglGetExtensionsStringEXT" );
        if ( wglGetExtensionsStringEXT != NULL )
        {
            tmp = string( (char*)wglGetExtensionsStringEXT() ); 
            wglexts = true; 
        }
    }

    // If it is possible to obtain WGL extensions list add
    // them to the rest of supported extensions.
    if ( wglexts )
    {
        begin = 0;
        end   = tmp.find( ' ', 0 );
        while( end != string::npos )
        {
            extensions.insert( extensions.end(), tmp.substr( begin, end-begin ) );
            begin = end + 1;
            end   = tmp.find( ' ', begin );
        }
	}

	// Get pointers to WGL specific functions that are required during window creation
    wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress( "wglCreateContextAttribsARB" );
    wglChoosePixelFormatARB    = (PFNWGLCHOOSEPIXELFORMATARBPROC)    wglGetProcAddress( "wglChoosePixelFormatARB" );
    wglChoosePixelFormatEXT    = (PFNWGLCHOOSEPIXELFORMATEXTPROC)    wglGetProcAddress( "wglChoosePixelFormatEXT" );
 
	// Set Samples count in Advanced Pixel Format
	iAttributes[27] = ContextParams.samples;

    // Choosing advanced Pixel Format in modern way 
    uint32 PixelFormat = 0;
    bool choosedPixelFormat = false;   
    if ( supportExtension( "WGL_ARB_pixel_format" ) )
    {
        uint32 numFormats;
        if ( wglChoosePixelFormatARB( mhDC, (const int*)iAttributes, fAttributes, 1, (int*)&PixelFormat, (unsigned int*)&numFormats ) )
            if ( numFormats >= 1 )
                choosedPixelFormat = true;
    }
    
    // Old way for choosing advanced Pixel Format
    if ( !choosedPixelFormat &&
         supportExtension( "WGL_EXT_pixel_format" ) )
    {
        uint32 numFormats;
        if ( wglChoosePixelFormatEXT( mhDC, (const int*)iAttributes, fAttributes, 1, (int*)&PixelFormat, (unsigned int*)&numFormats ) )
            if ( numFormats >= 1 )
                choosedPixelFormat = true;
    }

    // Basic Pixel Format
    if ( !choosedPixelFormat )
        PixelFormat = ChoosePixelFormat( mhDC, &pfdLegacy );

    // If couldn't find Pixel Format report error
    if ( PixelFormat == NULL )
    {
        cerr << "Error! Cannot find aproprieate pixel format." << endl;	
        DestroyOGLContext();	
        return CPUT_ERROR;
    } 


   // Data about OpenGL are gathered, proper Pixel Format is choosed.
    // Destroy Dummy Window and proceed to creation of proper window.
    // Disabling and deleting all rendering contexts
    wglMakeCurrent( NULL, NULL ); 
    wglDeleteContext( mhRC );
    mhRC = NULL;
    // Disabling device context
    ReleaseDC( hWnd, mhDC ); 
    mhDC = 0;
   
	// Deleting window
    DestroyWindow( hWnd );  

    // Unregistering window class
    if(TRUE != UnregisterClass( L"DummyWindowClass", GetModuleHandle(NULL) ))
	{
		return CPUT_ERROR;
	}

    // Clear message queue
    MSG msg = { 0 };
    while( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
    {
        TranslateMessage( &msg );
        DispatchMessage( &msg );

    }

	hWnd = mpWindow->GetHWnd();

   

    // Acquiring Device Context
    mhDC = GetDC( hWnd );
    if ( mhDC == NULL )
    {
        cerr << "Error! Cannot create device context." << endl;		
        DestroyOGLContext();	
        return CPUT_ERROR;
    }  

    // Activating Pixel Format
    if ( !SetPixelFormat( mhDC, PixelFormat, &pfdLegacy ) )
    {	
        cerr << "Error! Cannot init pixel format." << endl;
        DestroyOGLContext();	
        return CPUT_ERROR;
	} 

    // OpenGL 4.0 Core profile settings
    uint32 glAttributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
                              WGL_CONTEXT_MINOR_VERSION_ARB, 0,
                              WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
                              GL_CONTEXT_PROFILE_MASK, GL_CONTEXT_CORE_PROFILE_BIT,
                              0, 0 };
   //         GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,
     //   GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
    // Debug version supports better debugging
#ifdef _DEBUG
    glAttributes[5] |= WGL_CONTEXT_DEBUG_BIT_ARB;
#endif 

    // Try to create OpenGL context in new way
    mhRC = wglCreateContextAttribsARB( mhDC, 0, (const int *) &glAttributes );
    if ( mhRC == NULL )
    {
        cerr << "Error! Cannot create window rendering context." << endl;
        DestroyOGLContext();				
        return CPUT_ERROR;
    }  

    // Activating rendering context
    if( !wglMakeCurrent( mhDC, mhRC ) )
    {	
        std::cerr << "Error! Cannot activate rendering context." << endl;
        DestroyOGLContext();	
        return CPUT_ERROR;
    } 
    
    
    // Setting created window as current 
    ShowWindow( hWnd, SW_SHOW );
    SetForegroundWindow( hWnd );
    SetFocus( hWnd );
    
    // Link all OpenGL function pointers
    glewExperimental = TRUE;
    if ( glewInit() != GLEW_OK )
    {
        cerr << "Error! Cannot activate GLEW." << endl;
        DestroyOGLContext();	
        return CPUT_ERROR;
    }

    // GLEW's problem is that it calls glGetString(GL_EXTENSIONS) which causes 
    // GL_INVALID_ENUM on GL 3.2 core context as soon as glewInit() is called.
    // Clear errors indicator 
    glGetError();
    
    wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress( "wglSwapIntervalEXT" );
    wglSwapIntervalEXT(0);

    return CPUT_SUCCESS;
}
コード例 #25
0
ファイル: Wbrwline.old.c プロジェクト: azulae/Gestool
CLIPPER WBrwRect( PARAMS ) // ( hWnd, nRow, aSizes, nFirstItem, nCol,
                           //   nLineStyle, nWidthVScroll )
{
   HWND hWnd        = ( HWND ) _parnl( 1 );

   HDC hDC          = GetDC( hWnd );
   WORD wRow        = _parni( 2 );
   WORD wHeight ;
   RECT rct;
   WORD nStyle = ISNUM( 6 ) ? _parni( 6 ) : -1 ; // CeSoTech


   #ifdef __CLIPPER__
      PCLIPVAR paSizes = _param( 3, 0x8000 );
      WORD wLen        = _VARRAYLEN( paSizes );
   #else
      #ifdef __HARBOUR__
         void * paSizes = ( void * ) _param( 3, IT_ARRAY );
         WORD wLen      = _parinfa( 3, 0 );
      #else
         void * paSizes = ( void * ) _param( 3, 0x8000 );
         WORD wLen      = _VARRAYLEN( paSizes );
      #endif
   #endif
   WORD wIndex      = _parni( 4 );
   WORD wCol        = _parni( 5 );
   WORD wMaxRight;
   LONG l;

   if( !wCol || wCol > wLen )
        return;


   GetWindowRect( hWnd, &rct );
   wMaxRight = rct.right - 2;

   wHeight = wLineHeight + 1 ;

   rct.top    = rct.top + ( bDrawHeaders ? wHeaderHeight+1 : 0 ) +
                (wHeight * (wRow-1) ) ;


   rct.bottom = rct.top + wHeight;
   rct.right  = rct.left;

   while( wIndex <= wCol )
   {
        rct.left   = rct.right;

        #ifndef __FLAT__

           rct.right  = ( wIndex == wLen && bAdjLastCol ? wMaxRight
                                         : rct.left + GetInt( paSizes, wIndex ) );

        #else
           #ifndef __HARBOUR__
              #define _parnl(x,y) PARNL(x,params,y);
           #endif
           l = _parnl( 3, wIndex );

           rct.right  = ( wIndex == wLen && bAdjLastCol ? wMaxRight
                                         : rct.left + l );

           #undef _parnl
        #endif

        if( rct.right >= wMaxRight )
        {
            wIndex = wCol + 1;   // ya no pintamos m s
            rct.right = wMaxRight;
        }
        else
            wIndex++;
   }



   ReleaseDC( hWnd, hDC );

   _reta( 4 );

   #ifdef __XPP__
      #define _storni( x, y, z ) STORNI( x, params, y, z )
   #endif


   // Si es un estilo sin separadores horizontales, pintar uno mas arriba
   //CeSoTech para que que bien completa el area !!!
   if (nStyle == 0 || nStyle == 5 || nStyle == 6 || nStyle == 9 || nStyle == 10)
      rct.top-- ;  // Las coord.de edicion deberan ser mas arriba tambien !!!


   _storni( rct.top,    -1, 1 );
   _storni( rct.left,   -1, 2 );
   _storni( rct.bottom, -1, 3 );
   _storni( ( wMaxRight <= rct.right ) ?
              wMaxRight - _parni( 7 ) : rct.right, -1, 4 );
}
コード例 #26
0
HWND CPUT_OGL::CreateDummyWindow(HINSTANCE hInst)
{
    WNDCLASS  Window;      // Window class
    uint32    PixelFormat; // Format of pixel
    
    // Window settings
    Window.style         = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;  // Have its own Device Context and also cannot be resized    
    Window.lpfnWndProc   = (WNDPROC) WndProcDummy;              // Procedure that handles OS evets
    Window.cbClsExtra    = 0;                                   // No extra window data
    Window.cbWndExtra    = 0;                                   //
    Window.hInstance     = hInst;                               // Handle to instance of program that this window belongs to
    Window.hIcon         = LoadIcon(NULL, IDI_WINLOGO);         // Load default icon
    Window.hCursor       = LoadCursor(NULL, IDC_ARROW);         // Load arrow pointer
    Window.hbrBackground = NULL;                                // No background (OpenGL will handle this)
    Window.lpszMenuName  = NULL;                                // No menu
    Window.lpszClassName = L"DummyWindowClass";                 // Class name
    
    // Registering Window Class
    if ( !RegisterClass( &Window ) )	
    {					
        cerr << "Error! Cannot register window class." << endl;
        return NULL;
    }

    // Create Dummy Window with OpenGL RC to gather required
    // information together with wgl functions pointers and
    // final Pixel Format number.
    HWND hWnd = CreateWindow(
        L"DummyWindowClass",           // Window class name
        L"CPUTFramework...",           // Title of window            
        WS_CLIPSIBLINGS |             // \_Prevents from overdrawing
        WS_CLIPCHILDREN |             // / by other windows
        WS_OVERLAPPEDWINDOW,          // Additional styles
        0, 0,                         // Position
        128,                          // True window widht
        128,                          // True window height
        NULL,                         // No parent window
        NULL,                         // No menu
        hInst,                        // Handle to this instance of program
        NULL );                       // Won't pass anything
    
    // Check if dummy window was created
    if ( hWnd == NULL )
    {
        cerr << "Error! Cannot create window." << endl;
        DestroyOGLContext();	
        return NULL;
    }  
    
    // Acquiring Device Context
    mhDC = GetDC( hWnd );
    if ( mhDC == NULL )
    {
        cerr << "Error! Cannot create device context." << endl;		
        DestroyOGLContext();	
        return NULL;
    }  
    
    // Choosing Pixel Format the old way
    PixelFormat = ChoosePixelFormat( mhDC, &pfdLegacy );
    if ( PixelFormat == NULL )
    {
        cerr << "Error! Cannot find aproprieate pixel format." << endl;	
        DestroyOGLContext();	
        return NULL;
    }  
    
    // Activating Pixel Format
    if ( !SetPixelFormat( mhDC, PixelFormat, &pfdLegacy ) )
    {	
        cerr << "Error! Cannot init pixel format." << endl;
        DestroyOGLContext();		
        return NULL;
    }  
    
    // Creating OpenGL Rendering Context
    mhRC = wglCreateContext( mhDC );
    if ( mhRC == NULL )
    {
        cerr << "Error! Cannot create window rendering context." << endl;
        DestroyOGLContext();						
        return NULL;
    }  
    
    // Activating rendering context
    if ( !wglMakeCurrent( mhDC, mhRC ) )
    {	
        cerr << "Error! Cannot activate rendering context." << endl;
        DestroyOGLContext();	
        return NULL;
    } 
    
    return hWnd;
}
コード例 #27
0
ファイル: T05GLOBE.C プロジェクト: AB1a/SUM2015
/* Функция обработки сообщения окна.
 * АРГУМЕНТЫ:
 *   - дескриптор окна:
 *       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;
  CREATESTRUCT *cs; 
  static BITMAP bm;
  static HBITMAP hBm, hBmLogo;
  static HDC hMemDC; 
  static INT w, h;
  

  switch (Msg)
  {
  case WM_CREATE:
    cs = (CREATESTRUCT *)lParam;
    SetTimer(hWnd, 111, 50, NULL);   
    hDC = GetDC(hWnd);
    hMemDC = CreateCompatibleDC(hDC);
    ReleaseDC(hWnd, hDC);

    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, 111, 0);      
    return 0;

  case WM_TIMER:      
    /* Clear Background */
    SelectObject(hMemDC, GetStockObject(NULL_PEN));
    SelectObject(hMemDC, GetStockObject(DC_BRUSH));
    SetDCBrushColor(hMemDC, RGB(255, 255, 255));   
    Rectangle(hMemDC, 0, 0, w + 1, h + 1);   
    
    SelectObject(hMemDC, GetStockObject(NULL_PEN));
    SelectObject(hMemDC, GetStockObject(DC_BRUSH));
    SetDCBrushColor(hMemDC, RGB(2, 2, 8)); 
    DrawGlobe(hMemDC, w, h);

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


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

  case WM_DESTROY:
    DeleteDC(hMemDC);
    DeleteObject(hBm);
    KillTimer(hWnd, 111);
    PostQuitMessage(0);
    return 0;

  }
  return DefWindowProc(hWnd, Msg, wParam, lParam);
} /* End of 'MyWindowFunc' function */
コード例 #28
0
ファイル: openorion.cpp プロジェクト: lightsgoout/interview
void InitWindow(HINSTANCE hInstance)
{
	// TODO: make it search all available configs and ask what to load from or something
	if(!cfg.LoadFromFile("default.cfg")) LogToFile("debug.log", "Failed to load config");

	window_rect.left = 0;
	window_rect.right = cfg.scr_width;
	window_rect.top = 0;
	window_rect.bottom = cfg.scr_height;

	window_class.hInstance = hInstance;
	window_class.style = CS_VREDRAW | CS_HREDRAW | CS_OWNDC;
	window_class.lpfnWndProc = WndProc;
	window_class.cbClsExtra = 0;
	window_class.cbWndExtra = 0;
	window_class.hbrBackground = NULL;
	window_class.hIcon = LoadIcon(NULL, IDI_WINLOGO);
	window_class.hCursor = LoadCursor(NULL, IDC_ARROW);
	window_class.lpszMenuName = NULL;
	window_class.lpszClassName = "OpenOrionClass";

	fullscreenflag = cfg.fullscreen;

	if(!RegisterClass(&window_class))
	{
		MessageBox(NULL, "Failed to register window class", "RegisterClass() Error", MB_OK | MB_ICONEXCLAMATION);
		LogToFile("debug.log", "Failed to register window class");
		PostQuitMessage(-1);
	}

	if(cfg.fullscreen)
	{
		memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));    // Очистка для хранения установок
		dmScreenSettings.dmSize = sizeof(dmScreenSettings);      // Размер структуры Devmode
		dmScreenSettings.dmPelsWidth = cfg.scr_width;        // Ширина экрана
		dmScreenSettings.dmPelsHeight = cfg.scr_height;        // Высота экрана
		dmScreenSettings.dmBitsPerPel = cfg.scr_bpp;        // Глубина цвета
		dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Режим Пикселя

		DWORD disp;

		disp = ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN);

		switch(disp)
		{
		case DISP_CHANGE_SUCCESSFUL:
			{
				fullscreenflag = true;
				ShowCursor(true);
				break;
			}
		case DISP_CHANGE_BADDUALVIEW:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADDUALVIEW)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADDUALVIEW", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_BADFLAGS:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADFLAGS)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADFLAGS", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_BADMODE:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADMODE)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADMODE", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_BADPARAM:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADPARAM)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADPARAM", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_FAILED:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_FAILED)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_FAILED", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_NOTUPDATED:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_NOTUPDATED)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_NOTUPDATED", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		case DISP_CHANGE_RESTART:
			{
				fullscreenflag = false;
				ShowCursor(true);
				LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_RESTART)");
				MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_RESTART", MB_OK | MB_ICONEXCLAMATION);
				break;
			}
		}

	}

	if(fullscreenflag)
	{
		dwExStyle = WS_EX_APPWINDOW;
		//dwStyle = WS_OVERLAPPED;
		dwStyle = WS_POPUP;
	}
	else
	{
		dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;
		dwStyle = WS_OVERLAPPED;
	}

	AdjustWindowRectEx(&window_rect, dwStyle, false, dwExStyle);


	game_window = CreateWindowEx(dwExStyle,
			window_class.lpszClassName, GAMENAME,
			WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
			dwStyle,
			GetSystemMetrics(0) - GetSystemMetrics(0)/2 - window_rect.right / 2,
			GetSystemMetrics(1) - GetSystemMetrics(1)/2 - window_rect.bottom / 2,
			window_rect.right - window_rect.left,
			window_rect.bottom - window_rect.top,
			NULL, NULL, hInstance, NULL);

	if(!game_window)
	{
		
			LogToFile("debug.log","Failed to create game window");
			MessageBox(NULL, "Failed to create game window", "CreateWindowEx() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
					
			
	}

	pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
	pfd.nVersion = 1;
	pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
	pfd.iPixelType = PFD_TYPE_RGBA;
	pfd.cDepthBits = 24;
	pfd.iLayerType = PFD_MAIN_PLANE;
	pfd.cColorBits = cfg.scr_bpp;

	hDC = GetDC(game_window);

	if(!hDC)
	{
			LogToFile("debug.log","Failed to create device context");
			MessageBox(NULL, "Failed to create device context", "GetDC() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	pf = ChoosePixelFormat(hDC, &pfd);

	if(!pf)
	{
			LogToFile("debug.log","Failed to choose pixel format");
			MessageBox(NULL, "Failed to set pixel format", "ChoosePixelFormat() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	if(!SetPixelFormat(hDC, pf, &pfd))
	{
			LogToFile("debug.log","Failed to set pixel format");
			MessageBox(NULL, "Failed to set pixel format", "SetPixelFormat() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	hRC = wglCreateContext(hDC);

	if(!hRC)
	{
			LogToFile("debug.log","Failed to create rendering context");
			MessageBox(NULL, "Failed to create rendering context", "wglCreateContext() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	if(!wglMakeCurrent(hDC, hRC))
	{
			LogToFile("debug.log","Failed to make current context");
			MessageBox(NULL, "Failed to make current context", "wglMakeCurrent() Error", MB_OK | MB_ICONEXCLAMATION);
			PostQuitMessage(-1);
	}

	ShowWindow(game_window, SW_SHOW);
	SetForegroundWindow(game_window);
	SetFocus(game_window);
}
コード例 #29
0
ファイル: oglg2d.cpp プロジェクト: garinh/cs
bool csGraphics2DOpenGL::Open ()
{
  if (is_open) return true;

  csRef<iVerbosityManager> verbosemgr (
    csQueryRegistry<iVerbosityManager> (object_reg));
  if (verbosemgr) 
    detector.SetVerbose (verbosemgr->Enabled ("renderer.windows.gldriver"));
  
  // create the window.
  if (FullScreen)
  {
    SwitchDisplayMode (false);
  }

  int pixelFormat = -1;
  csGLPixelFormatPicker picker (this);
  /*
    Check if the WGL pixel format check should be used at all.
    It appears that some drivers take "odd" choices when using the WGL
    pixel format path (e.g. returning Accum-capable formats even if none
    was requested).
   */
  bool doWGLcheck = false;
  {
    GLPixelFormat format;
    if (picker.GetNextFormat (format))
    {
      doWGLcheck = (format[glpfvMultiSamples] != 0);
      picker.Reset ();
    }
  }
  if (doWGLcheck)
    pixelFormat = FindPixelFormatWGL (picker);

  m_bActivated = true;

  int wwidth = fbWidth;
  int wheight = fbHeight;
  DWORD exStyle = 0;
  DWORD style = WS_POPUP | WS_SYSMENU;
  int xpos = 0;
  int ypos = 0;
  if (FullScreen)
  {
    /*exStyle |= WS_EX_TOPMOST;*/
  }
  else
  {
    style |= WS_CAPTION | WS_MINIMIZEBOX;
    if (AllowResizing) 
      style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
    
    wwidth += 2 * GetSystemMetrics (SM_CXFIXEDFRAME);
    wheight += 2 * GetSystemMetrics (SM_CYFIXEDFRAME) + GetSystemMetrics (SM_CYCAPTION);
    xpos = (GetSystemMetrics (SM_CXSCREEN) - wwidth) / 2;
    ypos = (GetSystemMetrics (SM_CYSCREEN) - wheight) / 2;
  }

  m_hWnd = m_piWin32Assistant->CreateCSWindow (this, exStyle, style,
    xpos, ypos, wwidth, wheight);

  if (!m_hWnd)
    SystemFatalError (L"Cannot create Crystal Space window", GetLastError());

  SetTitle (win_title);
  
  // Subclass the window
  if (IsWindowUnicode (m_hWnd))
  {
    m_OldWndProc = (WNDPROC)SetWindowLongPtrW (m_hWnd, GWLP_WNDPROC, 
      (LONG_PTR) WindowProc);
    SetWindowLongPtrW (m_hWnd, GWLP_USERDATA, (LONG_PTR)this);
  }
  else
  {
    m_OldWndProc = (WNDPROC)SetWindowLongPtrA (m_hWnd, GWLP_WNDPROC, 
      (LONG_PTR) WindowProc);
    SetWindowLongPtrA (m_hWnd, GWLP_USERDATA, (LONG_PTR)this);
  }

  hDC = GetDC (m_hWnd);
  if (pixelFormat == -1)
  {
    picker.Reset();
    pixelFormat = FindPixelFormatGDI (hDC, picker);
  }

  PIXELFORMATDESCRIPTOR pfd;
  if (DescribePixelFormat (hDC, pixelFormat, 
    sizeof(PIXELFORMATDESCRIPTOR), &pfd) == 0)
    SystemFatalError (L"DescribePixelFormat failed.", GetLastError());

  if (SetPixelFormat (hDC, pixelFormat, &pfd) != TRUE)
  {
    HRESULT spfErr = (HRESULT)GetLastError();
    SystemFatalError (L"SetPixelFormat failed.", spfErr);
  }

  currentFormat[glpfvColorBits] = pfd.cColorBits;
  currentFormat[glpfvAlphaBits] = pfd.cAlphaBits;
  currentFormat[glpfvDepthBits] = pfd.cDepthBits;
  currentFormat[glpfvStencilBits] = pfd.cStencilBits;
  currentFormat[glpfvAccumColorBits] = pfd.cAccumBits;
  currentFormat[glpfvAccumAlphaBits] = pfd.cAccumAlphaBits;

  Depth = pfd.cColorBits; 

  hardwareAccelerated = !(pfd.dwFlags & PFD_GENERIC_FORMAT) ||
    (pfd.dwFlags & PFD_GENERIC_ACCELERATED);

  hGLRC = wglCreateContext (hDC);
  wglMakeCurrent (hDC, hGLRC);

  UpdateWindow (m_hWnd);
  ShowWindow (m_hWnd, m_nCmdShow);
  SetForegroundWindow (m_hWnd);
  SetFocus (m_hWnd);
  
  /* Small hack to emit "no HW acceleration" message on both GDI Generic and
   * sucky Direct3D default OpenGL */
  hardwareAccelerated &= 
    (strncmp ((char*)glGetString (GL_VENDOR), "Microsoft", 9) != 0);
  if (!hardwareAccelerated)
  {
    Report (CS_REPORTER_SEVERITY_WARNING,
      "No hardware acceleration!");
  }

  detector.DoDetection (m_hWnd, hDC);
  Report (CS_REPORTER_SEVERITY_NOTIFY,
    "GL driver: %s %s", detector.GetDriverDLL(), 
    detector.GetDriverVersion() ? detector.GetDriverVersion() : 
      "<version unknown>");

  if (FullScreen)
  {
    /* 
     * from the Windows Shell docs:
     * "It is possible to cover the taskbar by explicitly setting the size 
     * of the window rectangle equal to the size of the screen with 
     * SetWindowPos."
     */
    SetWindowPos (m_hWnd, CS_WINDOW_Z_ORDER, 0, 0, fbWidth, fbHeight, 0);
  }

  if (!csGraphics2DGLCommon::Open ())
    return false;

  ext.InitWGL_EXT_swap_control (hDC);

  if (ext.CS_WGL_EXT_swap_control)
  {
    ext.wglSwapIntervalEXT (vsync ? 1 : 0);
    vsync = (ext.wglGetSwapIntervalEXT() != 0);
    Report (CS_REPORTER_SEVERITY_NOTIFY,
      "VSync is %s.", 
      vsync ? "enabled" : "disabled");
  }

  return true;
}
コード例 #30
-1
ファイル: main.cpp プロジェクト: NetjerDjehuty/INFOMGP
bool createWindow(char* title, int width, int height)
{
	WNDCLASS wc;
	RECT rect;
	rect.left=0;
	rect.right=width;
	rect.top=0;
	rect.bottom=height;

	hInstance = GetModuleHandle(NULL);
	wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wc.lpfnWndProc = (WNDPROC) WndProc;
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hInstance = hInstance;
	wc.hIcon = LoadIcon(NULL, IDI_WINLOGO);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = NULL;
	wc.lpszMenuName = NULL;
	wc.lpszClassName = SAMPLE_NAME;

	if(!RegisterClass(&wc)) {
		return false;
	}

	AdjustWindowRectEx(&rect, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_APPWINDOW | WS_EX_WINDOWEDGE);

	if(!(hWnd=CreateWindowEx(WS_EX_APPWINDOW|WS_EX_WINDOWEDGE,SAMPLE_NAME,title,
							WS_OVERLAPPEDWINDOW|WS_CLIPSIBLINGS|WS_CLIPCHILDREN,
							0,0,rect.right-rect.left,rect.bottom-rect.top,
							NULL,NULL,hInstance,NULL))) {
		releaseWindow();
		return false;
	}

    static PIXELFORMATDESCRIPTOR pfd = {
		sizeof(PIXELFORMATDESCRIPTOR),
		1,
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
		PFD_TYPE_RGBA,
		32,
		0, 0,
		0, 0,
		0, 0,
		0, 0,
		0,
		0, 0, 0, 0,
		32,
		0,
		0,
		PFD_MAIN_PLANE,
		0,
		0, 0, 0
    };
	
	if(!(hDC=GetDC(hWnd)))
	{
		releaseWindow();
		OutputDebugString("");
		return FALSE;
	}
	
	int pixelformat;
	
    if ( (pixelformat = ChoosePixelFormat(hDC, &pfd)) == 0 ){
		OutputDebugString("ChoosePixelFormat Failed....");
        return FALSE;
    }

    if (SetPixelFormat(hDC, pixelformat, &pfd) == FALSE){
		OutputDebugString("SetPixelFormat Failed....");
        return FALSE;
    }

	if (!(hRC=wglCreateContext(hDC))){
		OutputDebugString("Creating HGLRC Failed....");
		return FALSE;
	}
	
	// Set Vsync
	//BOOL (WINAPI *wglSwapIntervalEXT)(int) = NULL;

	//if(strstr((char*)glGetString( GL_EXTENSIONS ),"WGL_EXT_swap_control")== 0) {
	//}
	//else {
		//wglSwapIntervalEXT = (BOOL (WINAPI*)(int))wglGetProcAddress("wglSwapIntervalEXT");
		//if(wglSwapIntervalEXT) wglSwapIntervalEXT(1);
	//}
	
	wglMakeCurrent(hDC,hRC);
	
	ShowWindow(hWnd,SW_SHOW);
	SetForegroundWindow(hWnd);
	SetFocus(hWnd);

	render_resize(width, height);
	
	glClearColor(0.0f,0.0f,0.0f,0.0f);
	glClearDepth(1.0f);
	
	return TRUE;
}