用delphi xe 实现一个用户登录的窗体
时间: 2024-05-14 09:17:37 浏览: 19
好的,以下是一个简单的用户登录窗体的 Delphi 代码示例:
```
unit LoginForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TLoginForm = class(TForm)
UsernameLabel: TLabel;
PasswordLabel: TLabel;
UsernameEdit: TEdit;
PasswordEdit: TEdit;
LoginButton: TButton;
CancelButton: TButton;
procedure LoginButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
LoginForm: TLoginForm;
implementation
{$R *.dfm}
procedure TLoginForm.CancelButtonClick(Sender: TObject);
begin
// 关闭窗体,不执行登录操作
Close;
end;
procedure TLoginForm.LoginButtonClick(Sender: TObject);
begin
// 判断用户名和密码是否正确
if (UsernameEdit.Text = 'admin') and (PasswordEdit.Text = '123456') then
begin
// 登录成功,关闭窗体并返回 ModalResult = mrOk
ModalResult := mrOk;
Close;
end
else
begin
// 登录失败,清空密码框并提示用户重新输入
PasswordEdit.Clear;
MessageDlg('用户名或密码错误,请重新输入!', mtError, [mbOK], 0);
end;
end;
end.
```
上述代码中,我们创建了一个名为 `TLoginForm` 的窗体类,其中包含了用户名和密码的标签、编辑框,以及登录和取消按钮。在单击登录按钮时,我们判断用户输入的用户名和密码是否正确,如果正确,我们将窗体的 `ModalResult` 属性设置为 `mrOk`,表示登录成功,否则清空密码框并提示用户重新输入。
我们可以在主程序中创建一个 `TLoginForm` 的实例并使用 `ShowModal` 方法显示它,当窗体返回 `mrOk` 时,表示用户已经成功登录,我们可以在主程序中执行相应的操作,例如显示主界面或者执行某些数据查询操作等。以下是一个简单的主程序示例:
```
program LoginDemo;
uses
Vcl.Forms, LoginForm in 'LoginForm.pas' {LoginForm};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TLoginForm, LoginForm);
if LoginForm.ShowModal = mrOk then
begin
// TODO: 登录成功,执行相应的操作
end;
Application.Run;
end.
```
在主程序中,我们首先创建了 `TLoginForm` 的一个实例 `LoginForm`,并使用 `ShowModal` 方法显示它。当窗体返回 `mrOk` 时,表示用户已经成功登录,我们可以在主程序中执行相应的操作。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)