请教一个简单的问题:动态产生的按钮控件,parent不是窗口,只是窗口里面的表格,怎么响应事件?btns[i]:=TButton.Create(nil);
btns[i].Parent:=tb;
btns[i].OnClick:=MyButtonClick;
procedure TForm1.MyButtonClick(Sender: TObject);
begin
  ShowMessage('abc');
end;

解决方案 »

  1.   

    btns[i].OnClick:=MyButtonClick;就是了,与parent没什么关系
    parent只是决定显示在什么位置
      

  2.   

    btns[i]:=TButton.Create(self);一般子控件要有Owner,这里是窗体
      

  3.   

    不行,如果 改为 btns[i].Parent:=self;,就没问题,可以正常响应。
      

  4.   

    tb是我的表格[TStringGrid]的名称。
      

  5.   

    TStringGrid不是容器类,所以不能是别的控件的Parent,就把Parent:=self,这也不影响你的按钮使用。
    如果要把Button和Grid的行对应起来,可以在生成Button的时候,把行号记录在Button的Tag里。更简单的办法是用第三方的StringGrid,比如Raize的,TMS的StringGrid都支持Cell里自动显示Button
      

  6.   

    TStringGrid继承关系:
    TCustomGrid在响应WM_Command时未调用inherited(原因未知),所以不能处理其子控件按钮的点击事件。解决办法是让TStringGrid自行处理WM_COMMAND。
    type
      TStringGrid=class(Grids.TStringGrid)
        procedure WMCommand(var Message: TWMCommand); message WM_COMMAND;
      end;  TForm1 = class(TForm)
        sg: TStringGrid;//是我们重新定义过的TStringGrid...procedure TStringGrid.WMCommand(var Message: TWMCommand);
    begin
      inherited;//保留TCustomGrid的处理代码
      with Message, TMessage(Message) do//将消息传给子控件
        Message.Result := SendMessage(Ctl, Msg + CN_BASE, WParam, LParam);
    end;
      

  7.   

    如果让Parent:=self;会有一个大问题,就是显示,比如我界面上有tpagecontrol时,切换到别的tabsheet也会显示按钮,每次切换去隐藏很不方便的。试试你提供的这种方法,看行不行。