drevet
drevet

Reputation: 51

delphi hitting enter

How can I make an edit box so that when I hit enter with the cursor still in it. Then it goes to that website in the webbrowser which was in the edit box?

can anyone help me?

Upvotes: 5

Views: 30514

Answers (2)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 108948

Drop a TEdit and a TWebBrowser on the form, and write an event handler to the edit control, namely OnKeyDown:

procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  case Key of
    VK_RETURN:
      WebBrowser1.Navigate(Edit1.Text);
  end;
end;

To make it slightly more elegant, I would suggest

procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  case Key of
    VK_RETURN:
      begin
        WebBrowser1.Navigate(Edit1.Text);
        Edit1.SelectAll;
      end;
  end;
end;

Update

If you rather would like the URL to open in the system's default browser, and not in a TWebBrowser on your form, replace WebBrowser1.Navigate(Edit1.Text) with

ShellExecute(0, nil, PChar(Edit1.Text), nil, nil, SW_SHOWNORMAL);

after you have added ShellAPI to your uses clause. But notice now that you have to be explicit with the protocol. For instance, bbc.co.uk won't work, but http://bbc.co.uk will.

Upvotes: 6

Remy Lebeau
Remy Lebeau

Reputation: 595827

You should use the OnKeyPress event instead of the OnKeyDown event:

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
  if ord(Key) = VK_RETURN then
  begin
    Key := #0; // prevent beeping
    WebBrowser1.Navigate(Edit1.Text);
  end;
end; 

Upvotes: 21

Related Questions