我正在使这个程序“填充”某个目录。但问题是,当我勾选“自动隐藏”时,它会在大约30-40秒后重新出现。
还有其他方法,因为我们真的很感激。谢谢:))
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Drive_Filler
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.Text = "H:/";
}
public bool isRunning = true;
public string current;
string[] alpha = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
private void button1_Click(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
{
this.Opacity = 0;
this.ShowInTaskbar = false;
}
createnew(textBox1.Text);
}
public void createnew(string dir)
{
while (isRunning)
{
Random rnd = new Random();
current = alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)];
System.IO.Directory.CreateDirectory(dir + current);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:1)
表格重新出现,因为它没有反应。此外,您的代码中存在许多问题,我也无法理解您的目的。
首先, createnew 具有无限循环。它将在UI线程中运行,导致您的表单显示为警告用户无响应状态的标志。而且, rnd 应该只声明一次。随机的C#(和许多其他语言)使用时间相关的默认种子值。换句话说,两个Random实例几乎同时初始化,两个Random的值数组都是相同的。
所以我建议将 Random rnd 创建为 Form1 的一个字段,然后使用Task,BackgroundWorker,ThreadPool或其他任何东西将循环放在另一个线程中。
Task.Run(() =>
{
while (isRunning)
{
current = alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)];
System.IO.Directory.CreateDirectory(dir + current);
}
}
);