Solved

Toggle fullscreen / windowed

Posted on 2001-06-04
5
2,942 Views
Last Modified: 2012-05-04
Hi!

Im working on a small program which only function is to toggle between fullscreen and windowed, no painting no nothing...
I've been looking all over for anything that could give me an hint on whats wrong with it but without success so here comes the complete code!

Hope anyone got some answer!

------------------------------------------------------
I can make a fullscreen window or a windowed one alone but i cant switch between them...
-------------------------------------------------------
//////////////////////////////////////////////////////////////////////////////////////////////////
// Initialize a window with the standard controls //
//////////////////////////////////////////////////////////////////////////////////////////////////

#include <windows.h>
#include <windowsx.h>
#include <stdio.h>

//////////////////////////////////////////////////////////////////////////////////////////////////

#define WIN32_LEAN_AND_MEAN
#define MENU      "Menu"
#define CLASS      "Class"
#define NAME      "Name"
#define KEY_DOWN(vk_code)      ((GetAsyncKeyState(vk_code) & 0x8000) ? 1 : 0)
#define KEY_UP(vk_code)            ((GetAsyncKeyState(vk_code) & 0x8000) ? 0 : 1)

//////////////////////////////////////////////////////////////////////////////////////////////////

bool      Initialize(HINSTANCE hinstance,int ncmdshow);
bool      WinFullscreen(HINSTANCE hinstance,int cmdshow);
bool      WinWindowed(HINSTANCE hinstance,int ncmdshow,DWORD dwWidth,DWORD dwHeight);
bool      LogEnable();
bool      Log(char* szLogText, ...);
bool      Error(HWND hwnd,char szText[]);
void      GameMain(void);

//////////////////////////////////////////////////////////////////////////////////////////////////
HINSTANCE                        hinstance;
HINSTANCE                        g_hinstance;
int                                    ncmdshow;
HWND                              hwnd                  = NULL;
HDC                                    hdc                        = NULL;
DWORD                              StartTime            = NULL;
bool                              bInitializing      = FALSE;
bool                              bFullScreen            = FALSE;

//////////////////////////////////////////////////////////////////////////////////////////////////
// WinMain
// INT
//////////////////////////////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE hinstance,HINSTANCE hprevinstance,LPSTR lpcmdline,int ncmdshow)
{
      lpcmdline            = lpcmdline;
      hprevinstance      = hprevinstance;
      MSG      msg;

      if(!LogEnable())
      {
            Error(hwnd,"Could not create logfile!");
      }

// Initialize window //
      Log("Initializing window");
      if(!Initialize(hinstance, ncmdshow))
      {
            DestroyWindow(hwnd);
            Log("Initializing->FAILED\n");
            return FALSE;
      }
      else
      {
            Log("Initializing->PASSED\n");
      }
      ShowWindow(hwnd, SW_SHOW);
      g_hinstance = hinstance;

// Enter the main event loop //
      while(1)
      {
            if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
            {
                  if(msg.message == WM_QUIT)
                        break;
// Translate any accelerator key //
                  TranslateMessage(&msg);
// Send the message to window proc //
                  DispatchMessage(&msg);
            }

// Start timer to lock OR measure the framerate //
            StartTime = GetTickCount();

// The main loop //
            GameMain();

// Lock to 30FPS - 33msec per frame //
            while((GetTickCount() - StartTime) < 33);
      }
// Return to sweet old windows //
      return(msg.wParam);
}


//////////////////////////////////////////////////////////////////////////////////////////////////
// WinProc
// Windows callback function
//////////////////////////////////////////////////////////////////////////////////////////////////
long FAR PASCAL WindowProc(HWND hwnd,UINT message,WPARAM wParam,LPARAM lParam)
{
      HDC                        hdc;
      PAINTSTRUCT            ps;

// Lets take a look at our keyboard //
      switch(message)
      {
      case WM_CREATE:
            return(0);
            break;

      case WM_PAINT:
            hdc = BeginPaint(hwnd,&ps);
            EndPaint(hwnd,&ps);
            break;

      case WM_KEYDOWN:
            switch(wParam)
            {
            case VK_ESCAPE:
                  PostMessage(hwnd,WM_CLOSE,0,0);
                  break;
            }
            break;

            case WM_SYSKEYUP:
                  switch(wParam)
                  {
// Handle ALT + ENTER, Toggle windowed and fullscreen mode //
                  case VK_RETURN:
                        // We are up to something, PAUSE everything else! //
                        bInitializing = TRUE;

                        bFullScreen = !bFullScreen;
                        Log("Change screen mode");
                        // If we have a window, destroy it! //
                        if(hwnd)
                        {
                              DestroyWindow(hwnd);
                        }
                        if(!Initialize(g_hinstance,ncmdshow))
                        {
                              DestroyWindow(hwnd);
                              Log("Init new window->FAILED\n");
                              return FALSE;                              
                        }
                        else
                        {
                              Log("Init new window->PASSED\n");
                              ShowWindow(hwnd, SW_SHOW);
                        }
                        // OK, we are done! //
                        bInitializing = FALSE;
                        break;
                  }
                  break;

      case WM_CLOSE:
            if(MessageBox(hwnd,"Are you sure you want to quit?","Notice",MB_YESNO | MB_ICONQUESTION) == IDNO)
                  return(0);

      case WM_DESTROY:
            if(!bInitializing)
            {
                  PostQuitMessage(0);
                  return(0);
            }
            break;

      default:break;
      }

// All other message //
      return(DefWindowProc(hwnd,message,wParam,lParam));
}


//////////////////////////////////////////////////////////////////////////////////////////////////
// Initialize()
// This function creates either a fullscreen or a window
// BOOL
//////////////////////////////////////////////////////////////////////////////////////////////////
bool Initialize(HINSTANCE hinstance, int ncmdshow)
{
      if(bFullScreen)
// Create a fullscreen window if thats what we want //
      {
            
            if(!WinFullscreen(hinstance,ncmdshow))
            {
                  Log("  Set to FULLSCREEN->FAILED");
                  return FALSE;
            }
            else
            {
                  Log("  Set to FULLSCREEN->PASSED");
            }
      }
      else
// Else create a window //
      {
            if(!WinWindowed(hinstance,ncmdshow,100,100))
            {
                  Log("  Set to WINDOWED->FAILED");
                  return FALSE;
            }
            else
            {
                  Log("  Set to WINDOWED->PASSED");
            }
      }
/*
// Start up initializing //
      if(!InitStart())
      {
            Log("InitStart->FAILED");
            return FALSE;
      }
      else
      {
            Log("InitStart->PASSED");
      }
*/
      return TRUE;
}

//////////////////////////////////////////////////////////////////////////////////////////////////
// Init Window FULLSCREEN
// BOOL
//////////////////////////////////////////////////////////////////////////////////////////////////
bool WinFullscreen(HINSTANCE hinstance, int ncmdshow)
{
      WNDCLASSEX            winclass;      // Holds the windows class info //

// Fill in the windows class info structure //
      winclass.cbSize                  = sizeof(WNDCLASSEX);
      winclass.style                  = CS_HREDRAW | CS_VREDRAW;
      winclass.lpfnWndProc      = WindowProc;
      winclass.cbClsExtra            = 0;
      winclass.cbWndExtra            = 0;
      winclass.hInstance            = hinstance;
      winclass.hIcon                  = LoadIcon(NULL, IDI_WINLOGO);
      winclass.hIconSm            = LoadIcon(NULL, IDI_WINLOGO);
      winclass.hCursor            = LoadCursor(NULL, IDC_ARROW);
      winclass.hbrBackground      = (HBRUSH)GetStockObject(GRAY_BRUSH);
      winclass.lpszMenuName      = MENU;
      winclass.lpszClassName      = CLASS;

// Register the windows class //
      if(!RegisterClassEx(&winclass))
      {
            Log("  Register windows class:FULLSCREEN->FAILED");
            return FALSE;
      }

// Create the fullscreen window //
      hwnd = CreateWindowEx(
                  WS_EX_TOPMOST,
                  CLASS,                                                // The class name //
                  NAME,                                                // The title //
                  WS_POPUP,
                  0,0,                                                // x, y //
                  GetSystemMetrics(SM_CXSCREEN),            // For Fullscreen: GetSystemMetrics(SM_CXSCREEN)
                  GetSystemMetrics(SM_CYSCREEN),            // For Fullscreen: GetSystemMetrics(SM_CYSCREEN)
                  NULL,                                                // Parent //
                  NULL,                                                // Menu //
                  hinstance,
                  NULL);

      if(!hwnd)
      {
            Log("  Create window:FULLSCREEN->FAILED");
            return FALSE;
      }

      return TRUE;
}


//////////////////////////////////////////////////////////////////////////////////////////////////
// Init Window WINDOWED
// BOOL
//////////////////////////////////////////////////////////////////////////////////////////////////
bool WinWindowed(HINSTANCE hinstance,int ncmdshow,DWORD dwWidth,DWORD dwHeight)
{
      WNDCLASSEX            winclass;      // Holds the windows class info //
      RECT                  rcWindow;      // Rectangle //

// Fill in the windows class info structure //
      winclass.cbSize                  = sizeof(WNDCLASSEX);
      winclass.style                  = CS_HREDRAW | CS_VREDRAW;
      winclass.lpfnWndProc      = WindowProc;
      winclass.cbClsExtra            = 0;
      winclass.cbWndExtra            = 0;
      winclass.hInstance            = hinstance;
      winclass.hIcon                  = LoadIcon(NULL, IDI_WINLOGO);
      winclass.hIconSm            = LoadIcon(NULL, IDI_WINLOGO);
      winclass.hCursor            = LoadCursor(NULL, IDC_ARROW);
      winclass.hbrBackground      = (HBRUSH)GetStockObject(GRAY_BRUSH);
      winclass.lpszMenuName      = MENU;
      winclass.lpszClassName      = CLASS;

// Register the windows class //
      if(!RegisterClassEx(&winclass))
      {
            Log("  Register windows class:WINDOWED->FAILED");
            return FALSE;
      }

// Create a window //
      hwnd = CreateWindowEx(
                  WS_EX_TOPMOST,//NULL,
                  CLASS,                                                            // The class name //
                  NAME,                                                            // The title //
                  WS_VISIBLE | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX | WS_MAXIMIZEBOX,
                  CW_USEDEFAULT,
                  SW_SHOW,
                  0,
                  0,
                  NULL,                                                            // Parent //
                  NULL,                                                            // Menu //
                  hinstance,
                  NULL);

      if(!hwnd)
      {
            Log("  Create window:WINDOWED->FAILED");
            return FALSE;
      }

// Set desired size for the client area of the window //
      SetRect(&rcWindow,0,0,dwWidth,dwHeight);

// Adjust the size so the borders etc. will fit //
      AdjustWindowRectEx(&rcWindow,
                                 GetWindowStyle(hwnd),      // Style of our main window //
                                 GetMenu(hwnd) != NULL,      // Does our window have a menu? //
                                 GetWindowExStyle(hwnd));      // Extended style of our window //

// Adjust the window to the new size //
      MoveWindow(hwnd,CW_USEDEFAULT,CW_USEDEFAULT,
                              rcWindow.right  - rcWindow.left,
                              rcWindow.bottom - rcWindow.top,
                              TRUE);
      
      return TRUE;
}


//////////////////////////////////////////////////////////////////////////////////////////////////
// GameMain
//////////////////////////////////////////////////////////////////////////////////////////////////
void GameMain(void)
{
}

------------------------------------------------------
LogFunction!
------------------------------------------------------
//////////////////////////////////////////////////////////////////////////////////////////////////
// This function is used to create a log file during setup or wherever needed!
//////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////
#include <stdarg.h>
#include <stdio.h>
#include <windows.h>
#include <windowsx.h>

//////////////////////////////////////////////////////////////////////////////////////////////////

bool      bLogEnabled;

//////////////////////////////////////////////////////////////////////////////////////////////////

bool Log(char* szLogText, ...)
{
// Take a look if logging is enabled //
      if(bLogEnabled)
      {
            FILE*      pFile;
            va_list pArg;

// Variable arguments lists "start" macro //
            va_start(pArg,szLogText);

// Open file and append to it //
            if((pFile = fopen("log.txt", "a"))  == NULL)
                  return FALSE;

// Write the text and add a newline //
            vfprintf(pFile, szLogText, pArg);
            putc('\n', pFile);

// Close the file //
            fclose(pFile);
      }
      return TRUE;
}

//////////////////////////////////////////////////////////////////////////////////////////////////
// Enables Log
//////////////////////////////////////////////////////////////////////////////////////////////////
bool LogEnable()
{

// EnableLog //
      bLogEnabled = TRUE;
      FILE*      pFile;

      if((pFile = fopen("log.txt", "wb")) == NULL)
            return FALSE;

// Close the file //
      fclose(pFile);
      return TRUE;
}
------------------------------------------------------
Utils
------------------------------------------------------
//////////////////////////////////////////////////////////////////////////////////////////////////
// This file contains small utils like error handling etc.
//////////////////////////////////////////////////////////////////////////////////////////////////
#include <windows.h>
#include <windowsx.h>

//////////////////////////////////////////////////////////////////////////////////////////////////
// Most imported: ERROR function
//////////////////////////////////////////////////////////////////////////////////////////////////
bool Error(HWND hwnd, char szText[])
{
      MessageBox(hwnd, szText, "System error!", MB_OK | MB_DEFBUTTON1 | MB_ICONEXCLAMATION);
      DestroyWindow(hwnd);
      return FALSE;
}


------------------------------------------------------
Sorry i had to post it all, but i couldnt find any help elsewhere!

-Robert-
0
Comment
Question by:Warichew
  • 3
5 Comments
 
LVL 22

Accepted Solution

by:
nietod earned 75 total points
ID: 6152070
There are no "full screen features" built into windows.  If you want a window to be the size of the full screen you just move and size it so it fills the whole screen.   You can get the dimensions of the screen in a variety of ways, but I think for your case you don't realy want the size of the screen.  What I suspect you reall you want is the size and location of the "work area" which is the portionof the screen that is not obscured byt he task bar.   To get that you use SystemParametersInfo() with an index of SPI_GETWORKAREA.   Then move the window to the desired size and location.  There are several ways to move a window, but the easiest is probably MoveWindow().
0
 
LVL 22

Expert Comment

by:nietod
ID: 6152083
Like

RECT WrkRec;
SystemParemetersInfo(SPI_GETWORKAREA,0,&WrkRec,0);
MoveWindow(WndHnd,WrkRec.Left,WrkRec.Top,WrkRec.Right - WrkRec.Left,WrhRec.Bottom-WrkRec.Top,TRUE);
0
 

Author Comment

by:Warichew
ID: 6155367
Hmm, couldnt get it to work, its the same problem...

RegisterClassEx(&winclass)->FAILED

Strange...

Compile it and test, check the log file afterwards.
0
 
LVL 22

Expert Comment

by:nietod
ID: 6155617
>> RegisterClassEx(&winclass)->FAILED
Whjat does that have to do with the problem?  My answer has nothing to do with registerign a class and it woudl have to be performed AFTER you register the class. so it would have no effect on this

Did you debug the code to see why RegisterClass failed?   You coudl try calling GetLastError.  the most likely causes are that you are using invalid handles, like for menus, icons etc, that you ae specifying names for resources that don't exist, or that you are registering a class name that is already used.
0
 
LVL 1

Expert Comment

by:Moondancer
ID: 6811460
I am sorry to see that Asker has not returned to update and finalize this question.  I am, therefore, force accepting this question.  In the event the Asker returns with additional needs related to this question, please respond and continue the collaboration process.
Thank you,
Moondancer
Community Support Moderator @ Experts Exchange
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
C++ assignment question 7 167
Which IDE to use to begin C++ training? 5 59
I could not build boost code, 10 78
Least Squares Curve Fitting 4 60
When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

912 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now