这两天正在学消息这个东东,昨天想做一个自定义的消息,网上的两位大虾很热心帮了忙,按照大虾的代码我试了一下是可以的,也没多想就结了帖,可是今天早上想把代码略作改动,就发现问题了,先把代码展示出来,各位表面看看:
unit Unit1;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics,Controls,     Forms,Dialogs, StdCtrls;const
  WM_MYMSG=WM_USER+2;type
  TForm1 = class(TForm)
    Button1: TButton;
    Edit1: TEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;var
  Form1: TForm1;implementationuses Unit2;{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);
var
  num:double;
begin
  num:=strtofloat(edit1.Text);
  form2:=tform2.Create(application.Owner);
  try
     form2.ShowModal;
     if num<50 then
        SendMessage(Form2.Handle,WM_MYMSG,1,0)
     else
        SendMessage(Form2.Handle,WM_MYMSG,2,0);
  finally
     form2.Free;
     form2:=nil;
  end;
end;end.
{---------------以下是form2中的代码------------------}
unit Unit2;interfaceuses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs,unit1, StdCtrls;type
  TForm2 = class(TForm)
    Edit1: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    procedure WmMyMsg(var Msg:TMessage);message WM_MYMSG;
    { Private declarations }
  public
    Flag:integer;
    { Public declarations }
  end;var
  Form2: TForm2;implementation{$R *.dfm}procedure TForm2.WmMyMsg(var Msg: TMessage);
begin
   flag:=Msg.WParam;
   inherited;
end;procedure TForm2.Button1Click(Sender: TObject);
begin
edit1.Text:=inttostr(flag);
end;end.现在碰到的问题是:在form1里输入一个小于50的值,本来希望是在form2的button1被按后edit1.text是1,可是显示的却是0,第二次再以相同的方法show出form2并按下button1后,edit1.text的值才会显示正确的1;如果在form1输入一个大于50的值,也会出现相同的问题,要到第二次才会显示正确的值2,这是为什么呢?

解决方案 »

  1.   

    把form2.ShowModal;
    改成form2.show;
    就可以了。
      

  2.   

    确实可以.但是,能否给我详细讲解一下,为什么把form2.ShowModal;改成form2.show;就可以了呢?
      

  3.   

    还是showmodal的原因,你说第一次没有收到数据,而第二次却收到数据,
    那是因为你没有在工程选项里把自动创建里的form2移除,如果你移出了的话
    你永远都得不到数据。
      

  4.   

    showmodal以后form1停止工作,也就是说你的消息根本就没有发出去。
    你调换一下位置就可以了
         form2.ShowModal;
         if num<50 then
            SendMessage(Form2.Handle,WM_MYMSG,1,0)
         else
            SendMessage(Form2.Handle,WM_MYMSG,2,0);把showmodal放到后面     
         if num<50 then
            SendMessage(Form2.Handle,WM_MYMSG,1,0)
         else
            SendMessage(Form2.Handle,WM_MYMSG,2,0);     form2.ShowModal;