C# apply a different file to the same variable - c#

I am trying to create a series of buttons, each play a sound. This sound is retrieved from an OpenFileDialog function. However, I have encountered the issue of one sound being assigned to all of the buttons. I know why this occurring, but I am unsure of how to resolve the issue. Basically, I began by assigning the same algorithms to each button:
openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileName = openFileDialog.FileName;
}
And:
soundPlayer = new SoundPlayer(fileName);
soundPlayer.Play();
Unfortunately, this was extremely ugly and so I decided to put each algorithm in to a method and just call the methods to their respective buttons. Like so:
public void openDialog()
{
openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileName = openFileDialog.FileName;
}
}
private void button27_Click(object sender, EventArgs e)
{
openDialog();
}
public void playDialog()
{
soundPlayer = new SoundPlayer(fileName);
soundPlayer.Play();
}
private void button1_Click(object sender, EventArgs e)
{
playDialog();
}
However, because openDialog() calls the same variable which receives the file name, each of the buttons calling openDialog() is using the same variable and so playing the same sound.

You have to make the fileName "part" of the Button. You can do it by either:
Using the Tag property of a button and cast to string when retrieving
Create a subclass of a Button called SoundButton and add FileName property of type string
Make a pick.
For example, using a Tag:
public void playDialog(string fileName)
{
soundPlayer = new SoundPlayer(fileName);
soundPlayer.Play();
}
private void button1_Click(object sender, EventArgs e)
{
playDialog((sender as Button).Tag as string);
}

You can make a list of sounds and then play it in a loop one by one:
Creating the list:
List<string> soundsList = new List<string>();
Adding to the list:
sounds.Add(openFileDialog.FileName);
Playing sounds:
foreach(string sound in soundsList)
{
soundPlayer = new SoundPlayer(sound);
soundPlayer.Play();
}
My answer of course is assuming you keep an order of first adding all the sounds you want and then playing them all. You should of course also need to add validation to check that the user has given you a correct sound to add to the list.
EDIT:
After reading your comment, you can also add a sound to Tag property of the button. Then when you want to play a sound of a specific button, you can just play whatever is inside that property of the button.
For example you can override the Click event like this:
private void button_Click(object sender, EventArgs e)
{
string soundFile = (sender as Button).Tag as string;
playDialog(soundFile);
}
This way all sounds are a "part" of the button

Related

openFileDialog_FileOK is never called in C#

I want to print the name of the selected file on label1 when the FileDialog closes successfully using the openFileDialog_FileOk in C#, but the openFileDialog_FileOK is never called.
Sorry for bad English.
namespace Graph_Win_Forms
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
label1.Text = "Dosya: " + openFileDialog1.FileName;
}
}
}
I tried delete code and WinForms Element but it didn't work
I suspect that you have copied that code from an online sample somewhere and you have ignored the fact that, if you expect that method to be invoked when an event is raised, you need to register it as an event handler. The most immediate option would be this:
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.FileOk += openFileDialog1_FileOk;
openFileDialog1.ShowDialog();
What was likely done in the first place was that an OpenFileDialog was added to the form in the designer and then the event handler generated in the designer. You could do that too, instead of creating the OpenFileDialog in code. If you do that, you can select an existing method in the designer rather than creating a new one.
Having said that, I would normally not handle that event anyway. If you're displaying one or more dialogues in different places and you want to write the code to execute on OK in one place then it makes sense to handle that event. It would also make sense if the event handler was in a different code file to the code that shows the dialogue. If you are only display the dialogue in one place though, I'd probably just check the result of ShowDialog and act on OK.
simple way to use below code.
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
if (openfiledialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
label1.Text = "Dosya: " + openfiledialog1.FileName;
}
}
if you are using the toolbox you have to declare your event 'openFileDialog1_FileOK' in property->Event->FileOk and remove the initialization of the OpenFileDialog instance because the design mode does it automatically.
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
label1.Text = "Dosya: " + openFileDialog1.FileName;
}

creating media player button from user control in main form c#

I want to play media player in main form, from user control that media player is in there. How can C call media player with buttons that I put them in main form?
private void player1_Load(object sender, EventArgs e)
{
}
private void bunifuImageButton7_Click(object sender, EventArgs e)
{
}
private void bunifuImageButton1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.bunifuMaterialTextbox1.Text = ofd.FileName;
}
}
}
Presumably, you have added a media player object to your form, and it's the COM object, axWindowsMediaPlayer (from your tags). Let's assume it has the default name of axWindowsMediaPlayer1.
I am also assuming that your bunifuImageButton7 is the Play button.
You need to load the path of your media file into the mediaplayer's URL property, and then activate its Play control, like this:
private void bunifuImageButton7_Click(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = bunifuMaterialTextbox1.Text;
axWindowsMediaPlayer1.Ctlcontrols.play();
}
This was easily found on the Microsoft site. You might want to visit their site and bookmark it, as it contains everything you need to know about the media player:
https://learn.microsoft.com/en-us/windows/desktop/wmp/axwindowsmediaplayer-object--vb-and-c
Documentation for all the other player controls is here:
https://learn.microsoft.com/en-us/windows/desktop/wmp/iwmpcontrols--vb-and-c

Edit Items in a ListBox

I am creating a program using WinForms so users can input info into textboxes on one form which then are saved into a Listbox on another form. I would like to be able to edit the items saved in the listbox by opening the original form on a button click. Really struggling with it as I can't think of the code and I can't seem to find a solution.
My Code:
private void btnAdd_Click(object sender, EventArgs e)
{
RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
newRoomDisplayForm.ShowDialog();
if(newRoomDisplayForm.DialogResult == DialogResult.OK)
{
listBoxRooms.Items.Add(newRoomDisplayForm.value);
}
newRoomDisplayForm.Close();
}
private void btnRemove_Click(object sender, EventArgs e)
{
this.listBoxRooms.Items.RemoveAt(this.listBoxRooms.SelectedIndex);
}
private void btnEdit_Click(object sender, EventArgs e)
{
}
So i've got a Add and Remove button which work perfectly just need a solution to the edit button.
Thanks in advance
I'm guessing newRoomDisplayForm.value is a property or a public member inside the form. You just need to do something like this:
private void btnEdit_Click(object sender, EventArgs e)
{
if(listBoxRooms.SelectedIndex < 0) return;
var tmpValue = listBoxRooms.Items[listBoxRooms.SelectedIndex].ToString();
RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
newRoomDisplayForm.value = tmpValue;
newRoomDisplayForm.ShowDialog();
//TODO: inside "newRoomDisplayForm" set the value to the textbox
// ie.: myValueTextBox.Text = this.value;
if(newRoomDisplayForm.DialogResult == DialogResult.OK)
{
// replace the selected item with the new value
listBoxRooms.Items[listBoxRooms.SelectedIndex] = newRoomDisplayForm.value;
}
}
Hope it helps!
You can simply remove the listitem in that specific position, create a new item and add it again. it's kind of replacement.

playing and stopping audio from two different buttons

I'm running this code for pausing the song but it obliviously doesn't work.
I can't access the variables of the first button from the second one, so I can't pause the song.
How do you think I could do that?
I'm using the naudio library cause I wanted to put the audio file as resource.
private void button3_Click(object sender, EventArgs e)
{
MemoryStream mp3file = new MemoryStream(Properties.Resources.musica1);
Mp3FileReader mp3reader = new Mp3FileReader(mp3file);
var waveOut = new WaveOut();
waveOut.Init(mp3reader);
waveOut.Play();
if (pausa)
{
waveOut.Pause();
}
}
private void button2_Click(object sender, EventArgs e)
{
pausa = true;
}
You will need to restructure your code. The problem is that in your button3_Click method, you are loading and playing your MP3, but then the function immediately terminates. The if statement won't be continuously checked, which is what I think you assume will happen. Therefore, clicking button2 will simply change the state of pausa but this doesn't affect anything.
One way would be to make all the variables (mp3file, mp3reader, and waveOut) declared at the class level, then put the rest of the code inside button3_Click into, say, your form's Load event handler.
// These variables are declared at the class level
MemoryStream mp3file;
Mp3FileReader mp3reader;
WaveOut waveOut;
...
private void Form1_Load(object sender, EventArgs e)
{
mp3file = new MemoryStream(Properties.Resources.musica1);
mp3reader = new Mp3FileReader(mp3file);
waveOut = new WaveOut();
waveOut.Init(mp3reader);
}
Now, your buttonX_Click functions can look like this (assuming button3 is your Play button and button2 is your Pause button):
private void button3_Click(object sender, EventArgs e)
{
waveOut.Play();
}
private void button2_Click(object sender, EventArgs e)
{
waveOut.Pause();
}
Because waveOut is declared at the class level, both buttons have access to it, and can therefore play and pause at will. You don't need pausa anymore, unless of course you need to know the playing state elsewhere in the program.

Filepath and textboxes

Ok I am going to try this again. I got more information now. I understand I can not use open and save dialogs and there is no database. So I am still kinda lost cause I was shown how to do it with open and save dialogs before. I am going to put what I am suppose to do and then so far the code I have. The code I have I have to build off and add too. I will also show what I am suppose to add to it. I am just trying to find the best way to understand this cause right now I am not. I am still new and I know the last couple days people have been trying to help me understand and then I was told it wasnt with the open and save dialog. Here is what I am suppose to do.
•Add a textbox named txtFilePath <--- already have that
•Add a button next to the above textbox that says “Load” (name it appropriately)<-already have that
•Add a button that says “Save” (name it appropriately) <-- already have this
•When thebutton “Load” is clicked, read the file specified in the textbox
(txtFilePath: Absolute path not relative) and add the objects found
within to the listbox<--- Not understanding
•When the user clicks the “Save” button, write the selected record to
the file specified in txtFilePath (absolute path not relative) without
truncating the values currently inside<-- not understanding
Here is the one part of code I have:`
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
EditDialog newEmployeeDialog = new EditDialog();
if (newEmployeeDialog.ShowDialog() == DialogResult.OK)
{
employeeList.Items.Add(newEmployeeDialog.StaffMember);
}
}
private void deleteButton_Click(object sender, EventArgs e)
{
if (employeeList.SelectedIndex == -1)
return;
if (MessageBox.Show("Really delete this employee",
"Delete", MessageBoxButtons.YesNo,
MessageBoxIcon.Question)
== DialogResult.Yes)
{
employeeList.Items.Remove(
employeeList.SelectedItem);
}
}
private void editButton_Click(object sender, EventArgs e)
{
if (employeeList.SelectedIndex == -1)
return;
int employeeNum = employeeList.SelectedIndex;
EditDialog newEmployeeDialog = new EditDialog();
newEmployeeDialog.StaffMember =
(Employee)employeeList.SelectedItem;
if (newEmployeeDialog.ShowDialog() == DialogResult.OK)
{
employeeList.Items.RemoveAt(employeeNum);
employeeList.Items.Insert(employeeNum, newEmployeeDialog.StaffMember);
employeeList.SelectedIndex = employeeNum;
}
}
private void employeeList_SelectedIndexChanged(object sender, EventArgs e)
{
if (employeeList.SelectedIndex != -1)
{
Employee currentEmployee = (Employee)employeeList.SelectedItem;
firstName.Text = currentEmployee.FirstName;
lastName.Text = currentEmployee.LastName;
jobTitle.Text = currentEmployee.JobTitle;
}
else
{
firstName.Text = lastName.Text = jobTitle.Text = "";
}
}
`
Now I know you can not see the button click but I do have them mark. I know when you use open and save how it works. How I can go about this? I would use stream writer right.I understand that the user will type the path into the textbox and when the user hits load, it will load the file that they are specified. Now I am just trying to understand a code to be able to word this right.
would it be something like this:
String filePath = this.txtFilePath.Text;
since I need to name the textbox txtFilePath. I know some of you might say this is simple but when you are first learning it don't seem that simple. I have been trying something to help me understand since I do my college from home. Thank you for reading hoping to hear from you guys.
Update: Would it be something like this
Reading a file
private void Load_Click(object sender, EventArgs e)
{
StreamReader myReader = new StreamReader(C:\\")
txtFilePath.Text = my reader.read to end();
myReader.Close();
}
then there is writing a file
{
StreamWriter myWriter = new StreamWriter("C:\\test.txt", true);
myWriter.Write("Some text");
myWriter.WriteLine("Write a line");
myWriter.WriteLine("Line 2");
myWriter.Close();
}
If this is correct then I have to get it where if the file is not there for the notepad to pop up so they can add it then they can save it without deleting anything out the file or files.
Assuming the file contains a list of employee names, you should be able to load them into your listbox using something like this:
var filepath = txtFilePath.Text;
if (File.Exists(filepath))
{
var lines = File.ReadAllLines(filepath);
foreach (var line in lines)
employeeList.Items.Add(line);
}
Then assuming you want to add a new employee name to the file that the user just entered into the listbox:
var filepath = txtFilePath.Text;
if (File.Exists(filepath))
using (var sw = File.AppendText(filepath))
sw.WriteLine((string)employeeList.Text);
else
using (var sw = File.CreateText(filepath))
sw.WriteLine((string)employeeList.Text);
This hasn't been tested, but it should work nearly as-is...

Categories

Resources