MDI Form with an Image

By: Kevin Scardina

Abstract: This FAQ discribs how to make the background of the main window in a MDI application

Question-

How can I make the main window of a MDI Application show a bitmap as the background? With regular applications all i have to do is throw a TImage down on the TForm and align it to the window. Set the TImage up with a image and I have a background, but if I change the FormStyle to fsMDIForm it no long is that easy.

Answer-

This is because the Parent of the TImage is the Form whose client area is visible. In an MDI application, the Frame Form (the form you work with at design-time) has its client area covered by the Client Form which serves as the parent of the MDI Child Forms. To actually have an image appear, you need to do your drawing to this client window. Here's an example...

//in header...

TFarProc ClientInstance;

TFarProc OldClientWindowProc;

void __fastcall MDIClientWndProc(TMessage &Message);

//in source...

__fastcall TForm1::TForm1(TComponent* Owner)

: TForm(Owner)

{

ClientInstance = MakeObjectInstance(MDIClientWndProc);

OldClientWindowProc = (void *)(GetWindowLong(ClientHandle, GWL_WNDPROC));

SetWindowLong(ClientHandle, GWL_WNDPROC, (LONG)(ClientInstance));

}

void __fastcall TForm1::MDIClientWndProc(TMessage &Message)

{

if (Message.Msg == WM_ERASEBKGND)

{

Message.Result = 0;

HDC DC = (HDC)Message.WParam;

StretchBlt(DC, 0, 0, Width, Height,

Image1->Canvas->Handle, 0, 0,

Image1->Picture->Bitmap->Width,

Image1->Picture->Bitmap->Height,

SRCCOPY);

}

else Message.Result = CallWindowProc((FARPROC)OldClientWindowProc,

ClientHandle, Message.Msg,

Message.WParam, Message.LParam);

}

void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)

{

SetWindowLong(ClientHandle, GWL_WNDPROC,

(LONG)OldClientWindowProc);

FreeObjectInstance(ClientInstance);

}

If you're running in 256-color mode, then you may need to handle the palette support messages as well...

if (Message.Msg == WM_QUERYNEWPALETTE)

{

HDC Hdc = GetDC(ClientHandle);

SelectPalette(Hdc, HPalette, false);

RealizePalette(Hdc);

InvalidateRect(ClientHandle, NULL, true);

ReleaseDC(ClientHandle, Hdc);

Message.Result = 0;

return;

}

if (Message.Msg == WM_PALETTECHANGED)

{

if ((HWND)Message.WParam != ClientHandle)

{

HDC Hdc = GetDC(ClientHandle);

SelectPalette(Hdc, HPalette, false);

RealizePalette(Hdc);

UpdateColors(Hdc);

ReleaseDC(ClientHandle, Hdc);

}

Message.Result = 0;

return;

}

Good Luck!


Server Response from: ETNASC03