Title: How can I close a form from within FormCreate or FormShow?
Question: I have a number of security checks that take place during either the OnCreate or OnShow events of some forms. If a user doesn''t meet all of the security criteria to use a form, I want to close it before the user sees it. However, I get an error message if I try to close the form from within the FormCreate or FormShow methods.
Answer:
There is a Windows message called WM_CLOSE which causes a window to close. However, you have to use the procedure "PostMessage" to send it instead of the more commonly seen "SendMessage" because PostMessage just sends the message out to the message queue instead of sending it and waiting for a response, which is what SendMessage does. So, my code looks something like this:
{...check security stuff..}
If not lCanAccess then
begin
messagedlg('Access Denied', mtInformation, [mbOK], 0);
PostMessage(self.handle, WM_CLOSE, 0, 0);
Screen.Cursor := crDefault; //make sure cursor changes back
end
else
{...continue setting up module...}