Change the selection in the ListBox - c#

I add audio files to the ListBox by clicking on the Button. Then OpenFileDialog (the code below) works. I use the added files ListBox to play (the code below). I click on button_play. There is a problem. When I click on the Button for sorting using listBox1.Sorted = true. After sorting, the audio file that should be played is not played. The audio file that was in this place before sorting is played. That is, if all songs had a number, then after sorting only the names were changed, but the numbers have not changed. And when you click button_play is played by the number.
private void button_add_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
label_load.Text = list_catalog.Items.Count.ToString();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
foreach (String file in openFileDialog1.FileNames)
{
if (list_catalog.Items.Contains(Vars.GetFileName(file)))
{
}
else
{
Vars.Files.Add(file);
list_catalog.Items.Add(Vars.GetFileName(file));
hello.Visible = false;
}
}
}
private void button_play_Click(object sender, EventArgs e)
{
string current = Vars.Files[list_catalog.SelectedIndex];
Vars.CurrentTrackNumber = list_catalog.SelectedIndex;
BassLike.Play(current, BassLike.Volume);
label_time1.Text = TimeSpan.FromSeconds(BassLike.GetPosOfStream(BassLike.Stream)).ToString();
label_time2.Text = TimeSpan.FromSeconds(BassLike.GetTimeOfStream(BassLike.Stream)).ToString();
xrewind.Maximum = BassLike.GetTimeOfStream(BassLike.Stream);
xrewind.Value = BassLike.GetPosOfStream(BassLike.Stream);
timer1.Enabled = true;
}

I think this will work...
string current = list_catalog.SelectedItem as string;
Vars.CurrentTrackNumber = Vars.Files.IndexOf(current);

Related

File being used by another process when using File.CopyTo method

This is the code for my windows form. The goal of the form is to be able to preview a pdf on the application and then chose a folder with a drop down that you would like to copy the file to (this is what a "house" refers to in the code). This is a little project for work to make it simpler to organize files that get sent to the company. The listBox works populating with all the pdfs and the preview window works as well (this is the axAcroPDF component). But when hitting the send button to copy the file it says the file is being used by another process.
public partial class Form1 : Form { public Form1() { InitializeComponent();
}
string selectedPDF = "";
string selectedHouse = "";
DirectoryInfo currentPDF;
private void button1_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "PDF Files(*.pdf) |*.pdf;";
openFileDialog1.ShowDialog();
if(openFileDialog1.FileName != null)
{
axAcroPDF1.LoadFile(openFileDialog1.FileName);
}
}
private void refreshBTN_Click(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\bkamide\Desktop\ExamplePDFS");
FileInfo[] smFiles = dinfo.GetFiles("*.pdf");
foreach (FileInfo fi in smFiles)
{
pdfList.Items.Add(Path.GetFileName(fi.Name));
}
}
private void pdfList_SelectedIndexChanged(object sender, EventArgs e)
{
string firstSelectedItem = pdfList.SelectedItem.ToString();
selectedPDF = firstSelectedItem;
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\bkamide\Desktop\ExamplePDFS\" + firstSelectedItem);
currentPDF = dinfo;
}
private void btnSend_Click(object sender, EventArgs e)
{
openFileDialog1.Reset();
axAcroPDF1.EndInit();
var sourceFile = new FileInfo(currentPDF.FullName);
var dest = Path.Combine(#"C:\Users\bkamide\Desktop\ExamplePDFS\", selectedHouse, sourceFile.FullName);
sourceFile.CopyTo(dest, true);
}
private void cbHouse_SelectedIndex(object sender, EventArgs e)
{
selectedHouse = cbHouse.SelectedIndex.ToString();
}
}
I tried in the send method to reset the openFileDialog and axAcroPDF (not sure if I did that right) to see if those were the processes that could be using the file. I also tried restarting my computer to make sure nothing in the background was using it as well. I also did try the using method but I was not quite sure how to implement it within this.

2 songs playing at the same time

I have a project I'm working on. music playing platform. i use windows media player for this but i have a problem. The music comes as a list from the database. There is a play button at the top of the lists. When I press the button, the music plays smoothly. but when I play another song, the other music doesn't stop and they both play at the same time. I need your help. I think the problem is caused by the following codes
private bool durum = false;
public void btn_koynat_Click(object sender, EventArgs e)
{
Form1 frm1 = (Form1)this.FindForm();
frm1.player = player;
if (durum == true)
{
durum = false;
frm1.sarkislider.Value = 0;
}
if (durum==false)
{
durum = true;
int sec = Convert.ToInt32(label_sec.Text);
frm1.btn_Oynat.Enabled = true;
frm1.durum = true;
player.URL = label_sarki.Text + ".MP3";
btn_koynat.BackgroundImage = Properties.Resources.sesacik;
frm1.btn_Oynat.BackgroundImage = Properties.Resources.durdurbutonu;
frm1.sarki_isim.Text = label_sarki.Text;
frm1.sarki_sanatci.Text = label_sanatci.Text;
frm1.label_timer2.Text = label3.Text;
frm1.sarkislider.Maximum = sec;
frm1.timer1.Enabled = true;
frm1.sarkislider.Value = 0;
player.controls.play();
}
}
You can use wplayer.playState to check if your player is running.
Here is a code example, which can avoid playing two songs at the same time.
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
private void button1_Click(object sender, EventArgs e)
{
if (wplayer.playState == WMPLib.WMPPlayState.wmppsPlaying)
{
wplayer.controls.stop();
wplayer.URL = comboBox1.SelectedItem.ToString();
wplayer.controls.play();
}
else
{
wplayer.URL = comboBox1.SelectedItem.ToString();
wplayer.controls.play();
}
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.Items.Add("1.mp3");
comboBox1.Items.Add("2.mp3");
comboBox1.Items.Add("3.mp3");
comboBox1.Items.Add("4.mp3");
comboBox1.Items.Add("5.mp3");
}
Note: I used combobox to store mp3 files. Based on my test, when I play a mp3 file and click button to play another mp3 file, the initial mp3 file was stopped and play another file.

How can i add links to wpf xmal design by run time code?

I can't figure out how the whole thing is built. Do i need to add each link by my self manually ? And if i have 100 links ?
This is a screenshot of what i see in the xmal file
But maybe i can add this links from the code it self ?
The code is long so i will not add it to here.
I got the project from here:
Background File Downloader
If i want to add to the downloader my own links ?
I see in the DownloaderDemo code this part that add the links:
// Get the contents of the rich text box
string rtbContents = new TextRange(rtbPaths.Document.ContentStart, rtbPaths.Document.ContentEnd).Text;
foreach (string line in rtbContents.Split('\n'))
{
String trimmedLine = line.Trim(' ', '\r');
if (trimmedLine.Length > 0)
{
// If the line is not empty, assume it's a valid url and add it to the files list
// Note: You could check if the url is valid before adding it, and probably should do this is a real application
downloader.Files.Add(new FileDownloader.FileInfo(trimmedLine));
}
}
But i don't understand what richTextBox ? I guess it's in the design in the DownloaderDemo.xaml
Still if i want to add my own links to download files ?
This is DownloaderDemo.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace FileDownloaderApp
{
/// <summary>Interaction logic for DownloaderDemo.xaml</summary>
public partial class DownloaderDemo : Window
{
// Creating a new instance of a FileDownloader
private FileDownloader downloader = new FileDownloader();
public DownloaderDemo()
{
InitializeComponent();
CommandBindings.Add(new CommandBinding(ApplicationCommands.Close,
new ExecutedRoutedEventHandler(delegate(object sender, ExecutedRoutedEventArgs args) { this.Close(); })));
downloader.StateChanged += new EventHandler(downloader_StateChanged);
downloader.CalculatingFileSize += new FileDownloader.CalculatingFileSizeEventHandler(downloader_CalculationFileSize);
downloader.ProgressChanged += new EventHandler(downloader_ProgressChanged);
downloader.FileDownloadAttempting += new EventHandler(downloader_FileDownloadAttempting);
downloader.FileDownloadStarted += new EventHandler(downloader_FileDownloadStarted);
downloader.Completed += new EventHandler(downloader_Completed);
downloader.CancelRequested += new EventHandler(downloader_CancelRequested);
downloader.DeletingFilesAfterCancel += new EventHandler(downloader_DeletingFilesAfterCancel);
downloader.Canceled += new EventHandler(downloader_Canceled);
}
public void DragWindow(object sender, MouseButtonEventArgs args)
{
DragMove();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.Height -= 30;
}
// A simple implementation of setting the directory path, adding files from a textbox and starting the download
private void btnStart_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.FolderBrowserDialog openFolderDialog = new System.Windows.Forms.FolderBrowserDialog();
if (openFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Set the path to the local directory where the files will be downloaded to
downloader.LocalDirectory = openFolderDialog.SelectedPath;
// Clear the current list of files (in case it's not the first download)
downloader.Files.Clear();
// Get the contents of the rich text box
string rtbContents = new TextRange(rtbPaths.Document.ContentStart, rtbPaths.Document.ContentEnd).Text;
foreach (string line in rtbContents.Split('\n'))
{
String trimmedLine = line.Trim(' ', '\r');
if (trimmedLine.Length > 0)
{
// If the line is not empty, assume it's a valid url and add it to the files list
// Note: You could check if the url is valid before adding it, and probably should do this is a real application
downloader.Files.Add(new FileDownloader.FileInfo(trimmedLine));
}
}
// Start the downloader
downloader.Start();
}
}
private void btnPause_Click(object sender, RoutedEventArgs e)
{
// Pause the downloader
downloader.Pause();
}
private void btnResume_Click(object sender, RoutedEventArgs e)
{
// Resume the downloader
downloader.Resume();
}
private void btnStop_Click(object sender, RoutedEventArgs e)
{
// Stop the downloader
// Note: This will not be instantantanious - the current requests need to be closed down, and the downloaded files need to be deleted
downloader.Stop();
}
// This event is fired every time the paused or busy state is changed, and used here to set the controls of the interface
// This makes it enuivalent to a void handling both downloader.IsBusyChanged and downloader.IsPausedChanged
private void downloader_StateChanged(object sender, EventArgs e)
{
// Setting the buttons
btnStart.IsEnabled = downloader.CanStart;
btnStop.IsEnabled = downloader.CanStop;
btnPause.IsEnabled = downloader.CanPause;
btnResume.IsEnabled = downloader.CanResume;
// Enabling or disabling the setting controls
rtbPaths.IsReadOnly = downloader.IsBusy;
cbUseProgress.IsEnabled = !downloader.IsBusy;
}
// Show the progress of file size calculation
// Note that these events will only occur when the total file size is calculated in advance, in other words when the SupportsProgress is set to true
private void downloader_CalculationFileSize(object sender, Int32 fileNr)
{
lblStatus.Content = String.Format("Calculating file sizes - file {0} of {1}", fileNr, downloader.Files.Count);
}
// Occurs every time of block of data has been downloaded, and can be used to display the progress with
// Note that you can also create a timer, and display the progress every certain interval
// Also note that the progress properties return a size in bytes, which is not really user friendly to display
// The FileDownloader class provides static functions to format these byte amounts to a more readible format, either in binary or decimal notation
private void downloader_ProgressChanged(object sender, EventArgs e)
{
pBarFileProgress.Value = downloader.CurrentFilePercentage();
lblFileProgress.Content = String.Format("Downloaded {0} of {1} ({2}%)", FileDownloader.FormatSizeBinary(downloader.CurrentFileProgress), FileDownloader.FormatSizeBinary(downloader.CurrentFileSize), downloader.CurrentFilePercentage()) + String.Format(" - {0}/s", FileDownloader.FormatSizeBinary(downloader.DownloadSpeed));
if (downloader.SupportsProgress)
{
pBarTotalProgress.Value = downloader.TotalPercentage();
lblTotalProgress.Content = String.Format("Downloaded {0} of {1} ({2}%)", FileDownloader.FormatSizeBinary(downloader.TotalProgress), FileDownloader.FormatSizeBinary(downloader.TotalSize), downloader.TotalPercentage());
}
}
// This will be shown when the request for the file is made, before the download starts (or fails)
private void downloader_FileDownloadAttempting(object sender, EventArgs e)
{
lblStatus.Content = String.Format("Preparing {0}", downloader.CurrentFile.Path);
}
// Display of the file info after the download started
private void downloader_FileDownloadStarted(object sender, EventArgs e)
{
lblStatus.Content = String.Format("Downloading {0}", downloader.CurrentFile.Path);
lblFileSize.Content = String.Format("File size: {0}", FileDownloader.FormatSizeBinary(downloader.CurrentFileSize));
lblSavingTo.Content = String.Format("Saving to {0}\\{1}", downloader.LocalDirectory, downloader.CurrentFile.Name);
}
// Display of a completion message, showing the amount of files that has been downloaded.
// Note, this does not hold into account any possible failed file downloads
private void downloader_Completed(object sender, EventArgs e)
{
lblStatus.Content = String.Format("Download complete, downloaded {0} files.", downloader.Files.Count);
}
// Show a message that the downloads are being canceled - all files downloaded will be deleted and the current ones will be aborted
private void downloader_CancelRequested(object sender, EventArgs e)
{
lblStatus.Content = "Canceling downloads...";
}
// Show a message that the downloads are being canceled - all files downloaded will be deleted and the current ones will be aborted
private void downloader_DeletingFilesAfterCancel(object sender, EventArgs e)
{
lblStatus.Content = "Canceling downloads - deleting files...";
}
// Show a message saying the downloads have been canceled
private void downloader_Canceled(object sender, EventArgs e)
{
lblStatus.Content = "Download(s) canceled";
pBarFileProgress.Value = 0;
pBarTotalProgress.Value = 0;
lblFileProgress.Content = "-";
lblTotalProgress.Content = "-";
lblFileSize.Content = "-";
lblSavingTo.Content = "-";
}
// Setting the SupportsProgress property - if set to false, no total progress data will be avaible!
private void cbUseProgress_Checked(object sender, RoutedEventArgs e)
{
downloader.SupportsProgress = (Boolean)cbUseProgress.IsChecked;
}
// Setting the DeleteCompletedFilesAfterCancel property - indicates if the completed files should be deleted after cancellation
private void cbDeleteCompletedFiles_Checked(object sender, RoutedEventArgs e)
{
downloader.DeleteCompletedFilesAfterCancel = (Boolean)cbDeleteCompletedFiles.IsChecked;
}
// Close the window when the close button is hit
private void btnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
You can easily add to the rich text box new download links by creating your own function that takes a new download link path, to append to the text box you do:
richTextBox.AppendText("new string of download link");
You're not sure what rich text box? It is in your .xaml file, it is called rtbPaths. So you could create a new button that executes a dialog box, takes a string and use that string to append to this text box.
It's hard to understand what is being asked here as well, sorry if I got this wrong.

How to copy, paste, cut in FastColoredTextBox?

I need three functions: Copy, Paste, Cut ,
For a FastColoredTextBox.. so far with my methods, the job is done but afterwards,
the cursor's position get changed and I got no clue on how to keep it where it
was before.
Here's my methods:
private void OnMouseMenuCut(object sender, EventArgs e)
{
var sPoint = rtbScript.SelectionStart;
var ePoint = rtbScript.SelectionLength;
var text = rtbScript.SelectedText;
rtbScript.Text = rtbScript.Text.Remove(sPoint, ePoint);
Clipboard.SetText(text.Replace("\n", "\r\n"));
rtbScript.Text = rtbScript.Text.Insert(sPoint, text);
}
private void OnMouseMenuCopy(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(rtbScript.SelectedText)) return;
Clipboard.SetText(rtbScript.SelectedText.Replace("\n", "\r\n"));
}
private void OnMouseMenuPaste(object sender, EventArgs e)
{
if (!Clipboard.ContainsText()) return;
var index = rtbScript.SelectionStart;
rtbScript.Text = rtbScript.Text.Insert(index, Clipboard.GetText());
}
Also, If there's a better way to do those functions, please post..
Thanks!
For a RichTextBox your code has more issues than loosing the Cursor position, It also looses all formatting! Here are versions that should work better:
private void OnMouseMenuCut(object sender, EventArgs e)
{
var sPoint = rtbScript.SelectionStart;
var text = rtbScript.SelectedText;
rtbScript.Cut();
Clipboard.SetText(text.Replace("\n", "\r\n"));
rtbScript.SelectionStart = sPoint;
}
private void OnMouseMenuCopy(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(rtbScript.SelectedText)) return;
Clipboard.SetText(rtbScript.SelectedText.Replace("\n", "\r\n"));
}
private void OnMouseMenuPaste(object sender, EventArgs e)
{
if (!Clipboard.ContainsText()) return;
var index = rtbScript.SelectionStart;
rtbScript.SelectedText = Clipboard.GetText();
rtbScript.SelectionStart = index + Clipboard.GetText().Length;
}
Note: You must never change the Text property of a RTB or else you will mess up the formating!
Since you wrote that this also works with your FastColoredTextBox I have undeleted the solution..
In the current version of FCTB, these methods already exist inside the FCTB.cs file. They just need to be linked up.

How to make one event to identify whether multiple radio buttons are checked?

I have the following code which checks each radio button (Temp30, Temp40 and Temp60) and does the necessary things such as turning the wash temperature light on etc...
I want to create an event which handles all 3 radio buttons. I thought it could possibly have something to do with the groupbox they are in? (it is called TempGroupBox)
Any help would be much appreciated!
private void Temp30_CheckedChanged(object sender, EventArgs e)
{
if (Temp30.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._30degrees;
SpeedGroupBox.Enabled = true;
}
}
private void Temp40_CheckedChanged(object sender, EventArgs e)
{
if (Temp40.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._40degrees;
SpeedGroupBox.Enabled = true;
}
}
private void Temp60_CheckedChanged(object sender, EventArgs e)
{
if (Temp60.Checked)
{
MainDisplayLabel.Text = (" SELECT SPIN SPEED");
WashTempLight.Visible = true;
WashTempLight.Image = Properties.Resources._60degrees;
SpeedGroupBox.Enabled = true;
}
}
You can bind all radioButton's event to the same handler and use sender parameter to get the control that the action is for.
private void Temps_CheckedChanged(object sender, EventArgs e)
{
string checkedName = ((RadioButton)sender).Name;
if(checkedName == "Temp40")
{
...
}
else if(checkedName == "Temp60")
{
...
}
}
You can add event handler for all RadioBUttons's like that after InitializeComponent():
var radioButtons =this.Controls.OfType<RadioButton>();
foreach (RadioButton item in radioButtons)
{
item.CheckedChanged += Temps_CheckedChanged;
}

Categories

Resources