C# AxWindowsMediaPlayer loop - c#

I've got this annoying problem which I can't track down where it goes wrong.
I'm creating a Windows Media Player in code and I'm trying to loop a video... It loops, but only once...
So it plays the video, and once more. And then it just stop and shows the end of the video. So it seems as if it loops only once.
This is the code I have:
try {
wmPlayer = new AxWMPLib.AxWindowsMediaPlayer();
wmPlayer.enableContextMenu = false;
((System.ComponentModel.ISupportInitialize)(wmPlayer)).BeginInit();
wmPlayer.Name = "wmPlayer";
wmPlayer.Enabled = true;
wmPlayer.Dock = System.Windows.Forms.DockStyle.Fill;
mainForm.Controls.Add(wmPlayer);
((System.ComponentModel.ISupportInitialize)(wmPlayer)).EndInit();
wmPlayer.uiMode = "none";
if(kind == "idle") {
IdleVideo(name);
}
}
catch { }
}
private static void IdleVideo(string name) {
System.Diagnostics.Debug.WriteLine("Video called once");
wmPlayer.URL = #"C:\ProjectSilver\assets\RadarDetectie\idle\" + name + "_idlescreen_movie.ogv";
Debug.WriteLine(wmPlayer.URL);
wmPlayer.settings.setMode("loop", true);
wmPlayer.Ctlcontrols.play();
}
So I hope you guys can help, why doesn't it keep playing?

just use
private void Form1_Load(object sender, EventArgs e)
{
// give the path of your video here
axWindowsMediaPlayer1.URL = "Path of your video";
// this line will automatically start your video
axWindowsMediaPlayer1.settings.autoStart = true;
//here the system will automatially create a thread and will keep on
running your video...
axWindowsMediaPlayer1.settings.setMode("loop", true);
}

Add an event handler for the PlayStateChange event:
wmPlayer.PlayStateChange += wmPlayer_PlayStateChange;
Then in the event handler check if e.newState==8 which means media ended:
AxWMPLib.AxWindowsMediaPlayer wmPlayer;
private void player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if(e.newState==8) // MediaEnded
// call function to play the video again
}
For play states, check this:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd562460%28v=vs.85%29.aspx
Edit:
I don't know what you do with kind, or where the first part of your code is defined, but this worked for me:
AxWMPLib.AxWindowsMediaPlayer wmPlayer;
private void button2_Click(object sender, EventArgs e)
{
wmPlayer = new AxWMPLib.AxWindowsMediaPlayer();
wmPlayer.CreateControl();
wmPlayer.enableContextMenu = false;
((System.ComponentModel.ISupportInitialize)(wmPlayer)).BeginInit();
wmPlayer.Name = "wmPlayer";
wmPlayer.Enabled = true;
wmPlayer.Dock = System.Windows.Forms.DockStyle.Fill;
this.Controls.Add(wmPlayer);
((System.ComponentModel.ISupportInitialize)(wmPlayer)).EndInit();
wmPlayer.uiMode = "none";
wmPlayer.URL = #"C:\...";
wmPlayer.settings.setMode("loop", true);
wmPlayer.Ctlcontrols.play();
}

Related

C# Emgucv turn off webcam

currently my program can open the webcam then dynamic capture the human face, however, I have no idea how to stop the camera because it will keep capturing the face even the windows are closed.
private static VideoCapture _cameraCapture;
public VideoSurveilance()
{
InitializeComponent();
Run();
}
void Run()
{
try
{
_cameraCapture = new VideoCapture();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
return;
}
_fgDetector = new
Emgu.CV.VideoSurveillance.BackgroundSubtractorMOG2();
_blobDetector = new CvBlobDetector();
_tracker = new CvTracks();
Application.Idle += ProcessFrame;
}
private void btnStopCamera_Click(object sender, EventArgs e)
{
_cameraCapture.Pause();//not working
_cameraCapture.Stop();//not working
_cameraCapture.Dispose();//worked but crashed due to memory issue
this.Close();
faceManipulate fm = new faceManipulate();
fm.Show();
Memory issue already solved. However, Dispose will cause the process frame Null Reference Object.
void ProcessFrame(object sender, EventArgs e)
{
Mat frame = _cameraCapture.QueryFrame();
Mat smoothedFrame = new Mat();
CvInvoke.GaussianBlur(frame, smoothedFrame, new Size(3, 3), 1);
}
You already solved the issue, you should call the Dispose method.
CameraCapture implements DisposableObject, you should not have it as a static variable, instead you should keep it as a variable and dispose when you are done with it.
I saw that you said that it "worked but crashed due to memory issue", if this is still a problem post a question or comment below describing the memory issue.
I noticed this code challenge is old and not many solutions have been posted at this time. However, the provided response will not really solve the issue. I encountered the same problem and found a way around it to avoid the memory NullReferenceError. I will use my own code here for convenience, but the challenges are the same, so it applies. Pick the code section that applies to your instance.
MY OBSERVATIONS
Any Bitmap object has to be disposed (bitmap.Dispose())
properly to free the memory from overload. The natural garbage
collector seems not to pick it up at the end of its function.
The Emgu.CV.Capture _capture; object has to be disposed
(_capture.Dsipose()) as well but has to be done with boolean control to avoid a NullReference error.
public partial class Main : Form
{
bool isStreaming;
bool onCamera;
Capture _capture;
public Main()
{
InitializeComponent();
}
private void btnReset_Click(object sender, EventArgs e)
{
onCamera = false;
isStreaming = false;
if (_capture != null) _capture.Dispose();
if (picStream.Image != null) picStream.Image = null;
if (picCapture.Image != null) picCapture.Image = null;
}
private void btnStream_Click(object sender, EventArgs e)
{
try
{
onCamera = true;
if (_capture != null) _capture.Dispose();
_capture = new Capture();
labelStatus.Text = "Streaming...";
isStreaming = true;
StreamVideo();
Application.Idle += Streaming;
}
catch {}
}
private void Streaming(object sender, EventArgs e)
{
try
{
if(onCamera && isStreaming)
{
if (picStream.Image != null) picStream.Image = null;
var img = _capture.QueryFrame().ToImage<Bgr, byte>();
var bmp = img.Bitmap;
picStream.Image = bmp;
}
}
catch {}
}
private void btnCapture_Click(object sender, EventArgs e)
{
onCamera = true;
CaptureImage();
labelStatus.Text = "Captured!";
if (picCapture.Image != null) picCapture.Image = null;
picCapture.Image = picStream.Image;
}
private void btnLoadCamera_Click(object sender, EventArgs e)
{
try
{
if (!isStreaming)
{
_capture = new Capture();
StreamVideo();
pnlStatus.BackColor = Color.DimGray;
}
else
{
_capture.Dispose();
Application.Idle -= Streaming;
picStream.Visible = true;
picStream.Image = null;
picCapture.Visible = false;
picCapture.Image = null;
isStreaming = false;
pnlStatus.BackColor = Color.DimGray;
}
}
catch {}
}
}

Windows forms not rendering buttons, images, launching application at runtime - C#

I'm having this issue for a while now on some machines, when the user runs the application all the buttons, images, menu items, almost everything goes blank.
My first thought was: I have a separate thread using BackgroundWorker updating a StatusBar and I've read that this can cause issues to form rendering.
I found an article (it's in portuguese, since I'm a Brazilian) that explains this is a issue caused by a security plugin installed by our banks called Warsaw. One of the solutions was to contact the developers to have them analyze your software so the plugin will work correctly. I've done this and I'm waiting for their response.
The other solution is to sign our assembiles so the plugin may recognize as a trusted software, this is good but not free of charge unfortunately.
Now, here's an example of my application looks like when it's launched with this issue:
A form with a GridView
The code for the separate thread as mentioned above:
int countAlerta = 0;
int countAlertaRFRP = 0;
int countAlertaAditivo = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
backgroundWorker1.RunWorkerAsync();
else
{
alertaToolStripStatusLabel.Text = "Continuando a verificação...";
alertaToolStripStatusLabel.IsLink = false;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(0);
timer1.Enabled = false;
lock (new object())
{
countAlerta = new BLL.AlertasBLL().CountRVSRAS();
countAlertaRFRP = new BLL.AlertasBLL().CountRFRP();
countAlertaAditivo = new BLL.AlertasBLL().CountAditivos();
}
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
alertaToolStripStatusLabel.Text = "Verificando...";
alertaToolStripStatusLabel.IsLink = false;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (countAlerta + countAlertaAditivo + countAlertaRFRP > 0)
{
alertaToolStripStatusLabel.Text = "ALERTA: Verifique!!!";
alertaToolStripStatusLabel.IsLink = true;
alertaToolStripStatusLabel.Font = new Font(alertaToolStripStatusLabel.Font, FontStyle.Bold);
}
else
{
alertaToolStripStatusLabel.Text = "Não existem alertas";
alertaToolStripStatusLabel.IsLink = false;
}
timer1.Enabled = true;
}

web browser cannot work with 1 click

I have a situation which occurs in WebBrowser with C#.
I am trying to do downloader through a site However , when i click first time, it doesn't work but if I click second times it works.
How can i solve this problem .
Sincerely.
Codes :
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Document.GetElementById("youtube-url").SetAttribute("value", textBox1.Text);
webBrowser1.Document.GetElementById("submit").InvokeMember("click");
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
label3.Text = "Video Alındı , indirme işleminin hazır olması bekleniyor";
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlElementCollection col = webBrowser1.Document.GetElementsByTagName("a");
String link = "";
foreach (HtmlElement el in col)
{
if (el.InnerText == "Download")
{
link = el.GetAttribute("href");
Download(link);
label3.Text = "Video indiriliyor";
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate("http://www.youtube-mp3.org/tr");
}
void Download(String link)
{
WebClient downloader = new WebClient();
downloader.DownloadFileAsync(new Uri(link),#"D:\a.mp3");
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(downloader_DownloadProgressChanged);
}
void downloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label3.Text = "Video İndiriliyor : " + progressBar1.Value + "%";
if (progressBar1.Value == 100)
label3.Text = "Video İndirildi";
}
You're blocking yourself from investigating what the problem is. It's never a good idea to disable script errors for WebBrowser control (as you do with ScriptErrorsSuppressed = true), unless you handle them internally in your host app. Do the following:
enable script errors (ScriptErrorsSuppressed = false);
enable script debugging for all applications;
implement WebBrowser Feature Control (FEATURE_BROWSER_EMULATION), so the web page is getting the same (or close) experience and HTML features as with full-featured IE browser.
Then, hopefully, you can find out what's going wrong when you're simulating a button click, and debug it.

Making sure a backgroundworker has finished before running it (again)

Context: I am playing music through a media element, and using a slider to display the point in the song that it is at. That updating is done in a backgroundworker, for obvious reasons.
private void bgPlay_DoWork(object sender,DoWorkEventArgs e)
{
while (isMediaPlaying)
{
this.Dispatcher.Invoke((Action)(() =>
{
timelineSlider.Value = mediaElement1.Position.TotalMilliseconds;
}));
}
}
private void Library_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
mediaElement1.Stop();
isMediaPlaying = false;
mediaElement1.Source = new Uri(songData[Library.SelectedIndex].Location);
mediaElement1.Volume = (double)volumeSlider.Value;
mediaElement1.Play();
isMediaPlaying = true;
bgPlay.RunWorkerAsync();
}
catch(Exception ex) {
F.MessageBox.Show(ex.ToString());
}
}
When I play a song, then double click on a different one, the background worker is still looping and throws an exception because it reaches bgPlay.RunWorkerAsync(); before the previous instance has finished. I tried to use the isMediaPlaying bool to tell the backgroundworker when to exit the loop, but the main thread reaches bgPlay.RunWorkerAsync(); before it finishes.
You are suffering of a common mistake when one is barely starting to program with threading, a race condition
I'd advise rewriting the code like this:
private static String threadingLock = "";
private void bgPlay_DoWork(object sender,DoWorkEventArgs e)
{
while (true)
{
lock(threadingLock) {
if(!isMediaPlaying)
break;
}
this.Dispatcher.Invoke((Action)(() =>
{
timelineSlider.Value = mediaElement1.Position.TotalMilliseconds;
}));
}
}
private void Library_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
try
{
lock(threadingLock) {
isMediaPlaying = false;
}
mediaElement1.Stop();
mediaElement1.Source = new Uri(songData[Library.SelectedIndex].Location);
mediaElement1.Volume = (double)volumeSlider.Value;
mediaElement1.Play();
isMediaPlaying = true;
bgPlay.RunWorkerAsync();
}
catch(Exception ex) {
F.MessageBox.Show(ex.ToString());
}
}
As a friendly tip, add a Thread.sleep(200) before invoking the update on the slider. It will reduce cpu usage without affecting the functionality of your application.

C# Web Browser Bot question

I want to do web browser bot. It should click link and wait 25 seconds.
private void webBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) // This is only way It worked for me.
{
if (webBrowserMain.Url.AbsoluteUri == #"http://www.clix-cents.com/pages/clickads")
{
Regex regAddId = new Regex("onclick=\\'openad\\(\"([\\d\\w]+)\"\\);", RegexOptions.IgnoreCase); // Find link and click it.
if (regAddId.IsMatch(webBrowserMain.DocumentText))
{
string AddId = regAddId.Match(webBrowserMain.DocumentText).Groups[1].ToString();
webBrowserMain.Navigate(#"http://www.clix-cents.com/pages/clickads?h=" + AddId);
}
}
else if (webBrowserMain.Url.AbsoluteUri.Contains("http://www.clix-cents.com/pages/clickads?h=")) // up to there everything is ok. But problem starts here.
{
Thread.Sleep(25000); // It pouses whole thread and browser, so timer in browser is not counting down.
Regex regCaptchaCode = new Regex("src=\\'/pages/captcha\\?t=c&s=([\\d\\w\\W]+)\\'", RegexOptions.IgnoreCase);
if (regCaptchaCode.IsMatch(webBrowserMain.DocumentText))
{
pictureBox1.ImageLocation = #"http://www.clix-cents.com/pages/captcha?t=c&s=" + regCaptchaCode.Match(webBrowserMain.DocumentText).ToString();
}
}
}
How to write bot for something like that? I have no idea.
Don't reinvent the wheel - there's already solutions out there like WatiN which is mainly used for testing but is also suitable for automation.
Code example from the WatiN page:
[Test]
public void SearchForWatiNOnGoogle()
{
using (var browser = new IE("http://www.google.com"))
{
browser.TextField(Find.ByName("q")).TypeText("WatiN");
browser.Button(Find.ByName("btnG")).Click();
Assert.IsTrue(browser.ContainsText("WatiN"));
}
}
You could probably use a timer. Eg:
private Timer t = new Timer();
private string nextUrl = "";
private void buttonStart_Click(object sender, EventArgs e)
{
t.Interval = 2500;
t.Tick += new EventHandler(t_Tick);
}
void t_Tick(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(nextUrl))
webBrowser1.Navigate(nextUrl);
else
{
Regex regCaptchaCode = new Regex("src=\\'/pages/captcha\\?t=c&s=([\\d\\w\\W]+)\\'", RegexOptions.IgnoreCase);
if (regCaptchaCode.IsMatch(webBrowserMain.DocumentText))
{
pictureBox1.ImageLocation = #"http://www.clix-cents.com/pages/captcha?t=c&s=" + regCaptchaCode.Match(webBrowserMain.DocumentText).ToString();
}
}
}
private void webBrowserMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) // This is only way It worked for me.
{
if (webBrowserMain.Url.AbsoluteUri == #"http://www.clix-cents.com/pages/clickads")
{
Regex regAddId = new Regex("onclick=\\'openad\\(\"([\\d\\w]+)\"\\);", RegexOptions.IgnoreCase); // Find link and click it.
if (regAddId.IsMatch(webBrowserMain.DocumentText))
{
string AddId = regAddId.Match(webBrowserMain.DocumentText).Groups[1].ToString();
nextUrl = #"http://www.clix-cents.com/pages/clickads?h=" + AddId;
t.Start();
}
}
else if (webBrowserMain.Url.AbsoluteUri.Contains("http://www.clix-cents.com/pages/clickads?h=")) // up to there everything is ok. But problem starts here.
{
nextUrl = "";
t.Start();
}
}
The actual implementation will depend on the actual data on the site and how you want to use it. If all the links are on one page and you want to open each one, you could parse for all the links and store into a list. Then start the timer. At each Tick, you could open 1 item.

Categories