Проблема с блокнотом в делфи

привет, мы используем версию Delphi 5. Возникла проблема при открытии блокнота в delphi. Мы хотим открыть блокнот нажатием кнопки и передать ему данные, чтобы блокнот мог отображать эти данные. Я не хочу экономить. пожалуйста, помогите мне в этом. благодаря.


person naren    schedule 11.07.2011    source источник
comment
Вы пытаетесь открыть приложение «Блокнот» или простой текстовый файл?   -  person Saanch    schedule 11.07.2011
comment
Я хочу открыть приложение блокнота, чтобы мы могли сохранять данные блокнота в зависимости от пользователя. благодаря.   -  person naren    schedule 11.07.2011
comment
Может быть, вы можете просто написать небольшую форму с помощью TMemo и бросить Блокнот?   -  person Uli Gerhardt    schedule 11.07.2011
comment
@naren TMemo с alClient внутри TForm практически идентичен Блокноту, и вы получаете гораздо больше контроля.   -  person David Heffernan    schedule 11.07.2011


Ответы (4)


Вы можете использовать что-то вроде:

uses
  Clipbrd;

procedure LaunchNotepad(const Text: string);
var
  SInfo: TStartupInfo;
  PInfo: TProcessInformation;
  Notepad: HWND;
  NoteEdit: HWND;
  ThreadInfo: TGUIThreadInfo;
begin
  ZeroMemory(@SInfo, SizeOf(SInfo));
  SInfo.cb := SizeOf(SInfo);
  ZeroMemory(@PInfo, SizeOf(PInfo));
  CreateProcess(nil, PChar('Notepad'), nil, nil, False,
                NORMAL_PRIORITY_CLASS, nil, nil, sInfo, pInfo);
  WaitForInputIdle(pInfo.hProcess, 5000);

  Notepad := FindWindow('Notepad', nil);
  // or be a little more strict about the instance found
//  Notepad := FindWindow('Notepad', 'Untitled - Notepad');

  if Bool(Notepad) then begin
    NoteEdit := FindWindowEx(Notepad, 0, 'Edit', nil);
    if Bool(NoteEdit) then begin
      SendMessage(NoteEdit, WM_SETTEXT, 0, Longint(Text));

      // To force user is to be asked if changes should be saved
      // when closing the instance
      SendMessage(NoteEdit, EM_SETMODIFY, WPARAM(True), 0);
    end;
  end
  else
  begin
    ZeroMemory(@ThreadInfo, SizeOf(ThreadInfo));
    ThreadInfo.cbSize := SizeOf(ThreadInfo);
    if GetGUIThreadInfo(0, ThreadInfo) then begin
      NoteEdit := ThreadInfo.hwndFocus;
      if Bool(NoteEdit) then begin
        Clipboard.AsText := Text;
        SendMessage(NoteEdit, WM_PASTE, 0, 0);
      end;
    end;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  LaunchNotepad('test string');
end;
person Sertac Akyuz    schedule 11.07.2011
comment
+1 за предоставление ответа, передающего текст в Блокнот без сохранения его в файл, как и запросил OP. - person Marjan Venema; 11.07.2011
comment
+1 за WaitForInputIdle. Я отредактировал ваш ответ, чтобы удовлетворить пользователей (таких как я), установивших настраиваемый блокнот, такой как Notepad2, Notepad ++ и т. Д. Хотя я не смог заставить его работать через WM_SETTEXT из-за проблем с юникодом, поэтому я использовал буфер обмена. - person NGLN; 11.07.2011
comment
@NGLN - Попытка найти (активное) окно редактирования для кучи программ редактирования текста не будет интересной, поэтому буфер обмена, вероятно, является лучшим выбором для альтернативных блокнотов. Однако могут быть и другие проблемы, например, я помню текущий сеанс для следующего запуска в блокноте ++, поэтому он никогда не открывает пустой документ при запуске. В любом случае, спасибо за редактирование, а также за то, что не newlineing мое начало. :) - person Sertac Akyuz; 12.07.2011
comment
@Sertac Да, и мне действительно было интересно, как вам понравится синтаксис end else begin. ;) - person NGLN; 12.07.2011
comment
@Sertac Что ж, после повторного прочтения вашего комментария поиск активного окна, похоже, не является проблемой для GetGUITreadInfo, но причина, по которой я использовал буфер обмена, заключалась в том, что отправка WM_SETTEXT привела к вставке только первого символа в элемент управления редактирования Notepad *, который Я перевел как проблему с юникодом. - person NGLN; 12.07.2011
comment
@NGLN - это действительно похоже на несовместимость с юникодом, но на какой стороне ошибка? Я могу получить ту же ошибку, отправив широкую строку в обычный блокнот с помощью SendMessageA, или могу отправить искаженный текст, отправив строку ansi с помощью SendMessageW. Я могу установить тексты Notepad (unicode), ConTEXT (ansi) с помощью SendMessageA или SendMessageW, если я использую соответствующий тип строки. - person Sertac Akyuz; 12.07.2011
comment
Это хороший ответ, но я бы посоветовал вообще не использовать Блокнот. Некоторые аргументы: захват буфера обмена может показаться невинным, но я ненавижу, когда приложения не предупреждают меня об этом, и в зависимости от внешнего приложения могут возникнуть некоторые проблемы, даже с якобы универсальным, таким как Блокнот. (наполовину связанные: blogs.msdn.com/b /oldnewthing/archive/2010/01/28/9954432.aspx) - person Leonardo Herrera; 12.07.2011

Вы можете использовать следующую команду в событии нажатия кнопки. Укажите имя файла, который вы хотите открыть в textFileName.txt

ShellExecute(Handle,'open', 'c:\windows\notepad.exe','textFileName.txt', nil, SW_SHOWNORMAL) ;

Если вы хотите открыть пустой текстовый файл и не хотите сохранять какие-либо данные, вы можете использовать следующий метод для события клика. ShellExecute(Handle,'open', 'c:\windows\notepad.exe',nil, nil, SW_SHOWNORMAL) ;

Добавьте также ShellApi в класс использования.

Обновленный код

    procedure TForm1.Button1Click(Sender: TObject);
    var
    tempString : TStringList;
    begin
      tempString := TStringList.Create;
      try
        tempString.Add('The text you wanted to display');
        tempString.SaveToFile('C:\~tempFile.txt');
      finally
        tempString.Free;
      end;
      ShellExecute(Handle,'open', 'c:\windows\notepad.exe','C:\~tempFile.txt', nil, SW_SHOWNORMAL) ;
    end;
person Saanch    schedule 11.07.2011
comment
на самом деле не хочу сохранять файл. Я хочу передать данные в блокнот через delphi и сохранить эти данные из блокнота. благодаря. - person naren; 11.07.2011
comment
Вы хотите открыть приложение «Блокнот», и пользователь наберет в нем что-то, но не обязательно сохранит данные. я прав? - person Saanch; 11.07.2011
comment
Нет, на самом деле у меня есть строковые данные, которые я хочу отобразить в блокноте. После того, как он откроется в блокноте, пользователь сам решит, сохранять этот файл или нет. Благодарность - person naren; 11.07.2011

Если вы не хотите, чтобы они могли сохранять данные, было бы более разумно сделать свой собственный Блокнот похожим, в конце концов, для этого хорош TMemo, а затем разрешить им редактировать только текст - если это ваше требование. В противном случае мало что помешает им сохранить файл.

person BugFinder    schedule 11.07.2011

Блокнот в Delphi.

  1. Возьмите один TMemo и дайте имя как: (memNotepad)

  2. Возьмите один TrzOpenDialog (rzopdlgOpenDialog)

  3. Возьмите один TrzSaveDialog (rzsvdlgSaveDialog)
  4. Возьмите один FontDialog (ftdlgFontDialog)
  5. Take one TMainMenu (mmMainMenu)
    • add the menu items File : New,Open,Save,SaveAs,Exit, Edit : Cut,Copy,Paste,Font

Код:

********************************************************************
unit ufrmNotePad;

interface

uses

  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Menus, RzShellDialogs, cxGraphics, cxCustomData,
  cxStyles, cxTL, cxControls, cxInplaceContainer, IniFiles;

type
  TfrmNotepad = class(TForm)

    memNotePad: TMemo;
    rzopdlgOpenDialog: TRzOpenDialog;
    rzsvdlgSaveDialog: TRzSaveDialog;
    mmMainMenu: TMainMenu;
    mniFile: TMenuItem;
    mniSave: TMenuItem;
    mniOpen: TMenuItem;
    mniNew: TMenuItem;
    mniSaveAs: TMenuItem;
    mniEdit: TMenuItem;
    mniPaste: TMenuItem;
    mniCopy: TMenuItem;
    mniCut: TMenuItem;
    ftdlgFontDialog: TFontDialog;
    mniFont: TMenuItem;
    mniExit: TMenuItem;
    procedure mniOpenClick(Sender: TObject);
    procedure mniSaveClick(Sender: TObject);
    procedure mniNewClick(Sender: TObject);
    procedure mniSaveAsClick(Sender: TObject);
    procedure mniCopyClick(Sender: TObject);
    procedure mniPasteClick(Sender: TObject);
    procedure mniCutClick(Sender: TObject);
    procedure mniFontClick(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure mniEditClick(Sender: TObject);
    procedure mniExitClick(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);

  private

    { Private declarations }
    procedure OpenDialog;
    procedure SaveDialog;
    procedure NewNotepad;
    procedure SaveAS;
    procedure Copy;
    procedure Cut;
    procedure Paste;
    procedure Font;
    procedure SaveSettingInToFile;
    procedure RetrieveSettingFromTheFile;
  public

    { Public declarations }
    FIniFile : TIniFile;
    FFileName : String;
    FCount : Integer;
  end;

var
  frmNotepad : TfrmNotepad;

implementation

{$R *.dfm}

{ Open File from the disk }

{ FCount- helps for save the file, if file is already save then FCount := 1 else FCount := 0}

{ FFileName - helps for store the filename of open filename or saved filename }

procedure TfrmNotepad.OpenDialog;

begin

  FCount := 1;

  rzopdlgOpenDialog.Title := 'Open File';

  rzopdlgOpenDialog.Filter := 'Text Files|*.txt; RTF Files|*.rtf';

  if rzsvdlgSaveDialog.FileName = FFileName then

  begin

    if rzopdlgOpenDialog.Execute then

      memNotePad.Lines.LoadFromFile(rzopdlgOpenDialog.FileName);

  end

  { if any file already opened and without saving the file try to open new file
    then message dialog box appears on the screen for save the file or save modification of the file }

  else if (memNotePad.Modified) then

  begin

    ModalResult := MessageDlg('Do you want to save Changes to untitled?',mtConfirmation,mbYesNoCancel,0);
    if (ModalResult = mrYes) then
    begin
      if rzsvdlgSaveDialog.Execute then
        memNotepad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName + '.txt');
      memNotePad.Clear;
      memNotePad.Modified := False;
    end
    else if (ModalResult = mrNo) then
    begin
      if rzopdlgOpenDialog.Execute then
      begin
        memNotePad.Lines.LoadFromFile(rzopdlgOpenDialog.FileName);
        FFileName := rzopdlgOpenDialog.FileName;
      end;
    end;
  end

  else if rzopdlgOpenDialog.Execute then

  begin

    memNotePad.Lines.LoadFromFile(rzopdlgOpenDialog.FileName);
    FFileName := rzopdlgOpenDialog.FileName;
  end;
  Caption := rzopdlgOpenDialog.FileName + ' - Delphi Notepad';

end;

{ Saving the file }

procedure TfrmNotepad.SaveDialog;

begin

  rzsvdlgSaveDialog.Title := 'Save';

  rzsvdlgSaveDialog.Filter := 'Text Files|*.txt; RTF Files|*.rtf';

  { if file already exist and after modification we try to save then it directly save into the file without opening the save dialog box }

  if FCount = 1 then

  begin

    { filename store in the FFileName is compare with the save dialog box filename
      if it matches then modification dirctly save into that file without opening the save dialog box }

    if rzsvdlgSaveDialog.FileName = FFileName then

      memNotePad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName + '.txt')

    { filename store in the FFileName is compare with the open dialog box filename
      if it matches then modification dirctly save into that file without opening the save dialog box }

    else if rzopdlgOpenDialog.FileName = FFileName then

    begin

      rzsvdlgSaveDialog.FileName := rzopdlgOpenDialog.FileName;
      memNotePad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName);
    end;
  end

  { else file already not save then Save Dialog box open }

  else

  begin

    if rzsvdlgSaveDialog.Execute then
      memNotePad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName + '.txt');
    Caption := rzsvdlgSaveDialog.FileName + ' - Delphi Notepad';
    FCount := 1;
  end;
  FFileName := rzsvdlgSaveDialog.FileName;

end;

{ New Notepad }

procedure TfrmNotepad.NewNotepad;

begin

  if FCount = 1 then

  begin

    memNotePad.Clear;

    Caption := 'UnNamed Delphi Notepad';

  end

  else if not (memNotePad.Modified) then

  begin

    memNotePad.Clear;

    Caption := 'UnNamed Delphi Notepad';

  end

  { without saving the modification's of file if try to click on new then
    message dialog box appears on the screen for saving the modification's }

  else if (memNotePad.Modified) then

  begin

    ModalResult := MessageDlg('Do you want to save Changes',mtConfirmation,mbYesNoCancel,0);

    if (ModalResult = mrYes) then

    begin

      if rzsvdlgSaveDialog.Execute then
        memNotepad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName + '.txt');
      memNotePad.Clear;
      memNotePad.Modified := False;
    end
    else if (ModalResult = mrNo) then
    begin
      memNotePad.Clear;
      memNotePad.Modified := False;
    end;
  end;

  FFileName := rzsvdlgSaveDialog.FileName;

  FCount := 1;

end;

{ Save As }

procedure TfrmNotepad.SaveAS;

begin

  rzsvdlgSaveDialog.Title := 'Save As';

  rzsvdlgSaveDialog.Filter := 'Text Files|*.txt; RTF Files|*.rtf';

  if rzsvdlgSaveDialog.Execute then

    memNotepad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName + '.txt');

  memNotePad.Clear;

  memNotePad.Modified := False;

end;

{ Cut text }

procedure TfrmNotepad.Cut;

begin

  memNotePad.CutToClipboard;

end;

{ Copy text }

procedure TfrmNotepad.Copy;

begin

  memNotePad.CopyToClipboard;

end;

{ Paste }


procedure TfrmNotepad.Paste;

begin

  memNotePad.PasteFromClipboard;

end;

{ Font Dialog is assign to memo }

procedure TfrmNotepad.Font;

begin

  if ftdlgFontDialog.Execute then

    memNotePad.Font := ftdlgFontDialog.Font;

end;


{ Save the setting of font in to Ini file }

procedure TfrmNotepad.SaveSettingInToFile;

var

  LColorName : String;

begin

  FIniFile.WriteString('Setting', 'FontName', memNotePad.Font.Name);

  FIniFile.WriteString('Setting', 'FontSize', IntToStr(memNotePad.Font.Size));

  LColorName := ColorToString(memNotePad.Font.Color);

  FIniFile.WriteString('Setting', 'FontColor', LColorName);

end;


{ Retrieve the setting of font from Ini file }

procedure TfrmNotepad.RetrieveSettingFromTheFile;

var

  LFontName, LFontSize, LFontColor: String;

begin

  FIniFile := TIniFile.Create('FontSettings.ini');

  LFontName := FIniFile.ReadString('Setting', 'FontName', 'Arial');

  memNotePad.Font.Name := LFontName;

  LFontSize := FIniFile.ReadString('Setting', 'FontSize', '8');

  memNotePad.Font.Size := StrToInt(LFontSize);

  LFontColor := FIniFile.ReadString('Setting', 'FontColor', 
ColorToString(clBlack));

  memNotePad.Font.Color := StringToColor(LFonTColor);

  ftdlgFontDialog.Font := memNotePad.Font;

end;

procedure TfrmNotepad.mniOpenClick(Sender: TObject);

begin

  OpenDialog;

end;


procedure TfrmNotepad.mniSaveClick(Sender: TObject);

begin

  SaveDialog;

end;


procedure TfrmNotepad.mniNewClick(Sender: TObject);

begin

  NewNotepad;

end;


procedure TfrmNotepad.mniSaveAsClick(Sender: TObject);

begin

  SaveAS;

end;


{ Exit from Notepad }

procedure TfrmNotepad.mniExitClick(Sender: TObject);

begin

  { While exit if the modification in file is not save then then message dialog appear on the screen }

  if (memNotePad.Modified) then

  begin

    ModalResult := MessageDlg('Do you want to save 
Changes',mtConfirmation,mbYesNoCancel,0);

    if (ModalResult = mrYes) then

    begin

      if rzsvdlgSaveDialog.FileName = FFileName then

        memNotePad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName + '.txt')

      else if rzopdlgOpenDialog.FileName = FFileName then

      begin

        rzsvdlgSaveDialog.FileName := rzopdlgOpenDialog.FileName;

        memNotePad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName);

      end

      else if rzsvdlgSaveDialog.Execute then

        memNotepad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName + '.txt');

      memNotePad.Clear;

      memNotePad.Modified := False;

      Close;

    end

    else if (ModalResult = mrNo) then

    begin

      memNotePad.Clear;

      memNotePad.Modified := False;

      Close;

    end;

  end;

  { call method for saving the font setting into Ini file }

  SaveSettingInToFile;

end;

procedure TfrmNotepad.mniCutClick(Sender: TObject);

begin

  Cut;

end;


procedure TfrmNotepad.mniCopyClick(Sender: TObject);

begin

  Copy;

end;


procedure TfrmNotepad.mniPasteClick(Sender: TObject);

begin

  Paste;

end;


procedure TfrmNotepad.mniFontClick(Sender: TObject);
begin

  Font;

end;


procedure TfrmNotepad.FormCreate(Sender: TObject);

begin

  FCount := 0;

  FFileName := 'ok';

  { call method for retrieve the font setting from Ini file }

  RetrieveSettingFromTheFile;

end;


procedure TfrmNotepad.FormDestroy(Sender: TObject);

begin

  { call method for saving the font setting into Ini file }

  SaveSettingInToFile;

end;


{ when text is selected on notepad, only then the copy & cut are enabled else disabled }

procedure TfrmNotepad.mniEditClick(Sender: TObject);

begin

  mniCopy.Enabled := memNotePad.SelLength > 0;

  mniCut.Enabled := memNotePad.SelLength > 0;

end;


procedure TfrmNotepad.FormCloseQuery(Sender: TObject; var CanClose: Boolean);

begin

  { While Destroying the form if the modification in file is not save then then
    message dialog appear on the screen }

  rzsvdlgSaveDialog.Filter := 'Text Files|*.txt; RTF Files|*.rtf';

  if (memNotePad.Modified) then

  begin

    ModalResult := MessageDlg('Do you want to save 
Changes',mtConfirmation,mbYesNoCancel,0);
    if (ModalResult = mrYes) then

    begin

      if rzsvdlgSaveDialog.FileName = FFileName then

        memNotePad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName + '.txt')

      else if rzopdlgOpenDialog.FileName = FFileName then

      begin

        rzsvdlgSaveDialog.FileName := rzopdlgOpenDialog.FileName;

        memNotePad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName);

      end

      else if rzsvdlgSaveDialog.Execute then

        memNotepad.Lines.SaveToFile(rzsvdlgSaveDialog.FileName + '.txt');

      memNotePad.Clear;

      memNotePad.Modified := False;

    end

    else if (ModalResult = mrNo) then

    begin

      memNotePad.Clear;

      memNotePad.Modified := False;

    end;

  end;

  CanClose := True;

end;


end.
person Rahul Ghule    schedule 26.05.2017