在用enumwindows枚举窗口时,遇到以下问题。如果不使用strlcopy程序可以运行,用了就不行了。请问怎么解决。 (10分)

  • 主题发起人 主题发起人 koy0755
  • 开始时间 开始时间
K

koy0755

Unregistered / Unconfirmed
GUEST, unregistred user!
得到所以窗口的标题。以下代码能正常运行个字符。第二个程序加入了strlcopy想得到标题的前8个字符,就运行不了了。<br>unit Unit1;<br><br>interface<br><br>uses<br>&nbsp; Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,<br>&nbsp; Dialogs, StdCtrls;<br><br>type<br>&nbsp; TForm1 = class(TForm)<br>&nbsp; &nbsp; ListBox1: TListBox;<br>&nbsp; &nbsp; Button1: TButton;<br>&nbsp; &nbsp; procedure Button1Click(Sender: TObject);<br>&nbsp; private<br>&nbsp; &nbsp; { Private declarations }<br>&nbsp; public<br>&nbsp; &nbsp; { Public declarations }<br>&nbsp; end;<br><br>var<br>&nbsp; Form1: TForm1;<br><br>implementation<br><br>{$R *.dfm}<br>function enumwindowsproc(ahwnd:hwnd;alparam:lparam):boolean;stdcall;<br>var wintext,w2:pchar;<br>begin<br>&nbsp; &nbsp; result:=true;<br>&nbsp; &nbsp; getwindowtext(ahwnd,wintext,100);<br>&nbsp; &nbsp; w2:=wintext;<br>&nbsp; &nbsp; form1.ListBox1.Items.add(inttostr(ahwnd)+'='+w2);<br><br>&nbsp; &nbsp; end;<br><br>procedure TForm1.Button1Click(Sender: TObject);<br>var<br>whwnd:hwnd;<br>smes:pchar;<br>begin<br>enumwindows(@enumwindowsproc,0);<br><br>end;<br><br>end.<br>
 
以下程序是得到所有窗体标题的前8个字符,在上面的程序的基础上只改了一句话。程序就运行不了了。<br>unit Unit1;<br><br>interface<br><br>uses<br>&nbsp;Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,<br>&nbsp;Dialogs, StdCtrls;<br><br>type<br>&nbsp;TForm1 = class(TForm)<br>&nbsp; &nbsp;ListBox1: TListBox;<br>&nbsp; &nbsp;Button1: TButton;<br>&nbsp; &nbsp;procedure Button1Click(Sender: TObject);<br>&nbsp;private<br>&nbsp; &nbsp;{ Private declarations }<br>&nbsp;public<br>&nbsp; &nbsp;{ Public declarations }<br>&nbsp;end;<br><br>var<br>&nbsp;Form1: TForm1;<br><br>implementation<br><br>{$R *.dfm}<br>function enumwindowsproc(ahwnd:hwnd;alparam:lparam):boolean;stdcall;<br>var wintext,w2:pchar;<br>begin<br>&nbsp; &nbsp;result:=true;<br>&nbsp; &nbsp;getwindowtext(ahwnd,wintext,100);<br>&nbsp; &nbsp;strlcopy(w2,wintext,8); //这里原来是w2:=wintext改用strcopy(w2,wintext)就用不<br>//试过用getmem(w2,10)先分配内存,也不行。请问这个问题如何解决?<br>&nbsp; &nbsp;form1.ListBox1.Items.add(inttostr(ahwnd)+'='+w2);<br><br>&nbsp; &nbsp;end;<br><br>procedure TForm1.Button1Click(Sender: TObject);<br>var<br>whwnd:hwnd;<br>smes:pchar;<br>begin<br>enumwindows(@enumwindowsproc,0);<br><br>end;<br><br>end.
 
var wintext,w2:pchar;<br>begin<br>&nbsp; &nbsp; result:=true;<br>//危险,因为你根本没有给wintext分配内存<br>[red] &nbsp; &nbsp;Size:=getwindowtext(ahwnd,wintext,0);<br>&nbsp; &nbsp; GetMem(wintext,Size);<br>&nbsp; &nbsp; getwindowtext(ahwnd,wintext,Size);<br>[/red] <br>&nbsp; &nbsp; form1.ListBox1.Items.add(inttostr(ahwnd)+'='+wintext);<br>&nbsp; &nbsp; FreeMem(wintext); &nbsp;//用完了要释放<br>&nbsp; &nbsp; end;
 
后退
顶部