当事件TextChanged中的代码在事件TextBoxURL_KeyDown中时,它也可以使用我想要的逻辑。但后来我不得不按下回车键,所以我把它移到TextChanged事件但现在当我在TextBoxUrl中输入有效时没有任何反应。
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DownloadMultipleFiles
{
public partial class AddNewDownloads : Form
{
public AddNewDownloads()
{
InitializeComponent();
foreach (Control ctrl in this.Controls)
{
if ((ctrl as TextBox) != null)
{
(ctrl as TextBox).TextChanged += TextChanged;
}
}
this.TextBoxURL.KeyDown += new KeyEventHandler(TextBoxURL_KeyDown); //add keyDown event
if (TextBoxFilename.Text == "" || TextBoxBrowse.Text == "")
{
TextBoxFilename.Enabled = false;
TextBoxBrowse.Enabled = false;
btnOK.Enabled = false;
}
}
private void AddNewDownloads_Load(object sender, EventArgs e)
{
}
private void btnBrowse_Click(object sender, EventArgs e)
{
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnOK_Click(object sender, EventArgs e)
{
}
private void TextBoxURL_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter) //validate the URL when you press the Enter key
{
}
}
private bool CheckValidUrl() // validate from clipboard
{
string isUrl = Clipboard.GetText();
Uri uriResult;
bool result = Uri.TryCreate(isUrl, UriKind.Absolute, out uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
return result;
}
private bool WriteValidUrl() // validate manual input
{
string pattern2 = @"^http://www.[a-z].com$";
Match match = Regex.Match(TextBoxURL.Text, pattern2);
if (match.Success)
return true;
else
return false;
}
private new void TextChanged(object sender, EventArgs e)
{
if (CheckValidUrl() == true || WriteValidUrl() == true)
{
TextBoxFilename.Enabled = true;
TextBoxBrowse.Enabled = true;
btnOK.Enabled = true;
}
else
{
TextBoxFilename.Enabled = false;
TextBoxBrowse.Enabled = false;
btnOK.Enabled = false;
}
if (TextBoxURL.Text == "")
{
TextBoxFilename.Enabled = false;
TextBoxBrowse.Enabled = false;
btnOK.Enabled = false;
}
}
}
}
答案 0 :(得分:1)
TextChanged在退出文本框时触发。您可能正在寻找KeyDown或KeyUp或KeyPress - 可能是KeyUp,因为这将允许您在添加新角色后捕获文本框中的内容。