Ben
Ben

Reputation: 556

ShowWindow vs SWP_SHOWWINDOW vs WS_VISIBLE

What is the difference between the following methods of showing a window:

Are there any other methods?

Upvotes: 8

Views: 7850

Answers (2)

Marcellus
Marcellus

Reputation: 1287

The SetWindowLong function sets the initial window style, i.e. if the window will appear immediately or not after creation. MSDN says that after window creation, you have to use the other two functions to set the visible property. A typical use would be:

case WM_CREATE:
{
    long style = GetWindowLong(hWnd, GWL_STYLE);
    SetWindowLong(hWnd, GWL_STYLE, style | WS_DLGFRAME);

    return 0;
}

ShowWindow and SetWindowPos have an overlapping functionality regarding the window visibility. If you have to move the window in x, y or z direction at the same time as setting its visibility, use SetWindowPos. I personally find that the need to specify the necessary uFlags parameter makes this function a bit cumbersome to use, but MSDN is your friend ;-)

If on the other hand you don't need the window to move at all but are about to maximize, minimize, restore etc. it, use ShowWindow. Since it only takes the window handle and the nCmdShow constant as parameters, it's an easy-to-use function.

Upvotes: 3

rodrigo
rodrigo

Reputation: 98338

I think that they are mostly the same, but with additional capabilities for each one:

  1. SetWindowLong with WS_VISIBLE added to GWL_STYLE is proably the least interesting: why mess with style bits if there is a function that does exactly what you need.
  2. SetWindowPos with SWP_SHOWWINDOW allows you to show the window and set its location and size at the same time, with a single atomic operation, so that no-one - program or user - may see the visible-unmoved or moved-invisible window.
  3. The ShowWindow function has a lot of magic involved, particularly the very first time it is called in a program. Additionaly, it has the SW_SHOWDEFAULT flag that is little used but not available to any other method, AFAIK.

There are other ways to make a window visible. From the top of my mind:

  1. Create it with the WS_VISIBLE flag set.
  2. DeferWindowPos has the same flags than SetWindowPos.

Upvotes: 10

Related Questions