-1

我在这些图像中创建和加载图片的过程,但是如何创建 OnClick 过程并确定我点击的是哪个?

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, jpeg, ExtCtrls, Math, StdCtrls;

type
  TForm1 = class(TForm)
Label1: TLabel;
procedure FormCreate(Sender: TObject);
private
procedure ImageClick(Sender: TObject);
{ Private declarations }
public
{ Public declarations }
end;

var
 Form1: TForm1;
 Box: array [1..8,1..8] of TImage;
 size: integer;

implementation


{$R *.dfm}

procedure imagecreation;
var i,j: integer;
begin
  size:=60;
  for i:=1 to 8 do
    begin
      for j:=1 to 8 do
        begin
      box[i,j]:=Timage.Create(Form1);
      box[i,j].AutoSize:=false;
      box[i,j].Proportional:=true;
      box[i,j].Width:=size;
      box[i,j].Height:=size;
      box[i,j].Top:=(i+1)*size;
      box[i,j].Left:=(j+1)*size;
      box[i,j].Parent:=Form1;
      box[i,j].OnClick:=ImageClick;
        end;
    end;
end;


procedure TForm1.FormCreate(Sender: TObject);
begin
  imagecreation;
end;

procedure TForm1.ImageClick(Sender: TObject);
var
  ClickedImage: TImage;
begin
  ClickedImage := Sender as TImage;
end;
end.

此时它调用“ImageClick”和未声明的标识符。这些是如何声明的?

4

2 回答 2

2

如果您有一个表单或其他类,您可以在其中定义一个方法并将其附加到所有图像:

// The event handler
procedure TForm1.ImageClick(Sender: TObject);
var
  Image: TImage;
begin
  // Senders points to the image clicked
  Image := Sender as TImage;
  // Use Image as you like. 
end;

// Creating the images.
procedure TForm1.CreateImage;
var
  Image: TImage;
begin
  Image := TImage.Create(Self);
  // Set parent, load picture, etc.
  Image.OnClick := ImageClick; // Attach the event.
end;
于 2012-12-22T17:39:55.257 回答
1

创建一个通用的 OnClick 处理程序(例如,在您的表单上):

procedure TForm1.ImageClick(Sender: TObject);
var
  ClickedImage: TImage;
begin
  ClickedImage := Sender as TImage;
  // Do whatever with the image clicked
end;

(提示:在代码编辑器中键入上述代码后,点击Ctrl++ ,IDE 会自动为您将声明添加到表单界面。)ShiftC

当您创建图像并将其分配给数组时,将其OnClick事件设置为上述事件:

for i:=1 to 8 do 
begin 
  for j:=1 to 8 do 
  begin      
    Images[i, j] := TImage.Create(nil);
    Images[i, j].OnClick := ImageClick;
    Images[i, j].LoadFromFile(AnImageFilename);
    // Other settings for image
  end;
end;

编辑:现在你已经发布了你的代码,问题是你没有为imagecreation你的表单创建一个方法,因此它不知道在哪里可以找到ImageClick. 您可以通过更改代码来修复它

procedure imagecreation;

procedure TForm1.imagecreation;

并使用我之前给您的快捷方式将其添加到表单的接口声明中。

于 2012-12-22T17:40:17.563 回答