我已经在Visual Studio中创建了一个GUI,其中有两个按钮。一个按钮用于显示ip,第二个按钮用于获取该IP并运行python脚本。
但是我想将这两个操作合并为一个按钮,如果第一次单击应显示/获取ip,而第二次单击则应触发Python脚本以及单击所有按钮即可。
我的代码是:
private void button1_Click(object sender, EventArgs e)
{
var fileName = "C:\\test.txt";
var sr = new StreamReader(fileName);
string fileContent = sr.ReadToEnd();
var startBlock = "hello";
var endBlock = "exit";
var ip = ParseForIpRegex(fileContent, startBlock, endBlock);
myTextBox.Text = ip; //Change this to match your code
}
private readonly string IPV4_PATTERN = "[0-9.]";
private string ParseForIpRegex(string textToSearch, string startBlock, string endBlock)
{
var pattern = $@"{startBlock}\D*\s*({IPV4_PATTERN}+).*{endBlock}";
var ms = Regex.Match(textToSearch, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (ms.Groups.Count > 0)
{
return ms.Groups[1].Value;
}
return string.Empty;
}
private void button1_Click_1(object sender, EventArgs e)
{
var hostname = myTextBox.Text;
var username = textBox1.Text;
var password = textBox2.Text;
var psi = new ProcessStartInfo();
psi.FileName = @"C:\Python38\python.exe";
var script = @"C:pythonscript.py";
//var config_file = file_path;
psi.Arguments = $"{script} {hostname} {username} {password}";
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
var errors = "";
var results = "";
MessageBox.Show("script processing");
using (var process = Process.Start(psi))
{
errors = process.StandardError.ReadToEnd();
results = process.StandardOutput.ReadToEnd();
}
Console.WriteLine("ERRORS:");
Console.WriteLine(errors);
Console.WriteLine();
Console.WriteLine("Results:");
Console.WriteLine(results);
if (errors != "")
{
MessageBox.Show(errors);
}
else
{
MessageBox.Show(results);
}
}
[请让我知道如何将这两个操作合并为一个。一键单击将执行第一个按钮操作,而第二个单击后将执行。
我想您需要保留所有按钮,因此您不使用args,只需调用该方法:
private void button1_Click(object sender, EventArgs e)
{
//DO job
// simulate the second click
button1_Click_1(sender, e)
}
private void button1_Click_1(object sender, EventArgs e)
{
//you could test args to check if its coming from first button
}
法语的答案,或者您可以在活动中添加2个句柄...根据您的喜好。
this.button1.Click += new System.EventHandler(this.button1_Click);
this.button1.Click += new System.EventHandler(this.button1_Click_1);
请注意,设计师会为您添加两个。因此,在form_load事件中添加第二个事件(或在您认为合适的地方)
欢呼声
您只需要定义一个布尔值即可检查它是否是第一次单击。
bool thefirst = true;
private void button1_Click(object sender, EventArgs e)
{
if (thefirst)
{
// show/take the ip
Console.WriteLine("First");
thefirst = false;
}
else
{
// run Python script
Console.WriteLine("Second");
}
}