1

How do I go about sending a Windows Message to a form in my application that is not the MainForm? Using the code below gives me an Access Violation.

procedure TMainForm.SendMessageToAnotherForm;
begin
  SendMessage(MyForm.Handle,WM_MY_MESSAGE,0,0);
end;

MyForm has already been created and is the top most window.

Edit: I have tried PostMessage also but I receive the same Access Violation and I am positive that WM_MY_MESSAGE is valid because I use it to communicate with MainForm somewhere else.

2
  • You can send messages using SendMessage or PostMessage to any form or Windows control. The code above is correct provided the WM_MY_MESSAGE value is correct and the message is processed correctly in MyForm. Commented May 19, 2010 at 13:37
  • 2
    "gives me an Access Violation" is meaningless without knowing WHAT access violation and at what addresses. It's like saying "my car made a funny noise", which is meaningless without more info. Commented May 19, 2010 at 16:52

2 Answers 2

8

The most probable reason to obtain an access violation with the above code is MyForm = nil or a wild pointer. Set a breakpoint on the line of code with SendMessage call and check it. If MyForm is a valid reference, then an access violation is caused by message processing in MyForm.

Sign up to request clarification or add additional context in comments.

Comments

2

Are you aware that SendMessage waits until the message is handled? That means that the message queue of the target window must be able to process messages.

If you call this method inside an event handler (like ButtonClick) you should better use PostMessage instead.

2 Comments

if the target window is in the same thread context as the code that is sending the message (which is the case in a VCL environment when a UI event handler sends a message to another UI window), then the message queue is not used, and the target window's message procedure is called directly. There are many calls to SendMessage() in the VCL's internals that would break if SendMessage() could not be used in an event handler.
This behavior is in the SendMessage() documentation: "If the specified window was created by the calling thread, the window procedure is called immediately as a subroutine. If the specified window was created by a different thread, the system switches to that thread and calls the appropriate window procedure. Messages sent between threads are processed only when the receiving thread executes message retrieval code."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.