I'm quite new to this things. Actually it is my first work. I want a program that reads random file count from textbox. and it has a button to randomize files from selected path. I need to open files in the listbox.
My problem is when I double click on the listbox, it opens the last file in the list no matter what file I d.clicked. I tried to add lines that put two slash before below. But it also didnt work. What can I do?
public Form1()
{
InitializeComponent();
}
Random r = new Random();
string path1;
DirectoryInfo dif;
FileInfo[] files;
int randomchoose;
//FileInfo[] files2;
//int hoho;
int[] randomcount;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog hoho = new FolderBrowserDialog();
hoho.ShowNewFolderButton = true;
if (hoho.ShowDialog() == DialogResult.OK)
{
path1 = hoho.SelectedPath;
textBox1.Text = path1;
dif = new DirectoryInfo(path1);
files = dif.GetFiles();
}
}
private void btnrasgele_Click(object sender, EventArgs e)
{
randomcount = new int[Convert.ToInt32(textBox3.Text)];
// int hoho=0;
foreach (int k in randomcount)
{
int pd = files.Length;
randomchoose = r.Next(0, Convert.ToInt32(pd + 1));
listBox1.Items.Add(files[randomchoose]);
//files2[hoho] = files[randomchoose].FullName;
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
//listBox1.SelectedIndex = hoho;
//Process.Start(files2[hoho].FullName);
Process.Start(files[randomchoose].FullName);
}
You passed in the randomchoose which is fixed at that point, try this instead:
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if(listBox1.SelectedItem != null)
Process.Start(((FileInfo)listBox1.SelectedItem).FullName);
}
Related
I am new to c# and I know the answer is very simple I just could not find it through searching
I created two buttons the first one generates random values
and the second one is an IF statement inside another button, but I`m getting a red line under 1value1 saying
the name does not exists in current context
private void button3_Click(object sender, EventArgs e)
{
Random b = new Random();
float value = b.Next(50, 100);
}
private void button2_Click(object sender, EventArgs e)
{
if (value < MinValue)
{
textBox18.Text = ("warning");
textBox18.ForeColor = Color.White;
textBox18.BackColor = Color.Red;
}
}
value is defined in the scope of the button3_Click and thus not accessible for the button2_Click. Put it as a variable of the class:
private int _minValue = 50;
private int _maxValue = 100;
private float _value = _maxValue;
private void button3_Click(object sender, EventArgs e)
{
Random b = new Random();
_value = b.Next(_minValue, _maxValue);
}
private void button2_Click(object sender, EventArgs e)
{
if (_value < _minValue)
{
textBox18.Text = ("warning");
textBox18.ForeColor = Color.White;
textBox18.BackColor = Color.Red;
}
}
Set property GenerateMember=True
I've created a program to make bug templates and am having a problem with text not saving correctly.
I have a text file called TemplateTexts that holds all the text for each template, a template looks like this -
REQUIREMENTS
- Example
ADDITIONAL REQUIREMENTS
- Example
- Example
-----COPY BELOW THIS LINE-----
When the program closes it copies all of that into 1 line of a text file. (looks like this)
REQUIREMENTS- Example ADDITIONAL REQUIREMENTS- Example - Example-----COPY BELOW THIS LINE-----
The text file contains 20 lines of templates. The template is saved as 1 line of text into the text file, but when I go to open the program again, it turns that 1 line of text into multiple lines of text like how it is displayed in the first example.
Any idea why this might be happening? or is there a better way to save each template into a text file, possibly by separating it with flags or something?
Here's the code to my program:
public partial class Form1 : Form
{
static String buttonNamesPath = AppDomain.CurrentDomain.BaseDirectory + "/ButtonNames.txt";
String[] ButtonNames = System.IO.File.ReadAllLines(buttonNamesPath);
static String buttonTextPath = AppDomain.CurrentDomain.BaseDirectory + "/ButtonText.txt";
String[] ButtonText = System.IO.File.ReadAllLines(buttonTextPath);
private void SetupTextField()
{
comboBox1.Items.Clear();
comboBox2.Items.Clear();
for (int i = 0; i < ButtonNames.Length; i++)
{
comboBox1.Items.Insert(i, ButtonNames[i]);
comboBox2.Items.Insert(i, ButtonNames[i]);
}
}
public Form1()
{
InitializeComponent();
this.FormClosing += this.Form1_FormClosing;
}
private void Form1_Load(object sender, EventArgs e)
{
SetupTextField();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string comboBoxText;
comboBoxText = comboBox1.SelectedItem.ToString();
int strNumber;
int strIndex = 0;
for (strNumber = 0; strNumber < ButtonNames.Length; strNumber++)
{
strIndex = Array.FindIndex(ButtonNames, x => x.Contains(comboBoxText));
if (strIndex >= 0)
break;
}
ButtonNames[strIndex] = textBox1.Text;
ButtonText[strIndex] = richTextBox2.Text;
SetupTextField();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
System.IO.File.WriteAllLines(buttonNamesPath, ButtonNames);
System.IO.File.WriteAllLines(buttonTextPath, ButtonText);
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
string comboBoxText;
comboBoxText = comboBox2.SelectedItem.ToString();
int strNumber;
int strIndex = 0;
for (strNumber = 0; strNumber < ButtonNames.Length; strNumber++)
{
strIndex = Array.FindIndex(ButtonNames, x => x.Contains(comboBoxText));
if (strIndex >= 0)
break;
}
richTextBox1.Text = ButtonText[strIndex];
}
private void label3_Click(object sender, EventArgs e)
{
}
}
I also have 2 text files called ButtonNames.txt and ButtonText.txt
When you ask the RichTextBox for its Text property, it converts the rich text it contains internally to a plain-text string, and apparently by default it uses \n to translate line endings. Notepad doesn't recognize \n as a line ending (because it's looking for the official Windows line ending of \r\n), so it displays everything on one line. If you want to save with \r\n for line endings, use string.Replace on the result of RichTextBox.Text to replace \n with \r\n.
See this question and its answers for more details:
RichTextBox Newline Conversion?
I am trying to navigate page, using different useragents. I have a random string generator, a timer that changes it every second (generate new random string every second), and a navigate. My question is, how to use string useragent (which is being changed every second) in another void ?
public static string RandomString(Random r)
{
string s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var sb = new StringBuilder();
int cnt = r.Next(5, 33);
for (int i = 1; i <= cnt; i++)
{
int idx = r.Next(0, s.Length);
sb.Append(s.Substring(idx, 1));
}
return sb.ToString();
}
private void timer2_Tick(object sender, EventArgs e)
{
var r = new Random();
string useragent = RandomString(r);
timer2.Stop();
timer2.Interval = 1;
timer2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
Navigate("http://example.org",useragent,null);
}
You can use useragent in global scope
private string useragent = string.Empty;
private void timer2_Tick(object sender, EventArgs e)
{
var r = new Random();
useragent = RandomString(r);
timer2.Stop();
timer2.Interval = 1;
timer2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(useragent))
return;
Navigate("http://example.org", useragent, null);
}
EDIT:
You should generate the string only when it is needed while navigating, so use this
private Random r = new Random();
private void timer1_Tick(object sender, EventArgs e)
{
Navigate("http://example.org", RandomString(r), null);
}
I am trying to make a simple app that grabs all *.jpg files from a folder, and displays them in PictureBox.
However i'm trying to make Prev/Next buttons to show images one by one. Here's my code for the Next button so far:
string path = #"..\..\Resources\Wallpapers\";
int count = 0;
private void Form1_Load(object sender, EventArgs e)
{
DisplayNextFile(count);
}
private void next_Click(object sender, EventArgs e)
{
DisplayNextFile(count);
}
private void DisplayNextFile(int c)
{
var rand = new Random();
var files = Directory.GetFiles(path, "*.jpg");
var images = new Image[files.Length];
for (int i = c; i < files.Length; ++i)
{
images[i] = Image.FromFile(files[i]);
picBoxMainPreview.Image = images[i];
break;
}
count++;
if (count == files.Length)
count = 0;
}
It works fine, but how can I do it for the Previous button?
Remove count++; from DisplayNextFile.
private void next_Click(object sender, EventArgs e)
{
count = (++count) % files.Length;
DisplayNextFile(count);
}
private void previous_Click(object sender, EventArgs e)
{
count = (count - 1) >= 0 ? count - 1 ? files.Length - 1;
DisplayNextFile(count);
}
Replace the for loop with:
picBoxMainPreview.Image = Image.FromFile(c);
I'm trying to make a slideshow with a mediaElement that shows each image in listbox x seconds.
How do I make my code play each image x seconds before continuing?
This code adds all images to a listbox named Listbox1
Dictionary<string, string> Listbox1Dict = new Dictionary<string, string>();
private void SearchBtn_Click(object sender, RoutedEventArgs e)
{
Listbox1.Items.Clear();
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.SelectedPath = "C:\\";
DialogResult result = folderDialog.ShowDialog();
if (result.ToString() == "OK")
FileNameTextBox.Text = folderDialog.SelectedPath;
string directory = FileNameTextBox.Text;
var files = Directory.GetFiles(directory).Where(name => !name.EndsWith(".ini"));
foreach (string file in files)
{
Listbox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file));
Listbox1Dict.Add(System.IO.Path.GetFileNameWithoutExtension(file), file);
}
}
This code shows all images in fullscreen but it skips everyone to last image at start.
private void button1_Click_1(object sender, RoutedEventArgs e)
{
foreach (var selected in Listbox1.Items)
{
string s = selected.ToString();
if (Listbox1Dict.ContainsKey(s))
{
mediaElement1.Visibility = Visibility.Visible;
SearchBtn.Visibility = Visibility.Hidden;
Listbox1.Visibility = Visibility.Hidden;
FileNameTextBox.Visibility = Visibility.Hidden;
mediaElement1.Source = new Uri(Listbox1Dict[s]);
mediaElement1.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
mediaElement1.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Background = new SolidColorBrush(Colors.Black);
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
}
}
}
Tried this code to make the image play one by one but I get an error. Look on comment on code:
private int currentSongIndex = -1;
void mediaElement1next(object sender, EventArgs e)
{
if(currentSongIndex == -1)
{
currentSongIndex = Listbox1.SelectedIndex;
}
currentSongIndex++;
if(currentSongIndex < Listbox1.Items.Count)
{
mediaElement1.Play(Listbox1.Items[currentSongIndex]); // No overload for method 'Play' takes 1 arguments
}
else
{
// last song in listbox has been played
}
}
I think you need a timer to set your next image. Using the code you're currently using, it will iterate through your list and change the image until you get to the end.
Take a look at DispatcherTimer. You could set it so, at each tick, it would change to the next image. Something like this (just writing off my head)
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
Then, inside your eventhandler:
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// get the next image
}
Of course you can use other kinds of timers, but that's the main idea.
Hold your image paths in a list & use the tick event of a timer.
Something like:
List<string> paths = new List<string>();
private void timer1_Tick(object sender, EventArgs e)
{
pictureBox1.Image = getNextImage();
}
private string getNextImage()
{
//code...
}
enter code here
EDIT:
Add a class variable: int index = 0;
On the SearchBtn_Click event, add the results to the list.
//..
foreach (string file in files)
{
paths.Add(file);
}
//..
Then do as I did above and the content of the getNextImage method would be:
private string getNextImage()
{
if(index < paths.Count - 1)
{
index += 1;
}
else
{
index = 0;
}
return paths[index];
}
My idea would be to implement a thread that counted to X and then called a NextImage() function when done.
Something like this:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Listbox1.Items.Count > 0)
{
if (dispatcherTimer.IsEnabled)
dispatcherTimer.Stop();
else
{
curImage = 0;
dispatcherTimer.Start();
}
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
Dispatcher.Invoke((Action)delegate
{
ShowNextImage();
}, null);
}
private void ShowNextImage()
{
if (curImage >= Listbox1.Items.Count)
curImage = 0;
var selected = Listbox1.Items[curImage];
string s = selected.ToString();
if (Listbox1Dict.ContainsKey(s))
{
mediaElement1.Visibility = Visibility.Visible;
SearchBtn.Visibility = Visibility.Hidden;
Listbox1.Visibility = Visibility.Hidden;
FileNameTextBox.Visibility = Visibility.Hidden;
mediaElement1.Source = new Uri(Listbox1Dict[s]);
mediaElement1.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
mediaElement1.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
this.Background = new SolidColorBrush(Colors.Black);
this.WindowStyle = WindowStyle.None;
this.WindowState = WindowState.Maximized;
}
}
and declaration
DispatcherTimer dispatcherTimer = new DispatcherTimer();
int x = 2; //seconds
private int curImage = 0;
and some construct
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, x);