int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, INT iCmdShow) { HWND hwnd; HACCEL hAccel; MSG msg; WNDCLASS wndclass; char szAppName[] = TEXT("WinMain"); wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon(hInstance, "altEngine"); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = NULL; wndclass.lpszMenuName = NULL; wndclass.lpszClassName = Rigid_Body; if (!RegisterClass(&wndclass)) { MessageBox(NULL, TEXT("Unable to register window class."), Rigid_Body, MB_ICONERROR); return 0; } hwnd = CreateWindow( Rigid_Body, // window class name TEXT("Rigid Body Dynamics"), // window caption WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, // window style CW_USEDEFAULT, // initial x position CW_USEDEFAULT, // initial y position CW_USEDEFAULT, // initial x size CW_USEDEFAULT, // initial y size NULL, // parent window handle NULL, // window menu handle hInstance, // program instance handle NULL); // creation parameters hAccel = LoadAccelerators(hInstance, Rigid_Body); ShowWindow(hwnd, iCmdShow); UpdateWindow(hwnd); while (TRUE) { if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if ( GetMessage(&msg, NULL, 0, 0) > 0 ) { if (!TranslateAccelerator(hwnd, hAccel, &msg)) { TranslateMessage (&msg) ; DispatchMessage (&msg) ; } } else { break; } } else { SendMessage(hwnd, WMU_RENDER, 0, 0); } } if (!UnregisterClass(Rigid_Body, hInstance)) { MessageBox(NULL, TEXT("Unable to unregister class."), Rigid_Body, MB_ICONERROR); return 1; } return (int)msg.wParam; }
bool CCEGLView::Create(LPCTSTR pTitle, int w, int h) { bool bRet = false; do { CC_BREAK_IF(m_hWnd); HINSTANCE hInstance = GetModuleHandle( NULL ); WNDCLASS wc; // Windows Class Structure // Redraw On Size, And Own DC For Window. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = _WindowProc; // WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = hInstance; // Set The Instance wc.hIcon = LoadIcon( NULL, IDI_WINLOGO ); // Load The Default Icon wc.hCursor = LoadCursor( NULL, IDC_ARROW ); // Load The Arrow Pointer wc.hbrBackground = NULL; // No Background Required For GL wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName = kWindowClassName; // Set The Class Name CC_BREAK_IF(! RegisterClass(&wc) && 1410 != GetLastError()); // center window position RECT rcDesktop; GetWindowRect(GetDesktopWindow(), &rcDesktop); // create window m_hWnd = CreateWindowEx( WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, // Extended Style For The Window kWindowClassName, // Class Name pTitle, // Window Title WS_CAPTION | WS_POPUPWINDOW, // Defined Window Style 0, 0, // Window Position 0, // Window Width 0, // Window Height NULL, // No Parent Window NULL, // No Menu hInstance, // Instance NULL ); CC_BREAK_IF(! m_hWnd); m_eInitOrientation = CCDirector::sharedDirector()->getDeviceOrientation(); m_bOrientationInitVertical = (CCDeviceOrientationPortrait == m_eInitOrientation || kCCDeviceOrientationPortraitUpsideDown == m_eInitOrientation) ? true : false; m_tSizeInPoints.cx = w; m_tSizeInPoints.cy = h; resize(w, h); // init egl m_pEGL = CCEGL::create(this); if (! m_pEGL) { DestroyWindow(m_hWnd); m_hWnd = NULL; break; } s_pMainWindow = this; bRet = true; } while (0); return bRet; }
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag,int frequency) { WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style fullscreen=fullscreenflag; // Set The Global Fullscreen Flag // hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window. wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = hInstance; // Set The Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer wc.hbrBackground = NULL; // No Background Required For GL wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName = "TASpring"; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel dmScreenSettings.dmDisplayFrequency = frequency; dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; if(frequency) dmScreenSettings.dmFields|=DM_DISPLAYFREQUENCY; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode. if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE } else { // Pop Up A Message Box Letting User Know The Program Is Closing. MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP); return FALSE; // Return FALSE } } } if (fullscreen) // Are We Still In Fullscreen Mode? { dwExStyle=WS_EX_APPWINDOW; // Window Extended Style dwStyle=WS_POPUP; // Windows Style // HideMouse(); // Hide Mouse Pointer } else { dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style } // Create The Window if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window "TASpring", // Class Name title, // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style 0, 0, // Window Position width, height, // Selected Width And Height NULL, // No Parent Window NULL, // No Menu hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { KillGLWindow(); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 24, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 8, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context? { KillGLWindow(); // Reset The Display char t[500]; sprintf(t,"Can't Create A GL Device Context. %d",GetLastError()); MessageBox(NULL,t,"ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display char t[500]; sprintf(t,"Can't Create A GL Rendering Context. %d",GetLastError()); MessageBox(NULL,t,"ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } ShowWindow(hWnd,SW_SHOW); // Show The Window SetForegroundWindow(hWnd); // Slightly Higher Priority SetFocus(hWnd); // Sets Keyboard Focus To The Window ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(); // Reset The Display MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success }
bool Win32Factory::init() { const char* vlc_name = "VLC Media Player"; const char* vlc_icon = "VLC_ICON"; const char* vlc_class = "SkinWindowClass"; // Get instance handle m_hInst = GetModuleHandle( NULL ); if( m_hInst == NULL ) { msg_Err( getIntf(), "Cannot get module handle" ); } // Create window class WNDCLASS skinWindowClass; skinWindowClass.style = CS_DBLCLKS; skinWindowClass.lpfnWndProc = (WNDPROC)Win32Factory::Win32Proc; skinWindowClass.lpszClassName = _T(vlc_class); skinWindowClass.lpszMenuName = NULL; skinWindowClass.cbClsExtra = 0; skinWindowClass.cbWndExtra = 0; skinWindowClass.hbrBackground = NULL; skinWindowClass.hCursor = LoadCursor( NULL, IDC_ARROW ); skinWindowClass.hIcon = LoadIcon( m_hInst, _T(vlc_icon) ); skinWindowClass.hInstance = m_hInst; // Register class and check it if( !RegisterClass( &skinWindowClass ) ) { WNDCLASS wndclass; // Check why it failed. If it's because the class already exists // then fine, otherwise return with an error. if( !GetClassInfo( m_hInst, _T(vlc_class), &wndclass ) ) { msg_Err( getIntf(), "cannot register window class" ); return false; } } // Create Window m_hParentWindow = CreateWindowEx( WS_EX_TOOLWINDOW, _T(vlc_class), _T(vlc_name), WS_POPUP | WS_SYSMENU | WS_MINIMIZEBOX, -200, -200, 0, 0, 0, 0, m_hInst, 0 ); if( m_hParentWindow == NULL ) { msg_Err( getIntf(), "cannot create parent window" ); return false; } // Store with it a pointer to the interface thread SetWindowLongPtr( m_hParentWindow, GWLP_USERDATA, (LONG_PTR)getIntf() ); // We do it this way otherwise CreateWindowEx will fail // if WS_EX_LAYERED is not supported SetWindowLongPtr( m_hParentWindow, GWL_EXSTYLE, GetWindowLongPtr( m_hParentWindow, GWL_EXSTYLE ) | WS_EX_LAYERED ); ShowWindow( m_hParentWindow, SW_SHOW ); // Initialize the systray icon m_trayIcon.cbSize = sizeof( NOTIFYICONDATA ); m_trayIcon.hWnd = m_hParentWindow; m_trayIcon.uID = 42; m_trayIcon.uFlags = NIF_ICON|NIF_TIP|NIF_MESSAGE; m_trayIcon.uCallbackMessage = MY_WM_TRAYACTION; m_trayIcon.hIcon = LoadIcon( m_hInst, _T(vlc_icon) ); strcpy( m_trayIcon.szTip, vlc_name ); // Show the systray icon if needed if( var_InheritBool( getIntf(), "skins2-systray" ) ) { addInTray(); } // Show the task in the task bar if needed if( var_InheritBool( getIntf(), "skins2-taskbar" ) ) { addInTaskBar(); } // Initialize the OLE library (for drag & drop) OleInitialize( NULL ); // Initialize the resource path char *datadir = config_GetUserDir( VLC_DATA_DIR ); m_resourcePath.push_back( (string)datadir + "\\skins" ); free( datadir ); datadir = config_GetDataDir(); m_resourcePath.push_back( (string)datadir + "\\skins" ); m_resourcePath.push_back( (string)datadir + "\\skins2" ); m_resourcePath.push_back( (string)datadir + "\\share\\skins" ); m_resourcePath.push_back( (string)datadir + "\\share\\skins2" ); free( datadir ); // Enumerate all monitors available EnumDisplayMonitors( NULL, NULL, MonitorEnumProc, (LPARAM)&m_monitorList ); int num = 0; for( list<HMONITOR>::iterator it = m_monitorList.begin(); it != m_monitorList.end(); ++it, num++ ) { MONITORINFO mi; mi.cbSize = sizeof( MONITORINFO ); if( GetMonitorInfo( *it, &mi ) ) { msg_Dbg( getIntf(), "monitor #%i, %ldx%ld at +%ld+%ld", num, mi.rcMonitor.right - mi.rcMonitor.left, mi.rcMonitor.bottom - mi.rcMonitor.top, mi.rcMonitor.left, mi.rcMonitor.top ); } } // All went well return true; }
void Win32EGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title ) { // destroy current window, if any if (mWindow) destroy(); #ifdef OGRE_STATIC_LIB HINSTANCE hInst = GetModuleHandle( NULL ); #else # if OGRE_DEBUG_MODE == 1 HINSTANCE hInst = GetModuleHandle("RenderSystem_GLES_d.dll"); # else HINSTANCE hInst = GetModuleHandle("RenderSystem_GLES.dll"); # endif #endif mWindow = 0; mClosed = false; mIsDepthBuffered = true; mColourDepth = mIsFullScreen? 32 : GetDeviceCaps(GetDC(0), BITSPIXEL); HWND parent = 0; bool vsync = false; String border; bool outerSize = false; bool hwGamma = false; int monitorIndex = -1; HMONITOR hMonitor = NULL; if (!mIsExternal) { DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN; DWORD dwStyleEx = 0; MONITORINFOEX monitorInfoEx; RECT rc; // If we didn't specified the adapter index, or if it didn't find it if (hMonitor == NULL) { POINT windowAnchorPoint; // Fill in anchor point. windowAnchorPoint.x = left; windowAnchorPoint.y = top; // Get the nearest monitor to this window. hMonitor = MonitorFromPoint(windowAnchorPoint, MONITOR_DEFAULTTONEAREST); } // Get the target monitor info memset(&monitorInfoEx, 0, sizeof(MONITORINFOEX)); monitorInfoEx.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(hMonitor, &monitorInfoEx); //size_t devNameLen = strlen(monitorInfoEx.szDevice); //mDeviceName = new char[devNameLen + 1]; //strcpy(mDeviceName, monitorInfoEx.szDevice); // No specified top left -> Center the window in the middle of the monitor if (left == -1 || top == -1) { int screenw = monitorInfoEx.rcMonitor.right - monitorInfoEx.rcMonitor.left; int screenh = monitorInfoEx.rcMonitor.bottom - monitorInfoEx.rcMonitor.top; SetRect(&rc, 0, 0, width, height); AdjustWindowRect(&rc, dwStyle, false); // clamp window dimensions to screen size int outerw = (rc.right-rc.left < screenw)? rc.right-rc.left : screenw; int outerh = (rc.bottom-rc.top < screenh)? rc.bottom-rc.top : screenh; if (left == -1) left = monitorInfoEx.rcMonitor.left + (screenw - outerw) / 2; else if (monitorIndex != -1) left += monitorInfoEx.rcMonitor.left; if (top == -1) top = monitorInfoEx.rcMonitor.top + (screenh - outerh) / 2; else if (monitorIndex != -1) top += monitorInfoEx.rcMonitor.top; } else if (monitorIndex != -1) { left += monitorInfoEx.rcMonitor.left; top += monitorInfoEx.rcMonitor.top; } mWidth = width; mHeight = height; mTop = top; mLeft = left; if (mIsFullScreen) { dwStyle |= WS_POPUP; dwStyleEx |= WS_EX_TOPMOST; mTop = monitorInfoEx.rcMonitor.top; mLeft = monitorInfoEx.rcMonitor.left; } else { if (parent) { dwStyle |= WS_CHILD; } else { if (border == "none") dwStyle |= WS_POPUP; else if (border == "fixed") dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; else dwStyle |= WS_OVERLAPPEDWINDOW; } int screenw = GetSystemMetrics(SM_CXSCREEN); int screenh = GetSystemMetrics(SM_CYSCREEN); if (!outerSize) { // Calculate window dimensions required // to get the requested client area SetRect(&rc, 0, 0, mWidth, mHeight); AdjustWindowRect(&rc, dwStyle, false); mWidth = rc.right - rc.left; mHeight = rc.bottom - rc.top; // Clamp window rect to the nearest display monitor. if (mLeft < monitorInfoEx.rcMonitor.left) mLeft = monitorInfoEx.rcMonitor.left; if (mTop < monitorInfoEx.rcMonitor.top) mTop = monitorInfoEx.rcMonitor.top; if ((int)mWidth > monitorInfoEx.rcMonitor.right - mLeft) mWidth = monitorInfoEx.rcMonitor.right - mLeft; if ((int)mHeight > monitorInfoEx.rcMonitor.bottom - mTop) mHeight = monitorInfoEx.rcMonitor.bottom - mTop; } } // register class and create window WNDCLASS wc = { CS_OWNDC, WindowEventUtilities::_WndProc, 0, 0, hInst, LoadIcon(NULL, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW), (HBRUSH)GetStockObject(BLACK_BRUSH), NULL, "OgreGLWindow" }; RegisterClass(&wc); if (mIsFullScreen) { DEVMODE displayDeviceMode; memset(&displayDeviceMode, 0, sizeof(displayDeviceMode)); displayDeviceMode.dmSize = sizeof(DEVMODE); displayDeviceMode.dmBitsPerPel = mColourDepth; displayDeviceMode.dmPelsWidth = mWidth; displayDeviceMode.dmPelsHeight = mHeight; displayDeviceMode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; /* if (mDisplayFrequency) { displayDeviceMode.dmDisplayFrequency = mDisplayFrequency; displayDeviceMode.dmFields |= DM_DISPLAYFREQUENCY; if (ChangeDisplaySettingsEx(mDeviceName, &displayDeviceMode, NULL, CDS_FULLSCREEN | CDS_TEST, NULL) != DISP_CHANGE_SUCCESSFUL) { LogManager::getSingleton().logMessage(LML_NORMAL, "ChangeDisplaySettings with user display frequency failed"); displayDeviceMode.dmFields ^= DM_DISPLAYFREQUENCY; } } if (ChangeDisplaySettingsEx(mDeviceName, &displayDeviceMode, NULL, CDS_FULLSCREEN, NULL) != DISP_CHANGE_SUCCESSFUL) LogManager::getSingleton().logMessage(LML_CRITICAL, "ChangeDisplaySettings failed"); */ } // Pass pointer to self as WM_CREATE parameter mWindow = CreateWindowEx(dwStyleEx, "OgreGLWindow", title.c_str(), dwStyle, mLeft, mTop, mWidth, mHeight, parent, 0, hInst, this); WindowEventUtilities::_addRenderWindow(this); LogManager::getSingleton().stream() << "Created Win32Window '" << mName << "' : " << mWidth << "x" << mHeight << ", " << mColourDepth << "bpp"; } RECT rc; // top and left represent outer window position GetWindowRect(mWindow, &rc); mTop = rc.top; mLeft = rc.left; // width and height represent drawable area only GetClientRect(mWindow, &rc); mWidth = rc.right; mHeight = rc.bottom; mNativeDisplay = GetDC(mWindow); mEglDisplay = eglGetDisplay(mNativeDisplay); mGLSupport->setGLDisplay(mEglDisplay); mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow); }
//--------------------------------------------------------------------------- bool CInternalWindow::BeginSplash() { #ifdef _WIN32 // load bitmap HANDLE hbmpSplash = LoadImage(GetModuleHandle( NULL ), _W("splash.bmp"), IMAGE_BITMAP, 0,0, LR_DEFAULTSIZE | LR_LOADFROMFILE); if (!hbmpSplash) return false; // Register splash class WNDCLASS wc = { 0 }; wc.lpfnWndProc = DefWindowProc; wc.hInstance = GetModuleHandle( NULL ); wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = _W("P3DSplash"); RegisterClass(&wc); // Create splash window and layered content widget m_hsplash = CreateWindow(_W("P3DSplash"), NULL, WS_POPUP, 0, 0, 0, 0, NULL, NULL, wc.hInstance, NULL); HWND m_hlayered = CreateWindowEx(WS_EX_LAYERED, _W("P3DSplash"), NULL, WS_POPUP | WS_VISIBLE, 0, 0, 0, 0, m_hsplash, NULL, wc.hInstance, NULL); // get the size of the bitmap BITMAP bm; GetObjectW(hbmpSplash, sizeof(bm), &bm); SIZE sizeSplash = { bm.bmWidth, bm.bmHeight }; // get the primary monitor's info POINT ptZero = { 0 }; HMONITOR hmonPrimary = MonitorFromPoint(ptZero, MONITOR_DEFAULTTOPRIMARY); MONITORINFO monitorinfo = { 0 }; monitorinfo.cbSize = sizeof(monitorinfo); GetMonitorInfo(hmonPrimary, &monitorinfo); // center the splash screen in the middle of the primary work area const RECT & rcWork = monitorinfo.rcWork; POINT ptOrigin; ptOrigin.x = rcWork.left + (rcWork.right - rcWork.left - sizeSplash.cx) / 2; ptOrigin.y = rcWork.top + (rcWork.bottom - rcWork.top - sizeSplash.cy) / 2; // create a memory DC holding the splash bitmap HDC hdcScreen = GetDC(NULL); HDC hdcMem = CreateCompatibleDC(hdcScreen); HBITMAP hbmpOld = (HBITMAP) SelectObject(hdcMem, hbmpSplash); // use the source image's alpha channel for blending BLENDFUNCTION blend = { 0 }; blend.BlendOp = AC_SRC_OVER; blend.SourceConstantAlpha = 255; blend.AlphaFormat = AC_SRC_ALPHA; // paint the window (in the right location) with the alpha-blended bitmap UpdateLayeredWindow(m_hlayered, hdcScreen, &ptOrigin, &sizeSplash, hdcMem, &ptZero, RGB(0, 0, 0), &blend, ULW_ALPHA); // delete temporary objects SelectObject(hdcMem, hbmpOld); DeleteDC(hdcMem); ReleaseDC(NULL, hdcScreen); #elif defined(X_WIN_PRESENT) //load the splash image using Imlib2 Imlib_Image image = imlib_load_image("splash.bmp"); if(!image) return false; imlib_context_set_image(image); //obtain root window (current screen) attributes int screen = DefaultScreen(m_display); XWindowAttributes rootWinAttribs; XGetWindowAttributes #endif return true; }
static LONG WINAPI exceptionPrinter( LPEXCEPTION_POINTERS ep ) { EnumWindows( enumWindowsForDisable,GetCurrentProcessId() ); #define DWARFSTACK_DIALOG_CLASS TEXT("dwarfstack_exception_dialog") WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = exceptionWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = DLGWINDOWEXTRA; wc.hInstance = GetModuleHandle( NULL ); wc.hIcon = NULL; wc.hCursor = LoadCursor( NULL,IDC_ARROW ); wc.hbrBackground = (HBRUSH)( COLOR_BTNFACE+1 ); wc.lpszMenuName = NULL; wc.lpszClassName = DWARFSTACK_DIALOG_CLASS; RegisterClass( &wc ); int sw = GetSystemMetrics( SM_CXSCREEN ); int sh = GetSystemMetrics( SM_CYSCREEN ); #define DLG_W 500 #define DLG_H 500 HWND hwnd = CreateWindow( DWARFSTACK_DIALOG_CLASS,TEXT("application crashed"), WS_CAPTION,(sw-DLG_W)/2,(sh-DLG_H)/2,DLG_W,DLG_H, NULL,NULL,GetModuleHandle(NULL),NULL ); RECT rect; GetClientRect( hwnd,&rect ); int w = rect.right - rect.left; int h = rect.bottom - rect.top; HWND textHwnd = CreateWindow( TEXT("edit"),TEXT(""), WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER|WS_HSCROLL|WS_VSCROLL| ES_MULTILINE|ES_AUTOHSCROLL|ES_AUTOVSCROLL|ES_READONLY, 0,0,w,h-32,hwnd,NULL,NULL,NULL ); CreateWindow( TEXT("button"),TEXT("OK"), WS_CHILD|WS_VISIBLE|WS_TABSTOP|BS_DEFPUSHBUTTON, (w-50)/2,h-28,50,24, hwnd,(HMENU)IDCANCEL,NULL,NULL ); #ifdef DWST_SHARED // needs -lgdi32 -> only in shared library HFONT font = GetStockObject( ANSI_FIXED_FONT ); if( font ) SendMessage( textHwnd,WM_SETFONT,(WPARAM)font,FALSE ); #endif { TCHAR exeName[MAX_PATH]; if( GetModuleFileName(GetModuleHandle(NULL),exeName,MAX_PATH) ) { Edit_ReplaceSel( textHwnd,TEXT("application:\r\n") ); Edit_ReplaceSel( textHwnd,exeName ); Edit_ReplaceSel( textHwnd,TEXT("\r\n\r\n") ); } } if( myExtraInfo ) { Edit_ReplaceSel( textHwnd,TEXT("extra information:\r\n") ); Edit_ReplaceSel( textHwnd,myExtraInfo ); Edit_ReplaceSel( textHwnd,TEXT("\r\n\r\n") ); } DWORD code = ep->ExceptionRecord->ExceptionCode; const TCHAR *desc = NULL; switch( code ) { #define EX_DESC( name ) \ case EXCEPTION_##name: desc = TEXT(" (") #name ")"; \ break EX_DESC( ACCESS_VIOLATION ); EX_DESC( ARRAY_BOUNDS_EXCEEDED ); EX_DESC( BREAKPOINT ); EX_DESC( DATATYPE_MISALIGNMENT ); EX_DESC( FLT_DENORMAL_OPERAND ); EX_DESC( FLT_DIVIDE_BY_ZERO ); EX_DESC( FLT_INEXACT_RESULT ); EX_DESC( FLT_INVALID_OPERATION ); EX_DESC( FLT_OVERFLOW ); EX_DESC( FLT_STACK_CHECK ); EX_DESC( FLT_UNDERFLOW ); EX_DESC( ILLEGAL_INSTRUCTION ); EX_DESC( IN_PAGE_ERROR ); EX_DESC( INT_DIVIDE_BY_ZERO ); EX_DESC( INT_OVERFLOW ); EX_DESC( INVALID_DISPOSITION ); EX_DESC( NONCONTINUABLE_EXCEPTION ); EX_DESC( PRIV_INSTRUCTION ); EX_DESC( SINGLE_STEP ); EX_DESC( STACK_OVERFLOW ); } TCHAR hexNum[20]; Edit_ReplaceSel( textHwnd,TEXT("code: 0x") ); _stprintf( hexNum,TEXT("%08lX"),code ); Edit_ReplaceSel( textHwnd,hexNum ); if( desc ) Edit_ReplaceSel( textHwnd,desc ); Edit_ReplaceSel( textHwnd,TEXT("\r\n") ); if( code==EXCEPTION_ACCESS_VIOLATION && ep->ExceptionRecord->NumberParameters==2 ) { ULONG_PTR flag = ep->ExceptionRecord->ExceptionInformation[0]; ULONG_PTR addr = ep->ExceptionRecord->ExceptionInformation[1]; Edit_ReplaceSel( textHwnd, flag==8?TEXT("data execution prevention"): (flag?TEXT("write access"):TEXT("read access")) ); Edit_ReplaceSel( textHwnd,TEXT(" violation at 0x") ); _stprintf( hexNum,TEXT("%p"),(void*)addr ); Edit_ReplaceSel( textHwnd,hexNum ); Edit_ReplaceSel( textHwnd,TEXT("\r\n") ); } Edit_ReplaceSel( textHwnd,TEXT("\r\n") ); struct dialog_info di = { 0,textHwnd,NULL }; dwstOfException( ep->ContextRecord,&dlgPrint,&di ); SendMessage( hwnd,WM_NEXTDLGCTL,(WPARAM)textHwnd,TRUE ); Edit_SetSel( textHwnd,0,0 ); ShowWindow( hwnd,SW_SHOW ); UpdateWindow( hwnd ); MSG msg; while( GetMessage(&msg,NULL,0,0) ) { if( IsDialogMessage(hwnd,&msg) ) continue; TranslateMessage( &msg ); DispatchMessage( &msg ); } return( EXCEPTION_EXECUTE_HANDLER ); }
bool ApplicationWindow_WGL::createWindow( std::string title, Vector2 position, Vector2 size, bool fullscreen, const ParameterMap *parameters) { _renderer = Renderer::getSingletonPtr(); HWND parentWnd = nullptr; int bpp = 32; int PixelFormat; // Holds The Results After Searching For A Match WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; if(parameters != nullptr) { ParameterMap::const_iterator it; ParameterMap::const_iterator itEnd = parameters->end(); if ( (it = parameters->find("parent_window")) != itEnd ) { parentWnd = (HWND) atoi(it->second.c_str()); dwStyle = WS_CHILD; } } Vector2 sceneSize = _renderer->_sceneViewMax - _renderer->_sceneViewMin; _aspectRatio = sceneSize.x / sceneSize.y; _fullscreen = fullscreen; _hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window. wc.lpfnWndProc = &ApplicationWindow_WGL::initialWndProc;// WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = _hInstance; // Set The Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer wc.hbrBackground = NULL; // No Background Required For GL wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName = SKETCHYDYNAMICS_WINDOW_CLASS_NAME; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Failed To Register The Window Class"); return FALSE; // Return FALSE } if (fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = (long)size.x; // Selected Screen Width dmScreenSettings.dmPelsHeight = (long)size.y; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bpp; // Selected Bits Per Pixel dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails, Use Windowed Mode. fullscreen=FALSE; Logger::getSingletonPtr()->writeWarning("Fullscreen mode not supported"); } } if (fullscreen) // Are We Still In Fullscreen Mode? { dwExStyle=WS_EX_APPWINDOW; // Window Extended Style dwStyle=WS_POPUP; // Windows Style //ShowCursor(FALSE); // Hide Mouse Pointer } RECT WindowRect; WindowRect.left = (long)position.x; WindowRect.right = (long)(position.x + size.x); WindowRect.top = (long)position.y; WindowRect.bottom = (long)(position.y + size.y); AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (!(_hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window SKETCHYDYNAMICS_WINDOW_CLASS_NAME, // Class Name title.c_str(), // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style (int)position.x, (int)position.y, // Window Position WindowRect.right-WindowRect.left, // Calculate Window Width WindowRect.bottom-WindowRect.top, // Calculate Window Height parentWnd, // Parent Window NULL, // No Menu _hInstance, // Instance this))) // Pass To WM_CREATE { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Window Creation Error"); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd= // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format bpp, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(_hDC=GetDC(_hWnd))) // Did We Get A Device Context? { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Create A GL Device Context"); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(_hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Find A Suitable PixelFormat"); return FALSE; // Return FALSE } if(!SetPixelFormat(_hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Set The PixelFormat"); return FALSE; // Return FALSE } if (!(_hRC=wglCreateContext(_hDC))) // Are We Able To Get A Rendering Context? { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Create A GL Rendering Context"); return FALSE; // Return FALSE } if(!wglMakeCurrent(_hDC,_hRC)) // Try To Activate The Rendering Context { destroyWindow(); // Reset The Display Logger::getSingletonPtr()->writeError("{ApplicationWindow_WGL}Can't Activate The GL Rendering Context"); return FALSE; // Return FALSE } ShowWindow(_hWnd, SW_SHOW); // Show The Window SetForegroundWindow(_hWnd); // Slightly Higher Priority SetFocus(_hWnd); // Sets Keyboard Focus To The Window resizeGLScene((int)size.x, (int)size.y); // Set Up Our Perspective GL Screen if(!_renderer->initGL()) { SKETCHYDYNAMICS_LOG_ERROR("OpenGL init failed"); destroyWindow(); return FALSE; } setVSync(false); return TRUE; // Success }
// WINDOWS MAIN FUNCTION // hInst = current instance of the program // hPrevInst = previous instance which is not used anymore. // cmdLine = holds command line arguments to be passed in to the program // cmdShow = holds an integer to specify if we want to show this window. int CALLBACK WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR cmdLine, int cmdShow) { WNDCLASS wc = {0}; wc.style = CS_HREDRAW | CS_VREDRAW; wc.hInstance = hInst; wc.hbrBackground = (HBRUSH)COLOR_WINDOW; wc.lpszClassName = wndClassName; wc.hCursor = 0; //TODO: Add cursors and icons to this program. wc.hIcon = 0; wc.lpfnWndProc = (WNDPROC)wndProc; RegisterClass(&wc); HWND window = CreateWindow(wndClassName, wndTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, wndWidth, wndHeight, 0, 0, hInst, 0); if(window) { ShowWindow(window, SW_SHOW); UpdateWindow(window); // NOTE: Initializing SDL if(SDL_Init(SDL_INIT_VIDEO) != 0 ) { DestroyWindow(window); return -2; } IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG); sdlWindow = SDL_CreateWindowFrom((void*)window); char error[MAX_PATH]; stringCopy(error, SDL_GetError()); OutputDebugStringA(error); if(!sdlWindow) { SDL_Quit(); DestroyWindow(window); return -3; } renderer = SDL_CreateRenderer(sdlWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(!renderer) { SDL_DestroyWindow(sdlWindow); SDL_Quit(); DestroyWindow(window); return -4; } i32 RefreshRate = 0; HDC dc = GetDC(window); i32 winRefreshRate = GetDeviceCaps(dc, VREFRESH); if( winRefreshRate > 1 ) { RefreshRate = winRefreshRate / 2; } else { RefreshRate = 30; } r32 targetSecsPerFrame = 1.0f / RefreshRate; GameMemory memory = {}; memory.permanentSize = Megabytes(64); memory.transientSize = Megabytes(64); memory.totalSize = memory.permanentSize + memory.transientSize; gameMemoryBlock = VirtualAlloc( 0, memory.totalSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if(!gameMemoryBlock) { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(sdlWindow); SDL_Quit(); DestroyWindow(window); return -5; } memory.permanentBlock = gameMemoryBlock; memory.transientBlock = (i8*)gameMemoryBlock + memory.permanentSize; memory.readEntireFile = ReadEntireFile; memory.freeFile = FreeFile; memory.writeEntireFile = WriteEntireFile; Win32Dims windowDims = GetWindowDimensions(window); Render render = {}; render.renderer = renderer; render.screenW = windowDims.width; render.screenH = windowDims.height; GameController input = {0}; input.dt = targetSecsPerFrame; Win32State state = {0}; state.memoryBlock = gameMemoryBlock; state.memorySize = memory.totalSize; GameCodeDLL gameCode = Win32LoadGameCode("Game.dll", "Game_temp.dll", "lock.tmp"); isRunning = true; r32 sleepIsGranular = (timeBeginPeriod(1) == TIMERR_NOERROR); LARGE_INTEGER lastCounter = Win32GetClock(); i64 lastCycles = __rdtsc(); LARGE_INTEGER performanceFreqPerSecRes; QueryPerformanceFrequency(&performanceFreqPerSecRes); globalPerformanceCountFreq = performanceFreqPerSecRes.QuadPart; // NOTE: PROGRAM LOOP!! while(isRunning) { // NOTE: compare File times for us to be able to reload the new game code FILETIME currentFileTime = Win32GetLastWriteTime("Game.dll"); if(CompareFileTime(¤tFileTime, &gameCode.lastWriteTime) != 0) { Win32UnloadGameCode(&gameCode); gameCode = Win32LoadGameCode("Game.dll", "Game_temp.dll", "lock.tmp"); } MSG msg = {0}; while(PeekMessage(&msg, window, 0, 0, PM_REMOVE)) { switch(msg.message) { case WM_CLOSE: { isRunning = false; }break; case WM_KEYUP: case WM_KEYDOWN: case WM_SYSKEYUP: case WM_SYSKEYDOWN: { u32 vkCode = (u32)msg.wParam; // This contains the keycode for the key that the user pressed. bool isDown = ((msg.lParam & (1 << 31)) == 0); // Check to see if the key is down now. bool wasDown = ((msg.lParam & (1 << 30)) != 0); // Check to see if the key was down previously. if(isDown != wasDown) { if(vkCode == 'W') { input.moveUp.isDown = isDown; } else if(vkCode == 'S') { input.moveDown.isDown = isDown; } else if(vkCode == 'A') { input.moveLeft.isDown = isDown; } else if(vkCode == 'D') { input.moveRight.isDown = isDown; } if(vkCode == VK_UP) { input.actionUp.isDown = isDown; } else if(vkCode == VK_DOWN) { input.actionDown.isDown = isDown; } else if(vkCode == VK_LEFT) { input.actionLeft.isDown = isDown; } else if(vkCode == VK_RIGHT) { input.actionRight.isDown = isDown; } else if(vkCode == VK_ESCAPE) { input.back.isDown = isDown; } else if(vkCode == 'O') { if(isDown) { if(state.recordingIndex == 0) { BeginRecording(&state, 1); } else { EndRecording(&state); BeginPlayback(&state, 1); } } } else if(vkCode == 'P') { if(isDown) { if(state.playbackIndex > 0) { EndPlayback(&state); ZeroMemory(&input, sizeof(input)); } } } } if(isDown) { bool AltKeyWasDown = ((msg.lParam & (1 << 29)) != 0); if(vkCode == VK_RETURN && AltKeyWasDown) { if(msg.hwnd) { isFullscreen = !isFullscreen; Win32FullscreenToggle(msg.hwnd); } } } }break; default: { TranslateMessage(&msg); DispatchMessage(&msg); } } } if(input.back.isDown) { isRunning = false; PostQuitMessage(0); } if(state.recordingIndex > 0) { RecordingInput(&state, &input); } else if(state.playbackIndex > 0) { PlaybackInput(&state, &input); } Win32Dims windowDims = GetWindowDimensions(window); Win32UpdateWindow(windowDims, (i32*)&render.screenW, (i32*)&render.screenH); if(gameCode.UpdateRender) { gameCode.UpdateRender(&memory, &input, &render); } LARGE_INTEGER workCounter = Win32GetClock(); r32 workSecsElapsed = Win32GetSecondsElapsed(lastCounter, workCounter); r32 secondsElapsed = workSecsElapsed; if(secondsElapsed < targetSecsPerFrame) { if(sleepIsGranular) { DWORD sleepMS = (DWORD)(1000.0f * (targetSecsPerFrame - secondsElapsed)); if(sleepMS > 0) { Sleep(sleepMS); } } r32 testSecsElapsed = Win32GetSecondsElapsed(lastCounter, Win32GetClock()); if(testSecsElapsed < targetSecsPerFrame) { //TODO: LOG MISSED SLEEP HERE!! } while(secondsElapsed < targetSecsPerFrame) { secondsElapsed = Win32GetSecondsElapsed(lastCounter, Win32GetClock()); } } else { //TODO: MISSED FRAME RATE!! } LARGE_INTEGER endCounter = Win32GetClock(); i64 endCycles = __rdtsc(); r64 elapsedCounts = (r64)(endCounter.QuadPart - lastCounter.QuadPart); r64 elapsedCycles = (r64)(endCycles - lastCycles); r32 MSperFrame = ((1000.0f * Win32GetSecondsElapsed(lastCounter, endCounter))); r32 FPS = (r32)(globalPerformanceCountFreq / elapsedCounts); r32 MegaCyclesPerFrame = (r32)(elapsedCycles / (1000.0f * 1000.0f)); char buffer[256]; sprintf_s(buffer, "%.02fms, %.02ffps, %.02fmcpf\n", MSperFrame, FPS, MegaCyclesPerFrame); OutputDebugStringA(buffer); lastCounter = endCounter; lastCycles = endCycles; } // NOTE: END OF WHILE LOOP //IMPORTANT: Unload this when we exit the program. Win32UnloadGameCode(&gameCode); } else { // TODO: Handle Error Loggin here!! return -1; } if(gameMemoryBlock) { VirtualFree(gameMemoryBlock, 0, MEM_RELEASE); } //Close SDL_DestroyRenderer(renderer); SDL_DestroyWindow(sdlWindow); IMG_Quit(); SDL_Quit(); DestroyWindow(window); return 0; }
bool d3d::InitD3D( HINSTANCE hInstance, int width, int height, bool windowed, D3DDEVTYPE deviceType, IDirect3DDevice9** device) { // // Create the main application window. // WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)d3d::WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(0, IDI_APPLICATION); wc.hCursor = LoadCursor(0, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = 0; wc.lpszClassName = "Direct3D9App"; if( !RegisterClass(&wc) ) { ::MessageBox(0, "RegisterClass() - FAILED", 0, 0); return false; } HWND hwnd = 0; hwnd = ::CreateWindow("Direct3D9App", "Direct3D9App", WS_EX_TOPMOST, 0, 0, width, height, 0 /*parent hwnd*/, 0 /* menu */, hInstance, 0 /*extra*/); if( !hwnd ) { ::MessageBox(0, "CreateWindow() - FAILED", 0, 0); return false; } ::ShowWindow(hwnd, SW_SHOW); ::UpdateWindow(hwnd); // // Init D3D: // HRESULT hr = 0; // Step 1: Create the IDirect3D9 object. IDirect3D9* d3d9 = 0; d3d9 = Direct3DCreate9(D3D_SDK_VERSION); if( !d3d9 ) { ::MessageBox(0, "Direct3DCreate9() - FAILED", 0, 0); return false; } // Step 2: Check for hardware vp. D3DCAPS9 caps; d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, deviceType, &caps); int vp = 0; if( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) vp = D3DCREATE_HARDWARE_VERTEXPROCESSING; else vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; // Step 3: Fill out the D3DPRESENT_PARAMETERS structure. D3DPRESENT_PARAMETERS d3dpp; d3dpp.BackBufferWidth = width; d3dpp.BackBufferHeight = height; d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; d3dpp.BackBufferCount = 1; d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; d3dpp.MultiSampleQuality = 0; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = hwnd; d3dpp.Windowed = windowed; d3dpp.EnableAutoDepthStencil = true; d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; d3dpp.Flags = 0; d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Step 4: Create the device. hr = d3d9->CreateDevice( D3DADAPTER_DEFAULT, // primary adapter deviceType, // device type hwnd, // window associated with device vp, // vertex processing &d3dpp, // present parameters device); // return created device if( FAILED(hr) ) { // try again using a 16-bit depth buffer d3dpp.AutoDepthStencilFormat = D3DFMT_D16; hr = d3d9->CreateDevice( D3DADAPTER_DEFAULT, deviceType, hwnd, vp, &d3dpp, device); if( FAILED(hr) ) { d3d9->Release(); // done with d3d9 object ::MessageBox(0, "CreateDevice() - FAILED", 0, 0); return false; } } d3d9->Release(); // done with d3d9 object return true; }
/* This Code Creates Our OpenGL Window. Parameters Are: * * title - Title To Appear At The Top Of The Window * * width - Width Of The GL Window Or Full screen Mode * * height - Height Of The GL Window Or Full screen Mode * * bits - Number Of Bits To Use For Color (8/16/24/32) * * fullscreenflag - Use Full screen Mode (TRUE) Or Windowed Mode (FALSE) */ BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullScreenFlag) { GLuint PixelFormat; // Holds the results after searching for a match WNDCLASS wc; // Windows class structure DWORD dwExStyle; // Window extended style DWORD dwStyle; // Window style RECT WindowRect; // Grabs rectangle upper left/lower right values WindowRect.left = (long)0; // Set left value to 0 WindowRect.right = (long)width; // Set right value to requested width WindowRect.top = (long)0; // Set top value to 0 WindowRect.bottom = (long)height; // Set bottom value to requested height g_bFullscreen = fullScreenFlag; // Set the global full screen flag hInstance = GetModuleHandle(NULL); // Grab an instance for out window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw on size, and own DC for window wc.lpfnWndProc = (WNDPROC)WndProc; // WndProc handles messages wc.cbClsExtra = 0; // No extra window data wc.cbWndExtra = 0; // No extra window data wc.hInstance = hInstance; // Set the instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load the default icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load the arrow pointer wc.hbrBackground = NULL; // No background required for GL wc.lpszMenuName = NULL; // We don't want a menu wc.lpszClassName = CLASSNAME; // Set the class name if (!RegisterClass(&wc)) // Attempt to register the window class { MessageBox(NULL, MSG_REGISTERCLASSFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (g_bFullscreen) { DEVMODE dmScreenSettings; // Device mode memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Makes sure memory's cleared dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size of the devmode structure dmScreenSettings.dmPelsWidth = width; // Selected screen width dmScreenSettings.dmPelsHeight = height; // Selected screen height dmScreenSettings.dmBitsPerPel = bits; // Selected bits per pixel dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Try to set selected mode and get results. NOTE: CDS_FULLSCREEN gets rid of start bar. if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { // If the mode failed, offer two options. Quit or use windowed mode. if (MessageBox(NULL, MSG_FULLSCREENNOTSUPPORT, ARTIST_NAME, MB_YESNO | MB_ICONEXCLAMATION) == IDYES) { g_bFullscreen = FALSE; // Windowed mode selected. Fullscreen = FALSE } else { // Pop up a message box letting user know the program is closing. MessageBox(NULL, MSG_PROGRAMNOTCLOSE, ERR_ERROR, MB_OK | MB_ICONSTOP); return FALSE; // Return FALSE } } } if (g_bFullscreen) // Are we still in fullscreen mode? { dwExStyle = WS_EX_APPWINDOW; // Window extended style dwStyle = WS_POPUP; // Windows Style ShowCursor(FALSE); // Hide mouse pointer } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Windows Extended style dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust window to true requested size // Create the window if (!(hWnd = CreateWindowEx(dwExStyle, // Extended style for the window CLASSNAME, // Class name title, // Window title dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, // Defined window style 0, 0, // Window position WindowRect.right - WindowRect.left, // Calculate window width WindowRect.bottom - WindowRect.top, // Calculate window height NULL, // No parent window NULL, // No menu hInstance, // Instance NULL))) // Don't pass anything to WM_CREATE { KillGLWindow(); // Reset the display MessageBox(NULL, MSG_CREATEWINDOWFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd = // pfd tells widows how we want things to be { sizeof(PIXELFORMATDESCRIPTOR), // Size of this pixel format descriptor 1, // Version number PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // Format must support window/opengl/double buffering PFD_TYPE_RGBA, // Request an RGBA format bits, // Select our color depth 0, 0, 0, 0, 0, 0, // Color bits ignored 0, // No Alpha buffer 0, // Shift bit ignored 0, // No accumulation buffer 0, 0, 0, 0, // Accumulation bits ignored DEPTHBUFFER, // 16bit z-buffer (depth buffer) 0, // No stencil buffer 0, // No auxiliary buffer PFD_MAIN_PLANE, // Main drawing layer 0, // Reserved 0, 0, 0 // Layer masks ignored }; if (!(hDC = GetDC(hWnd))) // Did we get a device context { KillGLWindow(); // Reset the display MessageBox(NULL, MSG_CREATEGLDCFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) // Did Windows Find A Matching Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_FINDPIXELFORMATFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!SetPixelFormat(hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_SETPIXELFORMATFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(hRC = wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_CREATEGLRCFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!wglMakeCurrent(hDC, hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_ACTIVEGLRCFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } ShowWindow(hWnd, SW_SHOW); // Show The Window SetForegroundWindow(hWnd); // Slightly Higher Priority SetFocus(hWnd); // Sets Keyboard Focus To The Window ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(); // Reset The Display MessageBox(NULL, MSG_INITFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success }
int WINAPI WinMain( HINSTANCE hinstance, HINSTANCE hprevinstance, LPSTR lpcmdline, int ncmdshow) { WNDCLASS winclass; // this will hold the class we create HWND hwnd; // generic window handle MSG msg; // generic message // first fill in the window class stucture winclass.style = CS_HREDRAW | CS_VREDRAW; winclass.lpfnWndProc = WindowProc; winclass.cbClsExtra = 0; winclass.cbWndExtra = 0; winclass.hInstance = hinstance; winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); winclass.hCursor = LoadCursor(NULL, IDC_ARROW); winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); winclass.lpszMenuName = NULL; winclass.lpszClassName = "WindowCreation"; // register the window class if (!RegisterClass(&winclass)) return(0); // create the window if (!(hwnd = CreateWindow( "WindowCreation", // class TITLE, // title WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, //Set the size of the window to the size of the screen width, height, NULL, // handle to parent NULL, // handle to menu hinstance, // instance NULL))) // creation parms return(0); /************************************************************************/ /* initialize vary member variable */ /************************************************************************/ InitializeGameClass(hwnd, width, height); /************************************************************************/ /* initialize end */ /************************************************************************/ // enter main event loop bool quit = false; while(!quit) { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { // test if this is a quit if (msg.message == WM_QUIT) quit = true; // translate any accelerator keys TranslateMessage(&msg); // send the message to the window proc DispatchMessage(&msg); } // end if else { /************************************************************************/ /* do some main logic control */ /************************************************************************/ myGame.RunGameLogic(); } } // end while return(msg.wParam); }
int main() { MSG msg; WNDCLASS wndclass; wndclass.cbClsExtra = 0; // 类附加内存 wndclass.cbWndExtra = 0; // 窗口附加内存 wndclass.hbrBackground = (HBRUSH) GetStockObject(COLOR_WINDOW); // 背景画刷句柄 wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); // 窗口光标句柄 wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // 窗口图标句柄 wndclass.hInstance = 0; // 包含窗口过程函数的程序实例 wndclass.lpfnWndProc = DefWindowProc; // 只想窗口过程函数的指针 wndclass.lpszClassName = "CRoot"; // 窗口类名称 wndclass.lpszMenuName = NULL; // 菜单资源 wndclass.style = CS_HREDRAW | CS_VREDRAW; // 窗口样式 RegisterClass(&wndclass); // 创建窗口, 定义一个变量用来保存成功创建窗口后返回的句柄 HWND hwnd; hwnd = CreateWindow("CRoot","Hello World",WS_CAPTION|WS_SYSMENU, 350, 120, 500, 500, NULL,NULL,0,NULL ); // 显示及刷新窗口 ShowWindow(hwnd, SW_SHOWNORMAL); UpdateWindow(hwnd); const int BUTTONNUMS = 2; //按钮 TBBUTTON tbb[2]; ZeroMemory(tbb, sizeof(tbb)); //CUT,COPY,PASTE /* #define STD_CUT 0 #define STD_COPY 1 #define STD_PASTE 2 #define STD_UNDO 3 #define STD_REDOW 4 #define STD_DELETE 5 #define STD_FILENEW 6 #define STD_FILEOPEN 7 #define STD_FILESAVE 8 #define STD_PRINTPRE 9 #define STD_PROPERTIES 10 #define STD_HELP 11 #define STD_FIND 12 #define STD_REPLACE 13 #define STD_PRINT 14 */ tbb[0].iBitmap = STD_FILENEW; tbb[0].fsState = TBSTATE_ENABLED; tbb[0].fsStyle = TBSTYLE_BUTTON; tbb[1].iBitmap = STD_REDOW; tbb[1].fsState = TBSTATE_ENABLED; tbb[1].fsStyle = TBSTYLE_BUTTON; //位图,commctl中的标准位图 TBADDBITMAP tbBitmap1; tbBitmap1.hInst = HINST_COMMCTRL; tbBitmap1.nID = IDB_STD_SMALL_COLOR; HWND hwnd2=CreateWindow(TOOLBARCLASSNAME,"按钮",WS_VISIBLE|WS_CHILD|WS_BORDER, 0,0,0,0,hwnd,(HMENU)0,0,0); //将位图添加到工具栏 SendMessage(hwnd2,TB_ADDBITMAP,0,(LPARAM)&tbBitmap1); //计算工具栏大小 SendMessage(hwnd2,TB_BUTTONSTRUCTSIZE,(WPARAM)sizeof(TBBUTTON),0); //添加按钮到工具栏 SendMessage(hwnd2,TB_ADDBUTTONS,(WPARAM)BUTTONNUMS,(LPARAM)&tbb); while(GetMessage(&msg,hwnd,0,0)) { if(msg.message == NULL)break; TranslateMessage(&msg); DispatchMessage(&msg); } }
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) { GLuint PixelFormat; // Содержит результаты подбора глубины цвета WNDCLASS wc; // Структура классов Windows DWORD dwExStyle; // Расширенный стиль окна DWORD dwStyle; // Стиль окна RECT WindowRect; // Получает значения верхнего левого и нижнего правого углов прямоугольника WindowRect.left = (long)0; // Устанавливает значение лево (Left) в 0 WindowRect.right = (long)width; // Устанавливает значение право (Right) в требуемую ширину (Width) WindowRect.top = (long)0; // Устанавливает значение верх (Top) в 0 WindowRect.bottom = (long)height; // Устанавливает значение низ (Bottom) в требуемую высоту (Height) fullscreen = fullscreenflag; // Устанавливаем глобальный флвг Fullscreen hInstance = GetModuleHandle(NULL); // Захватываем Instance для нашего окна wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Перерисовываем по размеру, и получаем DC для окна. wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // Нет дополнительных данных окна wc.cbWndExtra = 0; // Нет дополнительных данных окна wc.hInstance = hInstance; // Установим Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Згрузим иконку по умолчанию wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Згрузим стрелку курсора wc.hbrBackground = NULL; // Фон для GL не требуется wc.lpszMenuName = NULL; // Нам не нужны меню wc.lpszClassName = "OpenGL"; // Установим имя класса if (!RegisterClass(&wc)) { // Попытаемся зарегистрировать класс окна MessageBox(NULL, "Failed To Register The Window Class.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Возращаем FALSE } if (fullscreen) { // Попытаться включить полноеэкранный режим? DEVMODE dmScreenSettings; // Режим устройства memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Убедимся, что памать очищена dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Размер структуры devmode dmScreenSettings.dmPelsWidth = width; // Выбрана ширина экрана dmScreenSettings.dmPelsHeight = height; // Выбрана высота экрана dmScreenSettings.dmBitsPerPel = bits; // Выбрано количество бит на пиксель dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Попытаемся установить выбранный режим и получить резутьтаты. К седению: CDS_FULLSCREEN избавляется от кнопки стариGets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { // Если режиим не включился, предложим две возможности. Выйти или использовать оконный режим. if (MessageBox(NULL, "The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", "NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES) { fullscreen = FALSE; // Выбран оконный режим. Fullscreen = FALSE } else { // Показать сообщение, что приложение закончило работу. MessageBox(NULL, "Program Will Now Close.", "ERROR", MB_OK | MB_ICONSTOP); return FALSE; // Возвращаем FALSE } } } if (fullscreen) { // Так мы в полноэкранном режиме? dwExStyle = WS_EX_APPWINDOW; // Расширенный стиль окна dwStyle = WS_POPUP; // Стиль окна ShowCursor(FALSE); // Скрыть курсор мыши } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Расширенный стиль окна dwStyle = WS_OVERLAPPEDWINDOW; // Стиль окна } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Подстроить окно, чтобы оно соответствовало требуемому размеру // Создать окно if (!(hWnd = CreateWindowEx( dwExStyle, // Расширенный стиль для окна "OpenGL", // Наименование класса title, // Заголовок окна dwStyle | // Определенный стиль окна WS_CLIPSIBLINGS | // Требуемый стиль окна WS_CLIPCHILDREN, // Требуемый стиль окна 0, 0, // Местоположение окна WindowRect.right - WindowRect.left, // Вычисление ширины окна WindowRect.bottom - WindowRect.top, // Вычисление высоты окна NULL, // Нет родительского окна NULL, // Нет меню hInstance, // Instance NULL))) { // Не посылать сообщение по WM_CREATE KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Window Creation Error.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } static PIXELFORMATDESCRIPTOR pfd = { // pfd сообщает Windows какие параметры мы хотим sizeof(PIXELFORMATDESCRIPTOR), // Размер дескриптора формата пикселей 1, // Номер версии PFD_DRAW_TO_WINDOW | // Формат должен поддерживать окно PFD_SUPPORT_OPENGL | // Формат должен поддерживать OpenGL PFD_DOUBLEBUFFER, // Должна поддерживаться двойная буферизация PFD_TYPE_RGBA, // Запрос RGBA формата bits, // Выбор глубины цвета 0, 0, 0, 0, 0, 0, // Биты цвета игнорируются 0, // Нет альфа буферизации 0, // Бит сдвига игнорируется 0, // Нет буфера накопления 0, 0, 0, 0, // Биты накопления игнорируются 16, // 16битный Z-бувер (Буфер глубины) 0, // Нет буфера трафарета (stencil buffer) 0, // Нет вспомогательного буфера PFD_MAIN_PLANE, // Главная плоскость рисования 0, // Зарезервировано 0, 0, 0 // Слой масок игнорируется }; if (!(hDC = GetDC(hWnd))) { // Мы получили контекст устройства? KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) { // Windows нашла соответствующий формат пикселя? KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } if(!SetPixelFormat(hDC, PixelFormat, &pfd)) { // Мы можем установить формат пикселя? KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } if (!(hRC = wglCreateContext(hDC))) { // Мы можем получить контекст изображения? KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } if(!wglMakeCurrent(hDC, hRC)) { // Пытаемся активировать контекст изображения KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Activate The GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } ShowWindow(hWnd, SW_SHOW); // Показать окно SetForegroundWindow(hWnd); // Слегка увеличим приоритет SetFocus(hWnd); // Устанавливаем фокус клавииатуры на окно ReSizeGLScene(width, height); // Устанавливаем наше GL окно с перспективой if (!InitGL()) { // Инициализируем наше GL окно KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Initialization Failed.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Возращает FALSE } return TRUE; // Успешное завершение инициализациии }
void __declspec(dllexport) show(HWND hwndParent, int string_size, TCHAR *variables, stack_t **stacktop) { TCHAR fn[MAX_PATH]; TCHAR temp[64]; TCHAR *sleep=temp; EXDLL_INIT(); popstring(sleep); popstring(fn); sleep_val=0; while (*sleep >= _T('0') && *sleep <= _T('9')) { sleep_val*=10; sleep_val+=*sleep++-_T('0'); } if (fn[0] && sleep_val>0) { MSG msg; TCHAR classname[4]=_T("_sp"); static WNDCLASS wc; wc.lpfnWndProc = WndProc; wc.hInstance = g_hInstance; wc.hCursor = LoadCursor(NULL,IDC_ARROW); wc.lpszClassName = classname; if (RegisterClass(&wc)) { TCHAR fn2[MAX_PATH]; lstrcpy(fn2,fn); lstrcat(fn,_T(".bmp")); lstrcat(fn2,_T(".wav")); g_hbm=LoadImage(NULL,fn,IMAGE_BITMAP,0,0,LR_CREATEDIBSECTION|LR_LOADFROMFILE); if (g_hbm) { HWND myWnd; PlaySound(fn2,NULL,SND_ASYNC|SND_FILENAME|SND_NODEFAULT); myWnd = CreateWindowEx(WS_EX_TOOLWINDOW,classname,classname, 0,0,0,0,0,(HWND)hwndParent,NULL,g_hInstance,NULL); while (IsWindow(myWnd) && GetMessage(&msg,myWnd,0,0)) { DispatchMessage(&msg); } // Stop currently playing wave, we want to exit PlaySound(0,0,0); DeleteObject(g_hbm); UnregisterClass(classname, g_hInstance); } } } wsprintf(temp,_T("%d"),g_rv); pushstring(temp); }
bool d3d::InitD3D(HINSTANCE hInstance, int width, int height, bool windowed, D3DDEVTYPE deviceType, IDirect3DDevice9 **device) { WNDCLASS wc; wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)d3d::WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(0, IDI_APPLICATION); wc.hCursor = LoadCursor(0, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = 0; wc.lpszClassName = "Direct3D9App"; if(!RegisterClass(&wc)){ MessageBox(0, "RegisterClass() - FAILED", 0, 0); return false; } HWND hwnd = 0; hwnd = CreateWindow("Direct3D9App", "Direct3D9App", WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, 0, 0, width, height, 0, 0, hInstance, 0); if(!hwnd){ MessageBox(0, "CreateWindow() - FAILED", 0, 0); return false; } ShowWindow(hwnd, SW_SHOW); UpdateWindow(hwnd); HRESULT hr = 0; IDirect3D9 *d3d9 = 0; d3d9 = Direct3DCreate9(D3D_SDK_VERSION); if(!d3d9){ MessageBox(0, "Direct3DCreate9() - FAILED", 0, 0); return false; } D3DCAPS9 caps; d3d9->GetDeviceCaps(D3DADAPTER_DEFAULT, deviceType, &caps); int vp = 0; if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT) vp = D3DCREATE_HARDWARE_VERTEXPROCESSING; else vp = D3DCREATE_SOFTWARE_VERTEXPROCESSING; D3DPRESENT_PARAMETERS d3dpp; d3dpp.BackBufferWidth = width; d3dpp.BackBufferHeight = height; d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; d3dpp.BackBufferCount = 1; d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; d3dpp.MultiSampleQuality = 0; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = hwnd; d3dpp.Windowed = windowed; d3dpp.EnableAutoDepthStencil = true; d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8; d3dpp.Flags = 0; d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; hr = d3d9->CreateDevice(D3DADAPTER_DEFAULT, deviceType, hwnd, vp, &d3dpp, device); if(FAILED(hr)){ // try again using a 16-bit depth buffer d3dpp.AutoDepthStencilFormat = D3DFMT_D16; hr = d3d9->CreateDevice(D3DADAPTER_DEFAULT, deviceType, hwnd, vp, &d3dpp, device); if(FAILED(hr)){ d3d9->Release(); MessageBox(0, "CreateDevice() - FAILED", 0, 0); return false; } } d3d9->Release(); return true; }
void Win32Window::create(const String& name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams) { // destroy current window, if any if (mHWnd) destroy(); #ifdef OGRE_STATIC_LIB HINSTANCE hInst = GetModuleHandle( NULL ); #else # if OGRE_DEBUG_MODE == 1 HINSTANCE hInst = GetModuleHandle("RenderSystem_GL_d.dll"); # else HINSTANCE hInst = GetModuleHandle("RenderSystem_GL.dll"); # endif #endif mHWnd = 0; mName = name; mIsFullScreen = fullScreen; mClosed = false; // load window defaults mLeft = mTop = -1; // centered mWidth = width; mHeight = height; mDisplayFrequency = 0; mIsDepthBuffered = true; mColourDepth = mIsFullScreen? 32 : GetDeviceCaps(GetDC(0), BITSPIXEL); HWND parent = 0; String title = name; bool vsync = false; int fsaa = 0; String border; bool outerSize = false; if(miscParams) { // Get variable-length params NameValuePairList::const_iterator opt; NameValuePairList::const_iterator end = miscParams->end(); if ((opt = miscParams->find("title")) != end) title = opt->second; if ((opt = miscParams->find("left")) != end) mLeft = StringConverter::parseInt(opt->second); if ((opt = miscParams->find("top")) != end) mTop = StringConverter::parseInt(opt->second); if ((opt = miscParams->find("depthBuffer")) != end) mIsDepthBuffered = StringConverter::parseBool(opt->second); if ((opt = miscParams->find("vsync")) != end) vsync = StringConverter::parseBool(opt->second); if ((opt = miscParams->find("FSAA")) != end) fsaa = StringConverter::parseUnsignedInt(opt->second); if ((opt = miscParams->find("externalWindowHandle")) != end) { mHWnd = (HWND)StringConverter::parseUnsignedInt(opt->second); if (mHWnd) { mIsExternal = true; mIsFullScreen = false; } if ((opt = miscParams->find("externalGLControl")) != end) { mIsExternalGLControl = StringConverter::parseBool(opt->second); } } if ((opt = miscParams->find("externalGLContext")) != end) { mGlrc = (HGLRC)StringConverter::parseUnsignedLong(opt->second); if( mGlrc ) mIsExternalGLContext = true; } // window border style opt = miscParams->find("border"); if(opt != miscParams->end()) border = opt->second; // set outer dimensions? opt = miscParams->find("outerDimensions"); if(opt != miscParams->end()) outerSize = StringConverter::parseBool(opt->second); // only available with fullscreen if ((opt = miscParams->find("displayFrequency")) != end) mDisplayFrequency = StringConverter::parseUnsignedInt(opt->second); if ((opt = miscParams->find("colourDepth")) != end) mColourDepth = StringConverter::parseUnsignedInt(opt->second); // incompatible with fullscreen if ((opt = miscParams->find("parentWindowHandle")) != end) parent = (HWND)StringConverter::parseUnsignedInt(opt->second); } if (!mIsExternal) { DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN; DWORD dwStyleEx = 0; int outerw, outerh; if (mIsFullScreen) { dwStyle |= WS_POPUP; dwStyleEx |= WS_EX_TOPMOST; outerw = mWidth; outerh = mHeight; mLeft = mTop = 0; } else { if (parent) { dwStyle |= WS_CHILD; } else { if (border == "none") dwStyle |= WS_POPUP; else if (border == "fixed") dwStyle |= WS_OVERLAPPED | WS_BORDER | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; else dwStyle |= WS_OVERLAPPEDWINDOW; } int screenw = GetSystemMetrics(SM_CXSCREEN); int screenh = GetSystemMetrics(SM_CYSCREEN); if (!outerSize) { // calculate overall dimensions for requested client area RECT rc = { 0, 0, mWidth, mHeight }; AdjustWindowRect(&rc, dwStyle, false); // clamp window dimensions to screen size outerw = (rc.right-rc.left < screenw)? rc.right-rc.left : screenw; outerh = (rc.bottom-rc.top < screenh)? rc.bottom-rc.top : screenh; } // center window if given negative coordinates if (mLeft < 0) mLeft = (screenw - outerw) / 2; if (mTop < 0) mTop = (screenh - outerh) / 2; // keep window contained in visible screen area if (mLeft > screenw - outerw) mLeft = screenw - outerw; if (mTop > screenh - outerh) mTop = screenh - outerh; } // register class and create window WNDCLASS wc = { CS_OWNDC, WindowEventUtilities::_WndProc, 0, 0, hInst, LoadIcon(NULL, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW), (HBRUSH)GetStockObject(BLACK_BRUSH), NULL, "OgreGLWindow" }; RegisterClass(&wc); // Pass pointer to self as WM_CREATE parameter mHWnd = CreateWindowEx(dwStyleEx, "OgreGLWindow", title.c_str(), dwStyle, mLeft, mTop, outerw, outerh, parent, 0, hInst, this); WindowEventUtilities::_addRenderWindow(this); StringUtil::StrStreamType str; str << "Created Win32Window '" << mName << "' : " << mWidth << "x" << mHeight << ", " << mColourDepth << "bpp"; LogManager::getSingleton().logMessage(LML_NORMAL, str.str()); if (mIsFullScreen) { DEVMODE dm; dm.dmSize = sizeof(DEVMODE); dm.dmBitsPerPel = mColourDepth; dm.dmPelsWidth = mWidth; dm.dmPelsHeight = mHeight; dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (mDisplayFrequency) { dm.dmDisplayFrequency = mDisplayFrequency; dm.dmFields |= DM_DISPLAYFREQUENCY; if (ChangeDisplaySettings(&dm, CDS_FULLSCREEN | CDS_TEST) != DISP_CHANGE_SUCCESSFUL) { LogManager::getSingleton().logMessage(LML_NORMAL, "ChangeDisplaySettings with user display frequency failed"); dm.dmFields ^= DM_DISPLAYFREQUENCY; } } if (ChangeDisplaySettings(&dm, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) LogManager::getSingleton().logMessage(LML_CRITICAL, "ChangeDisplaySettings failed"); } } HDC old_hdc = wglGetCurrentDC(); HGLRC old_context = wglGetCurrentContext(); RECT rc; // top and left represent outer window position GetWindowRect(mHWnd, &rc); mTop = rc.top; mLeft = rc.left; // width and height represent drawable area only GetClientRect(mHWnd, &rc); mWidth = rc.right; mHeight = rc.bottom; mHDC = GetDC(mHWnd); if (!mIsExternalGLControl) { if (!mGLSupport.selectPixelFormat(mHDC, mColourDepth, fsaa)) { if (fsaa == 0) OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "selectPixelFormat failed", "Win32Window::create"); LogManager::getSingleton().logMessage(LML_NORMAL, "FSAA level not supported, falling back"); if (!mGLSupport.selectPixelFormat(mHDC, mColourDepth, 0)) OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "selectPixelFormat failed", "Win32Window::create"); } } if (!mIsExternalGLContext) { mGlrc = wglCreateContext(mHDC); if (!mGlrc) OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreateContext", "Win32Window::create"); } if (!wglMakeCurrent(mHDC, mGlrc)) OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglMakeCurrent", "Win32Window::create"); // Do not change vsync if the external window has the OpenGL control if (!mIsExternalGLControl) { // Don't use wglew as if this is the first window, we won't have initialised yet PFNWGLSWAPINTERVALEXTPROC _wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if (_wglSwapIntervalEXT) _wglSwapIntervalEXT(vsync? 1 : 0); } if (old_context && old_context != mGlrc) { // Restore old context if (!wglMakeCurrent(old_hdc, old_context)) OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglMakeCurrent() failed", "Win32Window::create"); // Share lists with old context if (!wglShareLists(old_context, mGlrc)) OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglShareLists() failed", " Win32Window::create"); } // Create RenderSystem context mContext = new Win32Context(mHDC, mGlrc); mActive = true; }
BOOL CFileTransDlg::Create(PFileVar pfv, PComVar pcv, PTTSet pts) { BOOL Ok; WNDCLASS wc; int fuLoad = LR_DEFAULTCOLOR; HWND hwnd; fv = pfv; cv = pcv; cv->FilePause &= ~fv->OpId; ts = pts; LOGFONT logfont; HFONT font; wc.style = CS_PARENTDC; wc.lpfnWndProc = AfxWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = DLGWINDOWEXTRA; wc.hInstance = AfxGetInstanceHandle(); wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL,IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE+1); wc.lpszMenuName = NULL; wc.lpszClassName = "FTDlg32"; RegisterClass(&wc); Pause = FALSE; hwnd = GetForegroundWindow()->GetSafeHwnd(); if (fv->OpId == OpLog) { // parent window is desktop Ok = CDialog::Create(CFileTransDlg::IDD, GetDesktopWindow()); } else { // parent window is VT window Ok = CDialog::Create(CFileTransDlg::IDD, NULL); } if (!fv->HideDialog) { // Visible = False のダイアログを表示する ShowWindow(SW_SHOWNORMAL); if (fv->OpId == OpLog) { ShowWindow(SW_MINIMIZE); } } else { // 直前にフォアグラウンドだったウィンドウにフォーカスを戻す。 // メニューからログをスタートした時に VTWin にフォーカスが戻らないので必要っぽい。 ::SetForegroundWindow(hwnd); } fv->HWin = GetSafeHwnd(); font = (HFONT)SendMessage(WM_GETFONT, 0, 0); GetObject(font, sizeof(LOGFONT), &logfont); if (get_lang_font("DLG_SYSTEM_FONT", fv->HWin, &logfont, &DlgFont, ts->UILanguageFile)) { SendDlgItemMessage(IDC_TRANS_FILENAME, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDC_TRANSFNAME, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDC_FULLPATH_LABEL, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDC_EDIT_FULLPATH, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDC_TRANS_TRANS, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDC_TRANSBYTES, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDC_TRANS_ELAPSED, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDC_TRANS_ETIME, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDC_TRANSPAUSESTART, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDCANCEL, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); SendDlgItemMessage(IDC_TRANSHELP, WM_SETFONT, (WPARAM)DlgFont, MAKELPARAM(TRUE,0)); } return Ok; }
BOOL CSocketThreadManager::SpawnThreads(LPCSTR lpClassName) { try { //Add to this class our thread ID, and a random number if (!lpClassName) { //Calculate our string int iStringLength; iStringLength=strlen(CSocketThreadManager_Class); //Add some size to it iStringLength+=50; //Allocate the string std::auto_ptr<char> pString(new char[iStringLength]); //Get our thread ID DWORD dwThreadID; dwThreadID=GetCurrentThreadId(); //Get the tick of the system DWORD dwProcessID; dwProcessID=GetTickCount(); //Create the string sprintf(pString.get(),"%s_%lu_%lu",CSocketThreadManager_Class, GetCurrentThreadId(), GetTickCount()); //And register the window //Check if we need to register the class if (!m_bRegisteredWindow) if (!RegisterClass(pString.get())) { //Report it ReportError("SpawnThreads","Failed to register window!"); //And quit return FALSE; } //Save the class name m_sClassName=pString.get(); } else m_sClassName=lpClassName; //Start creating threads //Allocate the thread structure m_pThreadData=new ThreadData[m_ulThreadCount]; //Initialize the data for (int iCount=0;iCount<m_ulThreadCount;++iCount) { m_pThreadData[iCount].bFreeze=FALSE; m_pThreadData[iCount].pEvent=NULL; m_pThreadData[iCount].hInstance=NULL; m_pThreadData[iCount].hWindowHandle=NULL; m_pThreadData[iCount].iSocketCount=0; m_pThreadData[iCount].iTimeoutCount=0; m_pThreadData[iCount].pThread=NULL; m_pThreadData[iCount].pCSection=COSManager::CreateCriticalSection(); m_pThreadData[iCount].pClass=this; } //Did we have an error? BOOL bError; bError=FALSE; //Our waiting list CWaitList aList; //Start spawning for (int iCounter=0; iCounter<m_ulThreadCount; ++iCounter) { //Copy the class name m_pThreadData[iCounter].sClassName=m_sClassName; //Create an event m_pThreadData[iCounter].pEvent=COSManager::CreateEvent(); //Add it to the list aList.AddObject(m_pThreadData[iCounter].pEvent, TRUE); //Set our instance m_pThreadData[iCounter].hInstance=m_hInstance; //Create extended data CreateExtendedData(m_pThreadData[iCounter].aExtension); //And create it m_pThreadData[iCounter].pThread=COSManager::CreateThread(SocketThread); //Check the thread has been created if (!m_pThreadData[iCounter].pThread->GetThreadID()) { //Report the error ReportError("SpawnThreads","Failed to create thread!"); //We have an error bError=TRUE; //Exit the loop break; } else //Start the thread m_pThreadData[iCounter].pThread->Start((LPVOID)&m_pThreadData[iCounter]); } //Tmp position DWORD dwTmp; if (aList.Wait(TRUE, dwTmp, THREADS_TIMEOUT)) { //Report the error ReportError("SpawnThreads","Timeout waiting for threads!"); //Close the threads CleanThreads(TRUE); //Exit return FALSE; } else if (bError) { //Close the threads CleanThreads(FALSE); //Exit return FALSE; } else { //We are OK m_bInitialized=TRUE; //Done return TRUE; } } ERROR_HANDLER_RETURN("SpawnThreads",FALSE) }
ALERROR CUWindow::Boot (void) // Boot // // Must be called after the window object is created { ALERROR error; DWORD dwStyle; int xPos, yPos, cxWidth, cyHeight; ASSERT(m_hWnd == NULL); // Register the class, if we haven't already if (!g_bRegistered) { WNDCLASS wc; // Register the class utlMemSet(&wc, sizeof(wc), 0); wc.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)CUWindowWndProc; wc.hInstance = m_pApp->GetInstance(); wc.hIcon = LoadIcon(m_pApp->GetInstance(), m_pApp->GetIconRes()); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszClassName = g_szClassName; if (!RegisterClass(&wc)) return ERR_FAIL; } // Figure out some initial parameters if (IsFullScreen()) { dwStyle = WS_POPUP | WS_CLIPSIBLINGS; xPos = 0; yPos = 0; cxWidth = GetSystemMetrics(SM_CXSCREEN); cyHeight = GetSystemMetrics(SM_CYSCREEN); } else { dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS; xPos = CW_USEDEFAULT; yPos = 0; cxWidth = CW_USEDEFAULT; cyHeight = 0; } // Create the actual window m_hWnd = CreateWindow( g_szClassName, "", dwStyle, xPos, yPos, cxWidth, cyHeight, NULL, (HMENU)NULL, m_pApp->GetInstance(), this); if (m_hWnd == NULL) return ERR_MEMORY; // The main frame covers the entire if (error = CreateFrame(NULL, 0, 0, NULL, NULL)) return error; return NOERROR; }
GLUSboolean GLUSAPIENTRY glusCreateWindow(const char* title, GLUSuint width, GLUSuint height, GLUSboolean fullscreen) { GLUSint attribList[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, 0, 0 }; static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; GLUSuint PixelFormat; // Holds The Results After Searching For A Match WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowRect.left = (long) 0; // Set Left Value To 0 WindowRect.right = (long) width; // Set Right Value To Requested Width WindowRect.top = (long) 0; // Set Top Value To 0 WindowRect.bottom = (long) height; // Set Bottom Value To Requested Height g_fullscreen = fullscreen; // Set The Global Fullscreen Flag g_hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window. wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = g_hInstance; // Set The Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer wc.hbrBackground = NULL; // No Background Required For GL wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName = "GLUS"; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { return GLUS_FALSE; // Return FALSE } if (fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = 32; // Selected Bits Per Pixel dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { glusDestroyWindow(); return GLUS_FALSE; } } if (fullscreen) { dwExStyle = WS_EX_APPWINDOW; // Window Extended Style dwStyle = WS_POPUP; // Windows Style ShowCursor(FALSE); // Hide Mouse Pointer } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle = WS_OVERLAPPEDWINDOW; // Windows Style } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (!(g_hWnd = CreateWindowEx(dwExStyle, // Extended Style For The Window "GLUS", // Class Name title, // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style 0, 0, // Window Position WindowRect.right - WindowRect.left, // Calculate Window Width WindowRect.bottom - WindowRect.top, // Calculate Window Height NULL, // No Parent Window NULL, // No Menu g_hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { glusDestroyWindow(); return GLUS_FALSE; } if (!(g_hDC = GetDC(g_hWnd))) // Did We Get A Device Context? { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!(PixelFormat = ChoosePixelFormat(g_hDC, &pfd))) // Did Windows Find A Matching Pixel Format? { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!SetPixelFormat(g_hDC, PixelFormat, &pfd)) // Are We Able To Set The Pixel Format? { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!(g_hRC = wglCreateContext(g_hDC))) // Are We Able To Get A Rendering Context? { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!wglMakeCurrent(g_hDC, g_hRC)) // Try To Activate The Rendering Context { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (g_major >= 3) { PFNWGLCREATECONTEXTATTRIBSARBPROCTEMP wglCreateContextAttribsARBTemp = NULL; HGLRC hRCTemp = NULL; GLUSint attribList[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 1, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, 0, 0 }; attribList[1] = g_major; attribList[3] = g_minor; attribList[5] = g_flags; if (!(wglCreateContextAttribsARBTemp = (PFNWGLCREATECONTEXTATTRIBSARBPROCTEMP) wglGetProcAddress("wglCreateContextAttribsARB"))) { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!(hRCTemp = wglCreateContextAttribsARBTemp(g_hDC, 0, attribList))) { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!wglMakeCurrent(NULL, NULL)) { wglDeleteContext(hRCTemp); glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } if (!wglDeleteContext(g_hRC)) { wglDeleteContext(hRCTemp); glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } g_hRC = hRCTemp; if (!wglMakeCurrent(g_hDC, g_hRC)) { glusDestroyWindow(); return GLUS_FALSE; // Return FALSE } } ShowWindow(g_hWnd, SW_SHOW); // Show The Window SetForegroundWindow(g_hWnd); // Slightly Higher Priority SetFocus(g_hWnd); // Sets Keyboard Focus To The Window g_width = width; g_height = height; return GLUS_TRUE; // Success }
bool CWinSystemWin32::CreateNewWindow(const CStdString& name, bool fullScreen, RESOLUTION_INFO& res, PHANDLE_EVENT_FUNC userFunction) { m_hInstance = ( HINSTANCE )GetModuleHandle( NULL ); m_nWidth = res.iWidth; m_nHeight = res.iHeight; m_bFullScreen = fullScreen; m_nScreen = res.iScreen; m_hIcon = LoadIcon(m_hInstance, MAKEINTRESOURCE(IDI_MAIN_ICON)); // Register the windows class WNDCLASS wndClass; wndClass.style = CS_OWNDC; // For OpenGL wndClass.lpfnWndProc = CWinEvents::WndProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = m_hInstance; wndClass.hIcon = m_hIcon; wndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); wndClass.hbrBackground = ( HBRUSH )GetStockObject( BLACK_BRUSH ); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = name.c_str(); if( !RegisterClass( &wndClass ) ) { return false; } HWND hWnd = CreateWindow( name.c_str(), name.c_str(), fullScreen ? WS_POPUP : WS_OVERLAPPEDWINDOW, 0, 0, m_nWidth, m_nHeight, 0, NULL, m_hInstance, userFunction ); if( hWnd == NULL ) { return false; } const DWORD dwHwndTabletProperty = TABLET_DISABLE_PENBARRELFEEDBACK | // disables UI feedback on pen button down (circle) TABLET_DISABLE_FLICKS; // disables pen flicks (back, forward, drag down, drag up) SetProp(hWnd, MICROSOFT_TABLETPENSERVICE_PROPERTY, reinterpret_cast<HANDLE>(dwHwndTabletProperty)); // setup our touch pointers HMODULE hUser32 = GetModuleHandleA( "user32" ); if (hUser32) { PtrGetGestureInfo = (pGetGestureInfo) GetProcAddress( hUser32, "GetGestureInfo" ); PtrSetGestureConfig = (pSetGestureConfig) GetProcAddress( hUser32, "SetGestureConfig" ); PtrCloseGestureInfoHandle = (pCloseGestureInfoHandle) GetProcAddress( hUser32, "CloseGestureInfoHandle" ); } m_hWnd = hWnd; m_hDC = GetDC(m_hWnd); m_bWindowCreated = true; CreateBlankWindows(); ResizeInternal(true); // Show the window ShowWindow( m_hWnd, SW_SHOWDEFAULT ); UpdateWindow( m_hWnd ); return true; }
static void _create_glwindow( const char* title, int cw, int ch ) { WNDCLASS wndclass = {0}; DWORD wndstyle = 0; RECT rect = {0}; HWND hwnd = 0; HDC hdc = 0; HGLRC hglrc = 0; if ( !GetClassInfo( GetModuleHandle( 0 ), APP_WINDOW_CLASSNAME, &wndclass ) ) { wndclass.style = CS_OWNDC | CS_DBLCLKS; wndclass.lpfnWndProc = _window_proc; wndclass.hInstance = GetModuleHandle( 0 ); wndclass.hIcon = LoadIcon( 0, IDI_APPLICATION ); wndclass.hbrBackground = (HBRUSH)NULL; wndclass.lpszClassName = APP_WINDOW_CLASSNAME; if ( !RegisterClass( &wndclass ) ) { assert(!"RegisterClass() failed"); } } SetRect( &rect, 0, 0, cw, ch ); AdjustWindowRect( &rect, WS_OVERLAPPEDWINDOW, 0 ); if ( !( hwnd = CreateWindow( APP_WINDOW_CLASSNAME, title, WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, 0, 0, wndclass.hInstance, 0 ) ) ) { assert( !"CreateWindow() failed" ); } if ( !( hdc = GetDC( hwnd ) ) ) { assert( !"GetDC() failed" ); } window.hwnd = hwnd; window.hdc = hdc; window.fullscreen = 0; window.x = rect.left; window.y = rect.top; window.w = cw; window.h = ch; window.hcursor = LoadCursor( 0, IDC_ARROW ); //app_window_setcursor( window, APP_MOUSECURSOR_ARROW ); { int pixelformat = 0; PIXELFORMATDESCRIPTOR pfd = {0}; pfd.nSize = sizeof( PIXELFORMATDESCRIPTOR ); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cRedBits = 8; pfd.cGreenBits = 8; pfd.cBlueBits = 8; pfd.cAlphaBits = 8; pfd.cDepthBits = 0; pfd.iLayerType = PFD_MAIN_PLANE; if ( !( pixelformat = ChoosePixelFormat( window.hdc, &pfd ) ) ) { assert( !"ChoosePixelFormat() failed" ); } if ( !SetPixelFormat( window.hdc, pixelformat, &pfd ) ) { assert( !"SetPixelFormat() failed" ); } } if ( !( hglrc = wglCreateContext( window.hdc ) ) ) { assert( !"wglCreateContext() failed" ); } wglMakeCurrent(window.hdc, hglrc ); window.hglrc = hglrc; EGL_loadextensions(); ShowWindow( window.hwnd, SW_RESTORE ); SendMessage( window.hwnd, APP_WINDOW_CREATE, 0, 0 ); }
bool Win32Dialog::CreateWnd( const wchar_t* title, int width, int height, int Icon, HWND Parent ) { if( m_hWnd ) return false; MWLOG(LEV_DEBUG, MOD_DLG, L" --> Win32Dialog::CreateWnd (Parent=%X)",Parent); DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values RECT DeskRect; WindowRect.left = (long)0; // Set Left Value To 0 WindowRect.right = (long)width; // Set Right Value To Requested Width WindowRect.top = (long)0; // Set Top Value To 0 WindowRect.bottom = (long)height; // Set Bottom Value To Requested Height GetClientRect( GetDesktopWindow(), &DeskRect ); WNDCLASS wc; // Windows Class Structure HICON hIco; if( Icon == 0 ) hIco = LoadIcon( NULL, IDI_WINLOGO ); else hIco = LoadIcon( m_hInstance, MAKEINTRESOURCE(Icon) ); wc.style = CS_HREDRAW | CS_VREDRAW; // | CS_OWNDC; // Redraw On Size, And Own DC For Window. wc.lpfnWndProc = (WNDPROC)WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; //DLGWINDOWEXTRA; // No Extra Window Data wc.hInstance = m_hInstance; // Set The Instance wc.hIcon = hIco; // Load The Default Icon wc.hCursor = LoadCursor( NULL, IDC_ARROW ); // Load The Arrow Pointer wc.hbrBackground = (HBRUSH)GetSysColorBrush( COLOR_3DFACE ); // What Color we want in our background wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName = m_appName; // Set The Class Name if( !RegisterClass( &wc ) ) // Attempt To Register The Window Class { unsigned long err = GetLastError(); MWLOG(LEV_WARN, MOD_DLG, L" --> Win32Dialog::CreateWnd - Failed To Register The Window Class - Error=%ld",err); return false; // Return FALSE } dwStyle = WS_CAPTION | WS_VISIBLE | WS_SYSMENU | WS_OVERLAPPED; dwExStyle = WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_WINDOWEDGE | WS_EX_TOPMOST; if( m_ModalHold ) { dwStyle |= WS_POPUP; dwExStyle |= WS_EX_DLGMODALFRAME; } AdjustWindowRectEx( &WindowRect, dwStyle, FALSE, dwExStyle ); // Adjust Window To True Requested Size Active_lpWnd = this; // Create The Window if( !( m_hWnd = Active_hWnd = CreateWindowEx( dwExStyle, // Extended Style For The Window m_appName, // Class Name title, // Window Title dwStyle, // Defined Window Style DeskRect.right/2 - (WindowRect.right-WindowRect.left)/2, DeskRect.bottom/2 - (WindowRect.bottom-WindowRect.top)/2, //CW_USEDEFAULT, CW_USEDEFAULT, // Window Position WindowRect.right-WindowRect.left, // Calculate Window Width WindowRect.bottom-WindowRect.top, // Calculate Window Height Parent, // No Parent Window NULL, // No Menu m_hInstance, // Instance (LPVOID)Active_lpWnd))) // Dont Pass Anything To WM_CREATE { unsigned long err = GetLastError(); KillWindow( ); // Reset The Display MWLOG(LEV_WARN, MOD_DLG, L" --> Win32Dialog::CreateWnd - Window Creation Error - Error=%ld",err); return false; // Return FALSE } MWLOG(LEV_DEBUG, MOD_DLG, L" --> Win32Dialog::CreateWnd - CreateWindowEx (m_hWnd=%X)",m_hWnd); WndMap.insert( TD_WNDPAIR( m_hWnd, this ) ); return true; }
pj_status_t GuiInit() { WNDCLASS wc; HWND hWnd = NULL; RECT r; DWORD dwStyle; enum { LABEL_HEIGHT = 30 }; enum { MENU_ID_EXIT = 50000 }; BITMAP bmp; HMENU hRootMenu; SHMENUBARINFO mbi; pj_status_t status = PJ_SUCCESS; /* Check if app is running. If it's running then focus on the window */ hWnd = FindWindow(MAINWINDOWCLASS, MAINWINDOWTITLE); if (NULL != hWnd) { SetForegroundWindow(hWnd); return status; } wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = (WNDPROC)DialogProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = g_hInst; wc.hIcon = 0; wc.hCursor = 0; wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = 0; wc.lpszClassName = MAINWINDOWCLASS; if (!RegisterClass(&wc) != 0) { DWORD err = GetLastError(); return PJ_RETURN_OS_ERROR(err); } /* Create the app. window */ g_hWndMain = CreateWindow(MAINWINDOWCLASS, MAINWINDOWTITLE, WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, (HWND)NULL, NULL, g_hInst, (LPSTR)NULL); if (g_hWndMain == NULL) { DWORD err = GetLastError(); return PJ_RETURN_OS_ERROR(err); } /* Create exit menu */ hRootMenu = CreateMenu(); AppendMenu(hRootMenu, MF_STRING, MENU_ID_EXIT, L"Exit"); /* Initialize menubar */ ZeroMemory(&mbi, sizeof(SHMENUBARINFO)); mbi.cbSize = sizeof(SHMENUBARINFO); mbi.hwndParent = g_hWndMain; mbi.dwFlags = SHCMBF_HIDESIPBUTTON|SHCMBF_HMENU; mbi.nToolBarId = (UINT)hRootMenu; mbi.hInstRes = g_hInst; if (FALSE == SHCreateMenuBar(&mbi)) { DWORD err = GetLastError(); return PJ_RETURN_OS_ERROR(err); } /* Store menu window handle */ g_hWndMenuBar = mbi.hwndMB; /* Show the menu */ DrawMenuBar(g_hWndMain); ShowWindow(g_hWndMenuBar, SW_SHOW); /* Override back button */ SendMessage(g_hWndMenuBar, SHCMBM_OVERRIDEKEY, VK_TBACK, MAKELPARAM(SHMBOF_NODEFAULT | SHMBOF_NOTIFY, SHMBOF_NODEFAULT | SHMBOF_NOTIFY)); /* Get main window size */ GetClientRect(g_hWndMain, &r); #if defined(WIN32_PLATFORM_PSPC) && WIN32_PLATFORM_PSPC != 0 /* Adjust the height for PocketPC platform */ r.bottom -= GetSystemMetrics(SM_CYMENU); #endif /* Create logo */ g_hBmp = SHLoadDIBitmap(LOGO_PATH); /* for jpeg, uses SHLoadImageFile() */ if (g_hBmp == NULL) { DWORD err = GetLastError(); return PJ_RETURN_OS_ERROR(err); } GetObject(g_hBmp, sizeof(bmp), &bmp); dwStyle = SS_CENTERIMAGE | SS_REALSIZEIMAGE | SS_BITMAP | WS_CHILD | WS_VISIBLE; g_hWndImg = CreateWindow(TEXT("STATIC"), NULL, dwStyle, (r.right-r.left-bmp.bmWidth)/2, (r.bottom-r.top-bmp.bmHeight)/2, bmp.bmWidth, bmp.bmHeight, g_hWndMain, (HMENU)0, g_hInst, NULL); if (g_hWndImg == NULL) { DWORD err = GetLastError(); return PJ_RETURN_OS_ERROR(err); } SendMessage(g_hWndImg, STM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)g_hBmp); /* Create label */ dwStyle = WS_CHILD | WS_VISIBLE | ES_CENTER; g_hWndLbl = CreateWindow(TEXT("STATIC"), NULL, dwStyle, 0, r.bottom-LABEL_HEIGHT, r.right-r.left, LABEL_HEIGHT, g_hWndMain, (HMENU)0, g_hInst, NULL); if (g_hWndLbl == NULL) { DWORD err = GetLastError(); return PJ_RETURN_OS_ERROR(err); } SetWindowText(g_hWndLbl, _T("Please wait..")); return status; }
int main(int argc, char **argv) { HWND navitWindow; COPYDATASTRUCT cd; char opt; TCHAR *g_szClassName = TEXT("TellNavitWND"); WNDCLASS wc; HWND hwnd; HWND hWndParent=NULL; if(argc>0) { while((opt = getopt(argc, argv, ":hvc:d:e:s:")) != -1) { switch(opt){ case 'h': print_usage(); exit(0); break; case 'e': errormode=atoi(optarg); break; default: err("Unknown option %c\n", opt); exit(1); break; } } } else { print_usage(); exit(1); } if(optind==argc) { err("Navit command to execute is needed."); exit(1); } memset(&wc, 0 , sizeof(WNDCLASS)); wc.lpfnWndProc = message_handler; wc.hInstance = GetModuleHandle(NULL); wc.lpszClassName = g_szClassName; if (!RegisterClass(&wc)) { err(TEXT("Window class registration failed\n")); return 1; } else { hwnd = CreateWindow( g_szClassName, TEXT("Tell Navit"), 0, 0, 0, 0, 0, hWndParent, NULL, GetModuleHandle(NULL), NULL); if(!hwnd) { err(TEXT("Can't create hidden window\n")); UnregisterClass(g_szClassName,NULL); return 1; } } navitWindow=FindWindow( TEXT("NAVGRA"), NULL ); if(!navitWindow) { err(TEXT("Navit window not found\n")); DestroyWindow(hwnd); UnregisterClass(g_szClassName,NULL); return 1; } else { int rv; char *command=g_strjoinv(" ",argv+optind); struct navit_binding_w32_msg *msg; int sz=sizeof(*msg)+strlen(command); cd.dwData=NAVIT_BINDING_W32_DWDATA; msg=g_malloc0(sz); msg->version=NAVIT_BINDING_W32_VERSION; g_strlcpy(msg->magic,NAVIT_BINDING_W32_MAGIC,sizeof(msg->magic)); g_strlcpy(msg->text,command,sz-sizeof(*msg)+1); cd.cbData=sz; cd.lpData=msg; rv=SendMessage( navitWindow, WM_COPYDATA, (WPARAM)hwnd, (LPARAM) (LPVOID) &cd ); g_free(command); g_free(msg); if(rv!=0) { err(TEXT("Error %d sending message, SendMessage return value is %d\n"), GetLastError(), rv); DestroyWindow(hwnd); UnregisterClass(g_szClassName,NULL); return 1; } } DestroyWindow(hwnd); UnregisterClass(g_szClassName,NULL); return 0; }
/* ** Sys_CreateConsole */ void Sys_CreateConsole( void ) { HDC hDC; WNDCLASS wc; RECT rect; const char *DEDCLASS = "JAMP WinConsole"; int nHeight; int swidth, sheight; int DEDSTYLE = WS_POPUPWINDOW | WS_CAPTION | WS_MINIMIZEBOX; memset( &wc, 0, sizeof( wc ) ); wc.style = 0; wc.lpfnWndProc = (WNDPROC) ConWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = g_wv.hInstance; wc.hIcon = LoadIcon( g_wv.hInstance, MAKEINTRESOURCE(IDI_ICON1)); wc.hCursor = LoadCursor (NULL,IDC_ARROW); wc.hbrBackground = (HBRUSH__ *)COLOR_INACTIVEBORDER; wc.lpszMenuName = 0; wc.lpszClassName = DEDCLASS; if ( !RegisterClass (&wc) ) { return; } rect.left = 0; rect.right = 600; rect.top = 0; rect.bottom = 450; AdjustWindowRect( &rect, DEDSTYLE, FALSE ); hDC = GetDC( GetDesktopWindow() ); swidth = GetDeviceCaps( hDC, HORZRES ); sheight = GetDeviceCaps( hDC, VERTRES ); ReleaseDC( GetDesktopWindow(), hDC ); s_wcd.windowWidth = rect.right - rect.left + 1; s_wcd.windowHeight = rect.bottom - rect.top + 1; s_wcd.hWnd = CreateWindowEx( 0, DEDCLASS, CLIENT_CONSOLE_TITLE, DEDSTYLE, ( swidth - 600 ) / 2, ( sheight - 450 ) / 2 , rect.right - rect.left + 1, rect.bottom - rect.top + 1, NULL, NULL, g_wv.hInstance, NULL ); if ( s_wcd.hWnd == NULL ) { return; } // // create fonts // hDC = GetDC( s_wcd.hWnd ); nHeight = -MulDiv( 8, GetDeviceCaps( hDC, LOGPIXELSY), 72); s_wcd.hfBufferFont = CreateFont( nHeight, 0, 0, 0, FW_LIGHT, 0, 0, 0, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, FF_MODERN | FIXED_PITCH, "Courier New" ); ReleaseDC( s_wcd.hWnd, hDC ); // // create the input line // s_wcd.hwndInputLine = CreateWindow( "edit", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOHSCROLL | WS_TABSTOP, 6, 400, s_wcd.windowWidth-20, 20, s_wcd.hWnd, ( HMENU ) INPUT_ID, // child window ID g_wv.hInstance, NULL ); // // create the buttons // s_wcd.hwndButtonCopy = CreateWindow( "button", NULL, BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | WS_TABSTOP, 5, 425, 72, 24, s_wcd.hWnd, ( HMENU ) COPY_ID, // child window ID g_wv.hInstance, NULL ); SendMessage( s_wcd.hwndButtonCopy, WM_SETTEXT, 0, ( LPARAM ) "Copy" ); s_wcd.hwndButtonClear = CreateWindow( "button", NULL, BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | WS_TABSTOP, 82, 425, 72, 24, s_wcd.hWnd, ( HMENU ) CLEAR_ID, // child window ID g_wv.hInstance, NULL ); SendMessage( s_wcd.hwndButtonClear, WM_SETTEXT, 0, ( LPARAM ) "Clear" ); s_wcd.hwndButtonQuit = CreateWindow( "button", NULL, BS_PUSHBUTTON | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | WS_TABSTOP, s_wcd.windowWidth-92, 425, 72, 24, s_wcd.hWnd, ( HMENU ) QUIT_ID, // child window ID g_wv.hInstance, NULL ); SendMessage( s_wcd.hwndButtonQuit, WM_SETTEXT, 0, ( LPARAM ) "Quit" ); // // create the scrollbuffer // s_wcd.hwndBuffer = CreateWindow( "edit", NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_BORDER | ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY | WS_TABSTOP, 6, 40, s_wcd.windowWidth-20, 354, s_wcd.hWnd, ( HMENU ) EDIT_ID, // child window ID g_wv.hInstance, NULL ); SendMessage( s_wcd.hwndBuffer, WM_SETFONT, ( WPARAM ) s_wcd.hfBufferFont, 0 ); s_wcd.SysInputLineWndProc = ( WNDPROC ) SetWindowLong( s_wcd.hwndInputLine, GWL_WNDPROC, ( long ) InputLineWndProc ); SendMessage( s_wcd.hwndInputLine, WM_SETFONT, ( WPARAM ) s_wcd.hfBufferFont, 0 ); SendMessage( s_wcd.hwndBuffer, EM_LIMITTEXT, ( WPARAM ) 0x7fff, 0 ); ShowWindow( s_wcd.hWnd, SW_SHOWDEFAULT); UpdateWindow( s_wcd.hWnd ); SetForegroundWindow( s_wcd.hWnd ); SetFocus( s_wcd.hwndInputLine ); s_wcd.visLevel = 1; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { static TCHAR szAppName[] = TEXT("Checker1"); HWND hwnd; MSG msg; WNDCLASS wndclass; wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = WndProc; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = hInstance; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = szAppName; if (!RegisterClass(&wndclass)) { MessageBox(NULL, TEXT("Program requires Windows NT!"), szAppName, MB_ICONERROR); return 0; } hwnd = CreateWindow(szAppName, TEXT("Checker1 Mouse Hit-Test Demo"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, iCmdShow); UpdateWindow(hwnd); while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; }
LONG WINAPI ImageView_CreateWindow(HWND hwnd, LPWSTR szFileName) { struct GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; WNDCLASS WndClass = {0}; TCHAR szBuf[512]; HWND hMainWnd; MSG msg; if (!ImageView_LoadSettings()) { shiSettings.Maximized = FALSE; shiSettings.Left = 0; shiSettings.Top = 0; shiSettings.Right = 520; shiSettings.Bottom = 400; } // Initialize GDI+ gdiplusStartupInput.GdiplusVersion = 1; gdiplusStartupInput.DebugEventCallback = NULL; gdiplusStartupInput.SuppressBackgroundThread = FALSE; gdiplusStartupInput.SuppressExternalCodecs = FALSE; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL); pLoadImage(szFileName); // Create the window WndClass.lpszClassName = _T("shimgvw_window"); WndClass.lpfnWndProc = (WNDPROC)ImageView_WndProc; WndClass.hInstance = hInstance; WndClass.style = CS_HREDRAW | CS_VREDRAW; WndClass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPICON)); WndClass.hCursor = LoadCursor(hInstance, IDC_ARROW); WndClass.hbrBackground = (HBRUSH)COLOR_WINDOW; if (!RegisterClass(&WndClass)) return -1; LoadString(hInstance, IDS_APPTITLE, szBuf, sizeof(szBuf) / sizeof(TCHAR)); hMainWnd = CreateWindow(_T("shimgvw_window"), szBuf, WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_CAPTION, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, NULL, NULL, hInstance, NULL); // Show it ShowWindow(hMainWnd, SW_SHOW); UpdateWindow(hMainWnd); // Message Loop while(GetMessage(&msg,NULL,0,0)) { TranslateMessage(&msg); DispatchMessageW(&msg); } if (image) GdipDisposeImage(image); GdiplusShutdown(gdiplusToken); return -1; }
DWORD WINAPI ThreadProc(LPVOID lpParameter) { const wchar_t CLASS_NAME[] = L"BERT Console Window"; static bool first = true; HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED); WNDCLASS wc = {}; wc.lpfnWndProc = WindowProc; wc.hInstance = ghModule; wc.lpszClassName = CLASS_NAME; if (first && !RegisterClass(&wc)) { DWORD dwErr = GetLastError(); DebugOut("ERR %x\n", dwErr); } // Create the window. hWndExcel = (HWND)lpParameter; // we may close and re-open the window. reopenWindow = true; while (reopenWindow) { reopenWindow = false; HWND hwndParent = 0; DWORD dw; if (CRegistryUtils::GetRegDWORD(HKEY_CURRENT_USER, &dw, REGISTRY_KEY, REGISTRY_VALUE_CONSOLE_ON_TOP) && dw) hwndParent = hWndExcel; HWND hwnd = CreateWindowEx( 0, // Optional window styles. CLASS_NAME, // Window class CONSOLE_WINDOW_TITLE, // Window text WS_OVERLAPPEDWINDOW, // Window style // Size and position CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, hwndParent, // Parent window NULL, // Menu ghModule, // Instance handle NULL // Additional application data ); if (hwnd == NULL) { DWORD dwErr = GetLastError(); DebugOut("ERR %x\n", dwErr); return 0; } if (first) CenterWindow(hwnd, (HWND)lpParameter); first = false; ShowWindow(hwnd, SW_SHOW); // Run the message loop. MSG msg = {}; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } hWndConsole = 0; ::SetFocus(hWndExcel); } CoUninitialize(); return 0; }