用SendMessage()对Memo如lines.add

mygodsos 2008-10-12 08:58:25

var
i:integer;
begin
for i:=0 to 300 do
SendMessage(Form1.Memo1.Handle,WM_SETTEXT,0,integer(pchar(inttostr(i))));
end;

结果就只在第一行的光标处不断覆盖i,请问用sendmessage()如何像memo.lines.add()一样,形成列表,别覆盖
...全文
198 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
mygodsos 2008-10-13
  • 打赏
  • 举报
回复
我以为一句话能搞掂,看来只好如此
wts 2008-10-13
  • 打赏
  • 举报
回复
用自定义消息也可以实现。
在那个Memo所在窗体里写一个接受自定义消息的方法,里面可以Memo1.lines.add(...);
然后在你的程序里发送自定义消息,同时把要发送的文字传过去。

不过僵哥的那个代码并不复杂啊。这要还觉得复杂,那真的就什么也不用写了。
僵哥 2008-10-12
  • 打赏
  • 举报
回复
如果你理解了,就会觉得很简单.
mygodsos 2008-10-12
  • 打赏
  • 举报
回复
啊,大哥,那么复杂呀,请问有没有简单一点的
僵哥 2008-10-12
  • 打赏
  • 举报
回复
参考:
procedure TMemoStrings.Insert(Index: Integer; const S: string);
var
SelStart, LineLen: Integer;
Line: string;
begin
if Index >= 0 then
begin
SelStart := SendMessage(Memo.Handle, EM_LINEINDEX, Index, 0);
if SelStart >= 0 then Line := S + #13#10 else
begin
SelStart := SendMessage(Memo.Handle, EM_LINEINDEX, Index - 1, 0);
if SelStart < 0 then Exit;
LineLen := SendMessage(Memo.Handle, EM_LINELENGTH, SelStart, 0);
if LineLen = 0 then Exit;
Inc(SelStart, LineLen);
Line := #13#10 + s;
end;
SendMessage(Memo.Handle, EM_SETSEL, SelStart, SelStart);
SendMessage(Memo.Handle, EM_REPLACESEL, 0, Longint(PChar(Line)));
end;
end;
xxaabb 2008-10-12
  • 打赏
  • 举报
回复
先WM_GETTEXT 后再WM_SETTEXT成不成
DELPHI文本整理器 样式像记事本 // 字符串处理功能 unit StringFunctions; interface uses Windows, Messages, SysUtils, Variants, Classes, Forms, Dialogs, StdCtrls, Commctrl; type TStringFunction = class(TObject) private function IsUpper(ch: char): boolean; function IsLower(ch: char): boolean; function ToUpper(ch: char): char; function ToLower(ch: char): char; public procedure ReplaceSelText(Edit: TCustomEdit; const s: String); procedure UpperSelText(Edit: TCustomEdit); procedure LowerSelText(Edit: TCustomEdit); function UpperFistLetter(Memo: TMemo): string; procedure ClearBlankLine(Memo: TMemo); procedure ClearBlankSpace(Memo: TMemo); procedure ClearNum(Memo: TMemo); procedure ClearLetter(Memo: TMemo); procedure InsertNumber(Memo: TMemo); procedure InsertComment(Memo: TMemo); procedure BatchReplaceString(Memo: TMemo); procedure JustOneLine(Memo: TMemo); procedure ReLine(Memo: TMemo; n: Integer); procedure TextToHtml(sTextFile, sHtmlFile: string); function Proper(const s: string): string; function CNWordsCount(text: string): Integer; function ENWordsCount(text: string): Integer; end; var StrFunction: TStringFunction; implementation // 让代码设置Memo后可以让memo在Ctrl+Z撤销有效 procedure TStringFunction.ReplaceSelText(Edit: TCustomEdit; const s: String); begin SendMessage(Edit.Handle, EM_REPLACESEL, 1, LPARAM(PChar(s))); // Edit.Perform(EM_REPLACESEL, 1, LPARAM(PChar(s))); end; // Edit显示行号 // ------------------------------------------------------------------------------ // 去除空行 // Memo1.Text := StringReplace(Memo1.Text, #13#10#13#10, #13#10, [rfReplaceAll]); { //无法撤销 //空行的去掉 //本行只有空格的也去掉 //全选 //复制到剪切板上 } procedure TStringFunction.ClearBlankLine(Memo: TMemo); var i: Integer; list: TStringList; begin with Memo do begin if Lines.Count > 0 then begin list := TStringList.Create; for i := 0 to Lines.Count - 1 do if (Trim(Lines[i]) <> '') then list.Add(Lines[i]); SelectAll; ReplaceSelText(Memo, list.text); list.Free; end; end; end; // 去除空格 // 将 空格替换为空 procedure TStringFunction.ClearBlankSpace(Memo: TMemo); var s: string; begin s := StringReplace(Memo.Lines.text, ' ', '', [rfReplaceAll]); Memo.SelectAll; ReplaceSelText(Memo, s); end; // 去除一字符串中的所有的数字 procedure TStringFunction.ClearNum(Memo: TMemo); var str: string; i: Integer; begin str := '1234567890'; for i := 0 to Length(str) do Memo.text := StringReplace(Memo.Lines.text, str[i], '', [rfReplaceAll]); { rfReplaceAll TReplaceFlags = set of (rfReplaceAll, rfIgnoreCase); } end; // 去除一字符串中的所有的字母 procedure TStringFunction.ClearLetter(Memo: TMemo); var str: string; i: Integer; begin str := 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; for i := 0 to Length(str) do Memo.text := StringReplace(Memo.Lines.text, str[i], '', [rfReplaceAll]); end; // 批量替换关键字 procedure TStringFunction.BatchReplaceString(Memo: TMemo); var i: Integer; begin for i := 0 to Length(Memo.Lines.text) do Memo.text := StringReplace(Memo.Lines.text, Memo.Lines[i], '', [rfReplaceAll]); ClearBlankSpace(Memo); end; // ------------------------------------------------------------------------------ // 全角转半角 // 符号有哪些 procedure ConvertQtoB; begin end; // 半角转换全角 procedure ConvertBtoQ; begin end; { 转换选中的文本大写 } procedure TStringFunction.UpperSelText(Edit: TCustomEdit); var x, y: Integer; begin With Edit do begin x := SelStart; y := SelLength; if SelText <> '' then begin ReplaceSelText(Edit, UpperCase(SelText)); SelStart := x; SelLength := y; end else begin Edit.SelectAll; ReplaceSelText(Edit, UpperCase(Edit.text)); end; end; end; { 转换选中的文本小写 } procedure TStringFunction.LowerSelText(Edit: TCustomEdit); var x, y: Integer; begin With Edit do begin x := SelStart; y := SelLength; if SelText <> '' then begin ReplaceSelText(Edit, LowerCase(SelText)); SelStart := x; SelLength := y; end else begin Edit.SelectAll; ReplaceSelText(Edit, LowerCase(Edit.text)); end; end; end; { 判断字符是否是大写字符 } function TStringFunction.IsUpper(ch: char): boolean; begin Result := ch in ['A' .. 'Z']; end; { 判断字符是否是小写字符 } function TStringFunction.IsLower(ch: char): boolean; begin Result := ch in ['a' .. 'z']; end; { 转换为大写字符 } function TStringFunction.ToUpper(ch: char): char; begin Result := chr(ord(ch) and $DF); end; { 转换为小写字符 } function TStringFunction.ToLower(ch: char): char; begin Result := chr(ord(ch) or $20); end; { Capitalizes First Letter Of Every Word In S 单语首字母大写 } function TStringFunction.Proper(const s: string): string; var i: Integer; CapitalizeNextLetter: boolean; begin Result := LowerCase(s); CapitalizeNextLetter := True; for i := 1 to Length(Result) do begin if CapitalizeNextLetter and IsLower(Result[i]) then Result[i] := ToUpper(Result[i]); CapitalizeNextLetter := Result[i] = ' '; end; end; { Memo选中的首字母大写 } function TStringFunction.UpperFistLetter(Memo: TMemo): string; var i, j: Integer; begin with Memo do begin i := SelStart; j := SelLength; // SelText := Proper(SelText); ReplaceSelText(Memo, Proper(SelText)); SelStart := i; SelLength := j; end; end; // ------------------------------------------------------------------------------ procedure TStringFunction.InsertNumber(Memo: TMemo); var i: Integer; str: String; begin for i := 0 to Memo.Lines.Count do begin str := Format('%.4d. %s', [i, Memo.Lines[i]]); Memo.Lines[i] := str; Application.ProcessMessages; end; end; // 注释和取消注释 // 获得选中的文本的起始行和结束行 procedure TStringFunction.InsertComment(Memo: TMemo); var str: string; x, y: Integer; begin str := Memo.SelText; x := Memo.SelStart; y := Memo.SelLength; if str = '' then Exit; // Memo.SetSelText('//' +str); Memo.SelText := '//' + str; Memo.SelStart := x + 2; Memo.SelLength := y + 2; end; // ------------------------------------------------------------------------------ // 合并成一行 procedure TStringFunction.JustOneLine(Memo: TMemo); var s: string; i: Integer; begin for i := 0 to Memo.Lines.Count - 1 do s := s + Memo.Lines[i]; Memo.SelectAll; ReplaceSelText(Memo, s); end; // ------------------------------------------------------------------------------ // 重新分行 { var n: Integer; begin n := StrToInt(InputBox('重新分行', '每行几个字符', '8')); ReLine(Memo1, n); end; } procedure TStringFunction.ReLine(Memo: TMemo; n: Integer); var s: string; i, j, k: Integer; L: TStringList; begin L := TStringList.Create; j := 1; for k := 0 to Memo.Lines.Count - 1 do s := s + Memo.Lines[k]; if Trim(s) <> '' then begin for i := 0 to (Length(s) div n) do // 几行 begin j := j + n; L.Add(Copy(s, j - n, n)); // COPY 的第一位不是0是1 // 每行的字符 end; end; Memo.SelectAll; ReplaceSelText(Memo, L.text); L.Free; end; // ------------------------------------------------------------------------------ // 获得汉字字符个数 function TStringFunction.CNWordsCount(text: string): Integer; var i, sum, c: Integer; begin Result := 0; c := 0; sum := Length(text); if sum = 0 then Exit; for i := 0 to sum do begin if ord(text[i]) >= 127 then begin Inc(c); end; end; Result := c; end; // 获得非汉字字符个数 function TStringFunction.ENWordsCount(text: string): Integer; var i, sum, e: Integer; begin Result := 0; e := 0; sum := Length(text); if sum = 0 then Exit; for i := 0 to sum do begin if (ord(text[i]) >= 33) and (ord(text[i]) <= 126) then begin Inc(e); end; end; Result := e; end; { TextToHtml('C:\1.txt','c:\2.htm'); } procedure TStringFunction.TextToHtml(sTextFile, sHtmlFile: string); var aText: TStringList; aHtml: TStringList; i: Integer; begin aText := TStringList.Create; try aText.LoadFromFile(sTextFile); aHtml := TStringList.Create; try aHtml.Clear; aHtml.Add(''); aHtml.Add(''); for i := 0 to aText.Count - 1 do aHtml.Add(aText.Strings[i] + '
'); aHtml.Add(''); aHtml.Add(''); aHtml.SaveToFile(sHtmlFile); finally aHtml.Free; end; finally aText.Free; end; end; Initialization StrFunction := TStringFunction.Create; Finalization StrFunction.Free; end.
Delphi彻底更换桌面壁纸及剪贴板监控程序,需要使用到下列delphi类库:   Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,    StdCtrls, registry, Clipbrd, ExtCtrls{监视剪贴板单元};   定义函数实现壁纸的注册表修改:   procedure TForm1.Button2Click(Sender: TObject);   Var    Reg:Tregistry; //Tregistry 对象在Registry 单元中声明,需用Uses令引用Registry单元   Begin    Reg:=Tregistry.Create;{创建Tregistry对象的实例}    Reg.Rootkey:= Hkey_Current_User;{设置根键名称}    Reg.OpenKey('Control Panel\Desktop',False); {打开Control Panel\Desktop 路径对应的主键}    Reg.WriteString('TileWallPaper', '0');    Reg.WriteString('Wallpaper','C:\C:\My Documents\Beautiful.bmp') ; //向TileWallpaper 和Wallpaper串覆盖写入新值    Systemparametersinfo(SPI_SETDESKWallpaper,0,Nil,SPIF_SendChange);{向Windows发送消息,通知Windows更换壁纸}    Reg.CloseKey;{将更改内容写入注册表并关闭}    Reg.Free;{释放对象}   End;   //处理剪切板内容,剪贴板监控功能:   //将WM_DRAWCLIPBOARD消息传递到下一个观察链中的窗口   SendMessage(NextClipHwnd,AMessage.Msg,AMessage.WParam,AMessage.LParam);   //查询剪贴板中特定格式的数据内容   if (Clipboard.HasFormat(CF_TEXT) or Clipboard.HasFormat(CF_OEMTEXT)) then   begin    //处理剪贴板中文本内容    Memo1.Lines.Add(Clipboard.asText) ;   End Else   if Clipboard.HasFormat(CF_BITMAP) Then   Begin    //处理剪贴板中图片内容    Bitmap := TBitmap.Create;    try    Bitmap.Assign(Clipboard);    Image1.Canvas.Draw(0, 0, Bitmap);    finally    Bitmap.Free;    end;   End ;如需完整源码,请在本面底部下载链接下载。
unit TreeViewFunctions; interface uses Windows, Messages, SysUtils, Variants, Classes, ComCtrls, Controls, Forms, FileCtrl, StrUtils, Masks, Vcl.OleCtrls, SHDocVw, IOUtils; procedure SaveTreeViewExplandState(TreeView: TTreeView; FileName: string); procedure LoadTreeViewExplandState(TreeView: TTreeView; FileName: string); function ExtractNewFolderPath(FileName: string; NewText: string): string; procedure HideHideHorizontalScrollBar(TreeView: TTreeView); function IsEmptyDir(sDir: String): Boolean; function AttachMentsExists(FileName: String): Boolean; procedure SetIcons(TreeView: TTreeView; list: TStringList); procedure EnumText(s: string; aItem: TTreeNode); function AttachmentsFolder(FileName: String): string; function ExtractNodeFullPath(TreeView: TTreeView): string; function Get_node_path(node: TTreeNode): string; function ExtractTreeViewFileName(RootPath: string; TreeView: TTreeView): string; /// /// Node.Selected := true; Node.Focused := true; /// /// /// Node.Selected := true; Node.Focused := true; /// /// /// Node.Selected := true; Node.Focused := true; /// function OpenFile(Path: string; RichEdit: TRichEdit; TreeView: TTreeView) : Boolean; overload; function OpenFile(Path: string; Webbrowser: TWebbrowser; TreeView: TTreeView) : Boolean; overload; procedure GetDirectories(Tree: TTreeView; Directory: string; Item: TTreeNode; IncludeFiles: Boolean); procedure DirToTreeView(Tree: TTreeView; Directory: string; Root: TTreeNode; IncludeFiles: Boolean; FileExt: string); procedure QSetPerpoty(TreeView: TTreeView); function ItemExist(Text: string; TreeView: TTreeView): Boolean; function RemoveDirs(folderPath: string): Boolean; function __RenameFile(OldName: string; Title: string): Boolean; function RenameFolder(filePath: string; Title: string): Boolean; var list: TStringList; implementation { // "D:\C++Builder学习大全中文版\index.htm" // "D:\C++Builder学习大全中文版\" // "index_files" // "D:\C++Builder学习大全中文版\index_files" var s, s1, s2: string; begin s := 'D:\C++Builder学习大全中文版\index.htm'; s1:=ExtractNewFolderPath(s,'_files'); s2 := ExtractNewFolderPath(s, '_AttachMents'); Memo1.lines.Add(s); Memo1.Lines.Add(s1); Memo1.lines.Add(s2); end; } function ExtractNewFolderPath(FileName: string; NewText: string): string; var _filesFolder: string; // "D:\C++Builder学习大全中文版\" _filesFolderName: string; // "index_files" _filesFolderPath: String; begin _filesFolder := ExtractFilePath(FileName); _filesFolderName := ChangeFileExt(ExtractFileName(FileName), '') + NewText; _filesFolderPath := _filesFolder + _filesFolderName; Result := _filesFolderPath; end; { SaveTreeViewExplandState(TreeView1,'TreeView.txt'); } procedure SaveTreeViewExplandState(TreeView: TTreeView; FileName: string); var list: TStringList; i: Integer; begin list := TStringList.Create; With TreeView do begin for i := 0 to Items.Count - 1 do begin if Items.Item[i].Expanded then list.Add(IntToStr(i)); end; list.Add(IntToStr(Selected.AbsoluteIndex)); end; list.SaveToFile(FileName); list.free; end; { LoadTreeViewExplandState(TreeView1, 'abc.txt'); } procedure LoadTreeViewExplandState(TreeView: TTreeView; FileName: string); var list: TStringList; i: Integer; node: TTreeNode; begin list := TStringList.Create; with list do begin list.LoadFromFile(FileName); for i := 0 to Count - 2 do // 最后一行放的是最后选中的那个节点索引 begin TreeView.Items[StrToInt(list[i])].Expand(False); end; node := TreeView.Items[StrToInt(list[Count - 1])]; TreeView.Select(TreeView.Items[StrToInt(list[Count - 1])], []); // node.Selected := True; // node.Focused := True; TreeView.SetFocus; TreeView.Focused; free; end; end; { FUNCTION ulong ShowScrollBar(ulong hwnd,ulong wBar,ulong bShow) LIBRARY "user32.dll" constant long SB_HORZ = 0 constant long SB_VERT = 1 constant long SB_BOTH = 3 } procedure HideHideHorizontalScrollBar(TreeView: TTreeView); begin // no responed NEW FORM TEST // ShowScrollBar(TreeView.Handle,SB_HORZ,False); end; // procedure // begin // { 当拖拽的高度不够的时候自动滚动滚动条 } // with TreeView1 do // begin // if (Y < 15) then // SendMessage(Handle, WM_VSCROLL, SB_LINEUP, 0) // else if (Height - Y < 15) then // SendMessage(Handle, WM_VSCROLL, SB_LINEDOWN, 0); // end; // end; { 返回 附件文件夹 "D:\C++Builder学习大全中文版\新建文本文档.htm" D:\C++Builder学习大全中文版\新建文本文档_Attachments } function AttachmentsFolder(FileName: String): string; begin Result := ExtractFilePath(FileName) + ChangeFileExt(ExtractFileName(FileName), '') + '_Attachments'; end; function AttachMentsExists(FileName: String): Boolean; var f: string; begin f := ExtractFilePath(FileName) + ChangeFileExt(ExtractFileName(FileName), '') + '_Attachments'; Result := DirectoryExists(f); end; procedure EnumText(s: string; aItem: TTreeNode); var node: TTreeNode; str: string; begin node := aItem; while node nil do begin if s = '' then str := node.Text else str := s + '\' + node.Text; list.Add(str); /// ////////////////////////// if node.HasChildren then EnumText(str, node.getFirstChild); node := node.getNextSibling; end; end; function IsEmptyDir(sDir: String): Boolean; var sr: TSearchRec; begin Result := True; if Copy(sDir, Length(sDir) - 1, 1) '\' then sDir := sDir + '\'; if FindFirst(sDir + '*.*', faAnyFile, sr) = 0 then repeat if (sr.Name '.') and (sr.Name '..') then begin Result := False; break; end; until FindNext(sr) 0; FindClose(sr); end; { 是文件 夹的设置为1 是文件 的设置为 2 } procedure SetIcons(TreeView: TTreeView; list: TStringList); var i: Integer; begin with TreeView do begin for i := 0 to Items.Count - 1 do begin if DirectoryExists(list.Strings[i]) then begin Items[i].ImageIndex := 0; Items[i].SelectedIndex := 0; Items[i].StateIndex := 0; end; if FileExists(list.Strings[i]) then begin Items[i].ImageIndex := 1; Items[i].SelectedIndex := 1; Items[i].StateIndex := 1; end; if (AttachMentsExists(list.Strings[i])) then if not IsEmptyDir(AttachmentsFolder(list.Strings[i])) then begin // Form1.Memo1.LINES.Add( AttachmentsFolder(list.Strings[i])); Items[i].ImageIndex := 2; Items[i].SelectedIndex := 2; Items[i].StateIndex := 2; end; end; end; end; procedure QSetPerpoty(TreeView: TTreeView); begin with TreeView do begin // Align := alBottom; // Anchors := [akLeft, akTop, akBottom, akRight]; Items.Clear; // BorderStyle := bsNone; Cursor := crHandPoint; ReadOnly := True; ShowHint := True; RowSelect := True; ShowButtons := True; ShowRoot := True; ShowLines := False; SortType := stText; HideSelection := False; RightClickSelect := True; DragMode := dmAutomatic; // Color := RGB(238, 243, 246); end; end; { 实际重命名 C:\windows\test.txt C:\windows\csadsajas.txt MoveFile(PChar('C:\1.txt'),PChar('C:\ABC.txt')); if not __RenameFile('C:\tree.txt','TreeView') then Application.MessageBox('重命名文件失败','重命名',MB_ICONERROR); } { 重命名文件 } function __RenameFile(OldName: string; Title: string): Boolean; var NewName: string; begin NewName := Format('%s%s%s', [ExtractFilePath(OldName), Title, ExtractFileExt(OldName)]); Result := MoveFile(PChar(OldName), PChar(NewName)); end; // 重命名文件夹 // RenameFolder('C:\1\','2'); // MoveFile('C:\1','C:\2'); // MoveFile('C:\1\','C:\2\'); function RenameFolder(filePath: string; Title: string): Boolean; var s, s1: string; begin // filePath:='C:\Windows\System32\'; // s = ExtractFileDir(filepath) = 'C:\Windows\System32' s := ExtractFileDir(filePath); // s1 = ExtractFileDir(s) = 'C:\Windows' // s1 ='C:\Windows' +'\'+ titles s1 := ExtractFileDir(s) + '\' + Title; Result := MoveFile(PChar(s), PChar(s1)); end; { IOUtils } function RemoveDirs(folderPath: string): Boolean; begin Result := False; if TDirectory.IsEmpty(folderPath) then begin TDirectory.Delete(folderPath); Result := True; end else begin if Application.MessageBox('确定要删除这个文件夹吗? 删除后无法恢复!', '提示', MB_ICONQUESTION + MB_YESNO) = ID_YES then begin TDirectory.Delete(folderPath, True); Result := True; end; end; // if TDirectory.Exists(folderPath) then // begin // Application.MessageBox('删除文件失败'+#13#10+'文件正确被使用?','错误',MB_ICONERROR+MB_OK); // Result:=False; // end; end; { if not ItemExist('Edit1.Text',TreeView1) then TreeView1.Items.AddChild(Treeview1.Selected,'Edit1.Text'); } function ItemExist(Text: string; TreeView: TTreeView): Boolean; var i: Integer; begin Result := False; if (Trim(Text) '') then begin for i := 0 to TreeView.Items.Count - 1 do if Trim(Text) = Trim(TreeView.Items[i].Text) then begin Result := True; Exit; end; end; Result := False; end; // ------------------------------------------------------------------------------ { TreeView获得选中的完整路径 aaaa\ssss\bbbb } function ExtractNodeFullPath(TreeView: TTreeView): string; var Path: string; Parent: TTreeNode; // Node: TTreeNode; begin Path := TreeView.Selected.Text; Parent := TreeView.Selected.Parent; while Parent nil do begin Path := Parent.Text + '\' + Path; Parent := Parent.Parent; end; Result := Path; end; function Get_node_path(node: TTreeNode): string; var Path: string; TreeNode: TTreeNode; begin Path := node.Text; TreeNode := node.Parent; while TreeNode nil do begin Path := TreeNode.Text + '\' + Path; TreeNode := TreeNode.Parent; end; Result := Path; end; { 获得文件完整路径 C:\abc\int.cpp } function ExtractTreeViewFileName(RootPath: string; TreeView: TTreeView): string; var FileName: string; begin Result := ''; if TreeView.Selected = nil then Exit; FileName := RootPath + ExtractNodeFullPath(TreeView); // 当前选中的文件名 if not FileExists(FileName) then Exit; Result := FileName; end; { 用RICHEDIT打开TREEVIEW中的文件 } function OpenFile(Path: string; RichEdit: TRichEdit; TreeView: TTreeView) : Boolean; overload; var FileName: string; begin Result := False; FileName := ExtractTreeViewFileName(Path, TreeView); if FileExists(FileName) then begin RichEdit.Lines.LoadFromFile(FileName); Result := True; end end; function OpenFile(Path: string; Webbrowser: TWebbrowser; TreeView: TTreeView) : Boolean; overload; var FileName: string; begin Result := False; FileName := ExtractTreeViewFileName(Path, TreeView); if FileExists(FileName) then begin Webbrowser.Navigate(FileName); Result := True; end end; { 将1个目录里面所有的文件添加到TREEVIEW中 GetDirectories(TreeView1, 'D:\DATA', nil, True); } procedure GetDirectories(Tree: TTreeView; Directory: string; Item: TTreeNode; IncludeFiles: Boolean); var SearchRec: TSearchRec; ItemTemp: TTreeNode; begin Tree.Items.BeginUpdate; if Directory[Length(Directory)] '\' then Directory := Directory + '\'; if FindFirst(Directory + '*.*', faDirectory, SearchRec) = 0 then begin repeat if (SearchRec.Attr and faDirectory = faDirectory) and (SearchRec.Name[1] '.') then begin if (SearchRec.Attr and faDirectory > 0) then Item := Tree.Items.AddChild(Item, SearchRec.Name); ItemTemp := Item.Parent; GetDirectories(Tree, Directory + SearchRec.Name, Item, IncludeFiles); Item := ItemTemp; end else if IncludeFiles then if SearchRec.Name[1] '.' then Tree.Items.AddChild(Item, SearchRec.Name); until FindNext(SearchRec) 0; FindClose(SearchRec); Tree.Items.EndUpdate; end; end; { 将1个目录里面所有的文件添加到TREEVIEW中 DirToTreeView(TreeView1,'D:\Data\',nil,True,'.cpp'); } procedure DirToTreeView(Tree: TTreeView; Directory: string; Root: TTreeNode; IncludeFiles: Boolean; FileExt: string); var SearchRec: TSearchRec; Node1: TTreeNode; begin with Tree.Items do begin BeginUpdate; if Directory[Length(Directory)] '\' then Directory := Directory + '\'; if FindFirst(Directory + '*.*', faDirectory, SearchRec) = 0 then begin Application.ProcessMessages; repeat { 添加文件夹 } if (SearchRec.Attr and faDirectory = faDirectory) and (SearchRec.Name[1] '.') then begin if SameText(RightStr(SearchRec.Name, 12), '_AttachMents') then // 不添加 _AttachMents这个文件夹 Continue; if (SearchRec.Attr and faDirectory > 0) then Root := AddChild(Root, SearchRec.Name); Node1 := Root.Parent; DirToTreeView(Tree, Directory + SearchRec.Name, Root, IncludeFiles, FileExt); Root := Node1; end else if IncludeFiles then { 添加文件 } if SearchRec.Name[1] '.' then { .TXT .txt .TxT .tXT 为一样的 } if SameText(RightStr(SearchRec.Name, 4), FileExt) then { 只添加 .CPP格式文件 } AddChild(Root, SearchRec.Name); until FindNext(SearchRec) 0; FindClose(SearchRec) end; EndUpdate; end; end; end.
unit Unit3; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, xpWindow, StdCtrls, AAFont, AACtrls; type TForm3 = class(TForm) Label2: TLabel; xpWindow1: TxpWindow; AAFadeText1: TAAFadeText; private { Private declarations } public { Public declarations } end; var Form3: TForm3; implementation {$R *.dfm} end. unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, shellapi, Menus, StdCtrls, ExtCtrls, AAFont, AACtrls, AAFontDialog,Registry, xpWindow; const wm_traynotify=wm_user+1000; type TForm1 = class(TForm) PopupMenu1: TPopupMenu; NToDos: TMenuItem; NCancel: TMenuItem; NReboot: TMenuItem; NClose: TMenuItem; Memo1: TMemo; N1: TMenuItem; GroupBox1: TGroupBox; Timer1: TTimer; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CheckBox3: TCheckBox; AAFontDialog1: TAAFontDialog; xpWindow1: TxpWindow; AAScrollText1: TAAScrollText; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure formdestroy(sender:tobject); procedure btnCancelClick(Sender: TObject); procedure btnToDosClick(Sender: TObject); procedure btnRebootClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure CheckBox2Click(Sender: TObject); procedure CheckBox3Click(Sender: TObject); procedure Timer1Timer(Sender: TObject); procedure N1Click(Sender: TObject); private { Private declarations } my_tray_icon:tnotifyicondata; procedure wmmytrayiconcallback(var msg:tmessage); message wm_traynotify; public { Public declarations } // procedure GameGontrol(sender:TObject); end; var Form1: TForm1; game:array[0..255] of string; FilePath : string; implementation uses Unit2, Unit3; {$R *.DFM} // 自定义过程,用于程序运行后,屏蔽操作系统的任务管理器 procedure DisableTaskmgr(Key: Boolean); Var Reg:TRegistry; Begin Reg:=TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Policies\System', True) then begin if Key then Reg.WriteString('DisableTaskMgr','1') else Reg.WriteInteger('DisableTaskMgr',0); Reg.CloseKey; end; except Reg.Free; end; end; procedure TForm1.FormCreate(Sender: TObject); var key:boolean; hKey:string; hReg:TregIniFile; registerTemp:TRegistry; begin // 程序开机自动运行 try registerTemp:=TRegistry.create; registerTemp.RootKey:=HKEY_LOCAL_MACHINE; if registerTemp.OpenKey('software\Microsoft\Windows\currentversion\run',True) then begin registerTemp.WriteString(extractfilename(application.ExeName),application.ExeName); end; except Showmessage('该程序无法自动运行,请及时与作者联系!'); end; disableTaskmgr(true); // 程序运行后,屏蔽系统任务管理器,防止学生强制关闭软件 visible:=false; application.ShowMainForm:=visible; with my_tray_icon do begin cbsize:=sizeof(tnotifyicondata); wnd:=handle; uid:=1; uflags:=nif_message or nif_icon or nif_tip; ucallbackmessage:=wm_traynotify; hicon:=loadicon(0,idi_winlogo); sztip:=''; end; shell_notifyicon(nim_add,@my_tray_icon); end; procedure tform1.formdestroy(sender:tobject); begin shell_notifyicon(nim_delete,@my_tray_icon); end; procedure tform1.wmmytrayiconcallback(var msg:tmessage); var cursorpos:tpoint; begin case msg.LParam of wm_lbuttondown: begin visible:=not visible; application.ShowMainForm:=visible; setforegroundwindow(application.handle); end; wm_rbuttondown: begin getcursorpos(cursorpos); popupmenu1.Popup(cursorpos.x,cursorpos.y); end; end; end; procedure TForm1.btnCancelClick(Sender: TObject); begin exitwindowsex(ewx_force,0); end; procedure TForm1.btnToDosClick(Sender: TObject); begin exitwindowsex(ewx_logoff,0); end; procedure TForm1.btnRebootClick(Sender: TObject); var st : SYSTEMTIME; hToken : THANDLE; tkp : TOKEN_PRIVILEGES; rr : Dword; begin OpenProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY,hToken); LookupPrivilegeValue(nil,'SeShutdownPrivilege',tkp.Privileges[0].Luid); // 设定权限为1 tkp.PrivilegeCount := 1; tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED; // 得到权限 AdjustTokenPrivileges(hToken, FALSE, tkp, 0,nil,rr); // 重起计算机 ExitWindowsEx(EWX_REBOOT , 0) end; procedure TForm1.btnCloseClick(Sender: TObject); begin // exitwindowsex(ewx_shutdown,0); Formclose.Show; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin if checkbox1.Checked=true then begin checkbox2.Checked:=false; checkbox3.Checked:=false; end ; end; procedure TForm1.CheckBox2Click(Sender: TObject); begin if checkbox2.Checked=true then begin checkbox1.Checked:=false; checkbox3.Checked:=false; end; end; procedure TForm1.CheckBox3Click(Sender: TObject); begin if checkbox3.Checked=true then begin checkbox2.Checked:=false; checkbox1.Checked:=false; end; end; procedure TForm1.Timer1Timer(Sender: TObject); var hcurrentWindow:HWnd; szText:array[0..254] of char; Gamefile:TextFile; // 文本文件,存放已经知道的游戏句柄 s:string; // i,j:integer; st:SYSTEMTIME; hToken:THANDLE; tkp:TOKEN_PRIVILEGES; RR:Dword; begin try if form3.Showing=true then begin form3.Close; end; memo1.Clear; hCurrentWindow:=GetWindow(Handle,GW_HWNDFIRST); While hCurrentWindow<>0 do begin if GetWindowText(hCurrentWindow,@szText,255)>0 then Memo1.Lines.Add(strpas(@sztext)+Datetimetostr(now)); // for i:=0 to 254 do // begin try FilePath := ExtractFilePath(Application.ExeName); // 程序运行后,自动获取Game.txt的路径 assignfile(Gamefile,FilePath+'\game.txt'); // 准备读取game.txt中的信息 reset(Gamefile); except showmessage('^_^'); end; while not eof(Gamefile) do begin readln(Gamefile,s); if strPas(@szText)=s then begin form3.Show; // 发现游戏后,分别处理 if checkbox1.Checked=true then begin sendMessage(hCurrentWindow,WM_CLOSE,0,0); // 关闭游戏 end; if checkbox3.Checked=true then // 关闭计算机 begin openProcessToken(GetCurrentProcess(),TOKEN_ADJUST_PRIVILEGES OR TOKEN_QUERY,hToken); LookupPrivilegeValue(nil,'SeShutdownPrivilege',tkp.Privileges[0].Luid); tkp.privilegecount:=1; tkp.privileges[0].Attributes:=se_privilege_enabled; adjusttokenprivileges(hToken,false,tkp,0,nil,rr); exitwindowsex(ewx_poweroff,0); end; if checkbox2.Checked=true then begin exitwindowsex(ewx_force,0); // 注销计算机 end; end; end; // end; hcurrentwindow:=getwindow( hCurrentWindow,gw_hwndnext); end; finally end; end; procedure TForm1.N1Click(Sender: TObject); var p:pchar; //指针,指向将被打开的帮助文件 begin p:=pchar(ExtractFilePath(Application.ExeName)+'Help.chm'); shellexecute(0,nil,p,nil,nil,SW_NORMAL); end; end. unit Unit2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,registry,xpWindow; type TFormclose = class(TForm) GroupBox1: TGroupBox; Label1: TLabel; Edit1: TEdit; Button1: TButton; xpWindow1: TxpWindow; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Formclose: TFormclose; implementation uses Unit1; {$R *.dfm} // 自定义过程,用于程序运行后,屏蔽操作系统的任务管理器 procedure DisableTaskmgr(Key: Boolean); Var Reg:TRegistry; Begin Reg:=TRegistry.Create; try Reg.RootKey := HKEY_CURRENT_USER; if Reg.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Policies\System', True) then begin if Key then Reg.WriteString('DisableTaskMgr','1') else Reg.WriteInteger('DisableTaskMgr',0); Reg.CloseKey; end; except Reg.Free; end; end; // 自定义过程,实现系统开机自动运行 procedure SetAuttorun(aProgTitle,aCmdLine:string;aRunOnce:boolean); var hKey:string; hReg:TRegIniFile; begin if aRunOnce then hKey:='Once' else hKey:=''; hReg:=TRegIniFile.Create(''); hReg.RootKey:=HKEY_LOCAL_MACHINE; hReg.WriteString('software\microsoft\windows\currentversion\run' +hKey+#0,aProgTitle,aCmdLine); // 修改操作系统注册表 hReg.Destroy; end; procedure TFormclose.Button1Click(Sender: TObject); var key:boolean; begin if edit1.Text='162534' then begin key:=false; DisableTaskmgr(key); // 当系统推出时恢复任务管理器 application.Terminate; end else begin showmessage('密码错误!'); formclose.Close; end; edit1.Clear; end; end.

1,183

社区成员

发帖
与我相关
我的任务
社区描述
Delphi Windows SDK/API
社区管理员
  • Windows SDK/API社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧