I have this functions and I must use MediaPlayer because I have to play more sounds together. This code works, but the sounds doesn't stop on the keyup (I tried some code but didn't worked). How can I do the function stopSound?
Thank'you!
private void Form1_KeyDown(object sender, KeyPressEventArgs e)
{
[...] // Other code
playSound(key, name);
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
[...] // Other code
stopSound(key, name);
}
private void playSound(string name)
{
[...] // Other code
string url = Application.StartupPath + "\\notes\\" + name + ".wav";
var sound = new System.Windows.Media.MediaPlayer();
sound.Open(new Uri(url));
sound.play();
}
private void stopSound(string name)
{
???
}
If you store all references to the MediaPlayer instances that you create in a List<MediaPlayer>, you could access them later using this list and stop them. Something like this:
List<System.Windows.Media.MediaPlayer> sounds = new List<System.Windows.Media.MediaPlayer>();
private void playSound(string name)
{
string url = Application.StartupPath + "\\notes\\" + name + ".wav";
var sound = new System.Windows.Media.MediaPlayer();
sound.Open(new Uri(url));
sound.play();
sounds.Add(sound);
}
private void stopSound()
{
for (int i = sounds.Count - 1; i >= 0; i--)
{
sounds[i].Stop();
sounds.RemoveAt(i);
}
}
Related
i'M in a small project that needs to Screenshot a game.
I made it Screenshot the game,and I need to make it Start and Stop the Screenshooter.
But I 've a problem now...
Code:
public string path = "";
public Form1()
{
InitializeComponent();
}
private static string _path = "C:\\temp\\not posted";
private static int _timespan = 3000;
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = true;
var path =#"FPSS";
if (path != string.Empty)
_path = path;
_timespan = 3000;
DirectoryInfo dir = new DirectoryInfo(_path);
PrintScreen ps = new PrintScreen();
if (!dir.Exists) dir.Create();
var countScreens = 0;
while (true)
{
var task=StartPrinting(ps);
task.Wait();
Thread.Sleep(_timespan);
if (countScreens == 20)
{
System.GC.Collect();
countScreens = 0;
}
countScreens++;
}
}
private static async Task StartPrinting(PrintScreen ps)
{
var name = DateTime.Now.ToString("yyyyMMddhhmmss");
ps.CaptureScreenToFile($"{_path}\\{name}.png", ImageFormat.Png);
Console.WriteLine($"Printed {name}");
}
private void button2_Click(object sender, EventArgs e)
{
button1.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
But in this way (with button1 start the infinite loop) I can't turn this off because the loop is running...
Any ideas? :)
Thanks!
So I made a software that can download strings from url. Here is my code:
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
var accounts = new WebClient().DownloadString("https://pastebin.pl/view/raw/sample").Split('\n');
textBox1.Text = accounts[new Random().Next(0, accounts.Length)];
}
How can I make custom progress bar made by text, such that only text will show for progressing the download? example:
When the download is 10% I want to put on text progressbar (Status: requesting database)
when it comes up to 50% I want to put on text progressbar (Status: getting information)
when it comes 100% (Status: completed)
My Full Code
My Ui
you should use async method to download
private void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
Download(new Uri("https://pastebin.pl/view/raw/sample"));
}
else if (radioButton2.Checked)
{
Download(new Uri("https://pastebin.pl/view/raw/sample2"));
}
else if (radioButton3.Checked)
{
Download(new Uri("https://pastebin.pl/view/raw/sample4"));
}
else
{
MessageBox.Show(this, "select radio btn");
}
}
private void Download(Uri uri)
{
Thread thread = new Thread(() =>
{
WebClient client = new WebClient();
client.DownloadProgressChanged += Client_DownloadProgressChanged1;
client.DownloadStringCompleted += Client_DownloadStringCompleted;
client.DownloadStringAsync(uri);
});
thread.Start();
}
private void Client_DownloadProgressChanged1(object sender, DownloadProgressChangedEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate {
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
if(percentage >=10 && percentage <50)
{
textBox1.Text ="message for 10%";
}
else if if(percentage >=50 && percentage <100)
{
textBox1.Text ="message for 50%";
}
else
{
textBox1.Text ="completed";
}
// you can use to show to calculated % of download
});
}
private void Client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
BeginInvoke((MethodInvoker)delegate
{
var accounts = e.Result.Split('\n');
textBox1.Text = accounts[new Random().Next(0,accounts.Length)];
});
}
WebClient has been deprecated in favor of HttpClient, but here goes.
You should use Progress<T> to report back progress.
You can define an extension method like:
public static class WebClientExtensions
{
public static async Task<string> DownloadStringTaskAsync(
this WebClient webClient,
string address,
IProgress<int> progress)
{
try
{
webClient.DownloadProgressChanged += downloadProgressChanged;
return await webClient.DownloadStringTaskAsync(address);
}
finally
{
webClient.DownloadProgressChanged -= downloadProgressChanged;
}
void downloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progress.Report(e.ProgressPercentage);
}
}
}
and use it like this:
private async void button1_Click(object sender, EventArgs e)
{
if (radioButton1.Checked)
{
var text = await new WebClient()
.DownloadStringTaskAsync(
"https://pastebin.pl/view/raw/sample",
new Progress<int>(p => /* report progress */));
var accounts = text.Split('\n');
textBox1.Text = accounts[new Random().Next(0, accounts.Length)];
}
}
I want to save richTextBox.Text every minute, when user checked save checkbox.
here checkbox event.
num_saveTime is numericUpDown control for inpute minute.
save_timer is global variable.
private void chk_save_CheckedChanged(object sender, EventArgs e)
{
if (chk_save.Checked)
{
num_saveTime.Enabled = false;
save_timer = new System.Timers.Timer();
save_timer.Elapsed += new System.Timers.ElapsedEventHandler(save_timer_Elapsed);
save_timer.Interval = 250;
save_timer.Start();
}
else
{
num_saveTime.Enabled = true;
save_timer.Stop();
}
}
and Timer Event
delegate void TimerDelegate(object sender, System.Timers.ElapsedEventArgs e);
void save_timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (rtxb_PKT.InvokeRequired)
{
TimerDelegate tdel = new TimerDelegate(save_timer_Elapsed);
rtxb_PKT.Invoke(tdel, new object[] { sender, e });
}
else
{
string now_ss = DateTime.Now.ToString("ss");
if (now_ss.Equals("00"))
{
string now_mm = DateTime.Now.ToString("mm");
string save_mm = Convert.ToInt32(num_saveTime.Value).ToString("D2");
if (save_mm.Equals(now_mm))
{
string path = Application.StartupPath + #"\" + DateTime.Now.ToString("yy-MM-dd--HH-mm-sss") + ".rtf";
rtxb_PKT.SaveFile(path, RichTextBoxStreamType.RichText);
rtxb_PKT.Clear(); //----here
}
}
}
}
I want clear richTextBox after save.
But I insert .Clear() that position, it clear text before save, so file is empty...
How can I clear it after saving?
I'm fairly new to WPF and I need your help with one object passing between more WPF windows.
Firstly I have my MainWindow with Button_Click event like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
Attribute ChooseYourAttr = new Attribute();
Application.Current.MainWindow.Close();
ChooseYourAttr.Show();
Character Player = new Character(firstTextbox.Text);
}
And Then I have my second window called Attribute with something like this:
private void attributeTopLabel_Initialized(object sender, EventArgs e)
{
String welcomeAttribute = "Ahh. I see! So ";
attributeTopLabel.Content = welcomeAttribute;
}
And I would like to have something like this: (Player.getName());
private void attributeTopLabel_Initialized(object sender, EventArgs e)
{
String welcomeAttribute = "Ahh. I see! So " + Player.getName();
attributeTopLabel.Content = welcomeAttribute;
}
Thanks for your answers!
Just pass the value through in the constructor:
private Character player = new Character();
public Attribute(Character player)
{
this.player = player;
}
...
Character player = new Character(firstTextbox.Text);
Attribute ChooseYourAttr = new Attribute(player);
...
private void attributeTopLabel_Initialized(object sender, EventArgs e)
{
String welcomeAttribute = "Ahh. I see! So " + player.GetName();
attributeTopLabel.Content = welcomeAttribute;
}
My question is the following:
I have a timer and each 1 ms i want to load an image and display it in a picture box in win forms
The first images work very fine however from some point the images start loading hard.
Can you please tell me how to solve this problem?
Regards and thank you for your time :)
private string path = "";
private int index = 0;
private void fileSourceToolStripMenuItem_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
path = fullPath.Replace(fileName, "");
MessageBox.Show("Path for file source has been selected");
}
}
private const string IMAGENAME = "TestImage";
Bitmap b;
private void timer_Tick(object sender, EventArgs e)
{
try
{
string currentImage = IMAGENAME + index.ToString() + ".bmp";
index++;
b = new Bitmap(path + "\\" + currentImage);
pb.SizeMode = PictureBoxSizeMode.StretchImage;
pb.Image = b;
}
catch { };
}
private void button1_Click(object sender, EventArgs e)
{
timer.Start();
}
private void button2_Click(object sender, EventArgs e)
{
timer.Stop();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
string currentImage = IMAGENAME + index.ToString() + ".bmp";
index += 1;
Bitmap b = new Bitmap(path + "\\" + currentImage);
pb.Image = b;
}
catch { };
}
private void button4_Click(object sender, EventArgs e)
{
try
{
index -= 1;
string currentImage = IMAGENAME + index.ToString() + ".bmp";
Bitmap b = new Bitmap(path + "\\" + currentImage);
pb.Image = b;
}
catch { };
}
Play with DoubleBuffered property first.
GDI+ is very slow and even when using double buffering then it's still slow.
I would suggest you to find an alternative as there isn't really a way to fix the "flickering".
However there is one thing, the way you're actually loading the images in the tick handle is pretty cpu consuming.
I would suggest you load all the required image's bytes into a collection of some sort, ex. an array.
Then simply create the bitmap from the image bytes.
Besides you're not even disposing the current image, which you should before allocating new memory for the next image.