Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
Hi this WPF alarm app wont trigger the label to be fed in via animation. Initially it was made in a Form then I brought into WPF. When in C# Form this was all fine, everything triggered, but as soon as I brought it into WPF it wouldn't trigger.
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.Navigation;
using System.Windows.Shapes;
using System.Speech;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Dynamic;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Web;
using System.Timers;
using System.Runtime.InteropServices;
using System.Windows.Threading;
using System.Diagnostics;
using System.Windows.Media.Animation;
namespace Alarm_Clock_WPF
{
public partial class MainWindow : Window
{
DispatcherTimer dispatcherTimer1 = new DispatcherTimer();
DispatcherTimer dispatcherTimer2 = new DispatcherTimer();
public MainWindow()
{
System.Windows.Threading.DispatcherTimer dispathcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer1.Tick += new EventHandler(dispatcherTimer1_Tick);
dispatcherTimer2.Tick += new EventHandler(dispatcherTimer2_Tick);
dispatcherTimer1.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer1.Start();
dispatcherTimer2.Start();
InitializeComponent();
}
private void dispatcherTimer1_Tick(object sender, EventArgs e)
{
CountTime.Content = DateTime.Now.Hour.ToString("00") + ":" + DateTime.Now.Minute.ToString("00") + ":" + DateTime.Now.Second.ToString("00");
if (CountTime.Content == TriggerTime.Content)
{
DateTime now2 = DateTime.Now;
string date1 = DateTime.Today.ToString("D");
string time2 = now2.GetDateTimeFormats('t')[0];
//Label Leave Animation
//DoubleAnimation animation = new DoubleAnimation(0, TimeSpan.FromSeconds(2));
//label4.BeginAnimation(OpacityProperty, animation);
System.Diagnostics.Process.Start("https://www.youtube.com/");
//Music
System.Media.SoundPlayer sp = new System.Media.SoundPlayer(#"C:\Users\*****\Documents\Wake up theme 01.wav");
sp.Play();
//Video
//Video beach = new Video(#"C:\Users\******\Desktop\Jarvis\...avi");
//beach.Play();
label1.Content = "Done";
//Actual Wake Up Call
dispatcherTimer1.Stop();
}
}
private void dispatcherTimer2_Tick(object sender, EventArgs e)
{
//Alarm settings
if (CountTime.Content == TriggerTime.Content)
{
DateTime now2 = DateTime.Now;
string date1 = DateTime.Today.ToString("D");
string time2 = now2.GetDateTimeFormats('t')[0];
//Label Leave Animation
//DoubleAnimation animation = new DoubleAnimation(0, TimeSpan.FromSeconds(2));
//label4.BeginAnimation(OpacityProperty, animation);
System.Diagnostics.Process.Start("https://www.youtube.com/");
//Music
System.Media.SoundPlayer sp = new System.Media.SoundPlayer(#"C:\Users\*******\Documents\Wake up theme 01.wav");
sp.Play();
//Video
//Video beach = new Video(#"C:\Users\*******\Desktop\Jarvis\...avi");
//beach.Play();
label1.Content = "Done";
//Actual Wake Up Call
dispatcherTimer1.Stop();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
TriggerTime.Content = DateTime.Today.Hour.ToString("00") + ":" + DateTime.Today.Minute.ToString("00") + ":" + DateTime.Today.Second.ToString("00");
}
}
}
Obviously the coding itself is pretty bad, but the reason im here is to find out why the the 2 labels "CountTime and TriggerTime" wont trigger, if I set them != they trigger automatically. But when set == they dont.
To sum up comments. Because Content is an Object you compare it by reference. Use Equals method, which is overridden by String, to compare values:
CountTime.Content.Equals(TriggerTime.Content)
or cast both values to String and then compare them:
(string)CountTime.Content == (string)TriggerTime.Content
Related
I converted a window of mine to use CefSharp in order to render some PDF file. One of the features the old component supported (WebBrowser of WPF, which unfortunately depends on IE, which does not work in this case) is accessing javascript elements through code in order to be aware of when the PDF has been scrolled to the bottom. Unfortunately this does not appear to work with CefSharp with the following code. Perhaps i am missing some initializer flag for this to work?
Currently in my Logs All i get is ScrollProgress|0|0|734
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CefSharp;
using NLog;
using Application = System.Windows.Application;
using MessageBox = System.Windows.MessageBox;
using WebBrowser = System.Windows.Forms.WebBrowser;
namespace MyNamespace
{
public partial class PdfConfirmWindow : Window
{
private static readonly ILogger Log = LogManager.GetLogger(nameof(PdfConfirmWindow));
public PdfConfirmWindow()
{
InitializeComponent();
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
ChromiumWebBrowser.LoadingStateChanged += ChromiumWebBrowserOnLoadingStateChanged;
UpdateBrowserContent();
}
private void ChromiumWebBrowserOnLoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
if (!e.IsLoading)
{
Log.Debug("Loading completed");
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
// (window.innerHeight + window.scrollY) >= document.body.offsetHeight
// e.scrollHeight - e.scrollTop === e.clientHeight
// CefSharp.PostMessage('EndOfDocumentReached');
const string script = #"
(function(){
var intervalHandler;
function onScrollCallback() {
var e = document.body;
var values = ['ScrollProgress'];
values.push(document.body.clientHeight);
values.push(window.scrollY);
values.push(window.innerHeight);
CefSharp.PostMessage(values.join('|'));
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight){
//clearInterval(intervalHandler);
}
}
setTimeout(function(){
var intervalHandler = setInterval(function(){
onScrollCallback();
}, 100);
}, 500);
})();
";
ChromiumWebBrowser.Focus();
ChromiumWebBrowser.WebBrowser.JavascriptMessageReceived += WebBrowserOnJavascriptMessageReceived;
ChromiumWebBrowser.WebBrowser.ExecuteScriptAsync(script);
}));
}
}
private async void WebBrowserOnJavascriptMessageReceived(object sender, JavascriptMessageReceivedEventArgs e)
{
await UIHelper.Thread;
// ChromiumWebBrowser.WebBrowser.JavascriptMessageReceived -= WebBrowserOnJavascriptMessageReceived;
if (e.Message?.ToString().Equals("EndOfDocumentReached", StringComparison.OrdinalIgnoreCase) == true)
{
SetReachedStatus(true);
}
if (e.Message?.ToString().StartsWith("ScrollProgress", StringComparison.OrdinalIgnoreCase) == true)
{
Log.Debug(e.Message?.ToString());
}
}
}
I started learning C# using the book Head First C# and i'm doing the game in chapter 1 using WPF project , the thing is i think i followed everything according to the book but i get a invalidoperationexception in the begin method
here is the code i wrote :
using System;using
System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;`
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Random random = new Random();
public MainWindow()
{
InitializeComponent();
}
private void startButton_Click(object sender, RoutedEventArgs e)
{
AddEnemy();
}
private void AddEnemy()
{
ContentControl enemy = new ContentControl();
enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
AnimateEnemy(enemy,0,Play_Area.ActualWidth-100,"(Canvas.left)");
AnimateEnemy(enemy, random.Next((int)Play_Area.ActualHeight - 100), random.Next((int)Play_Area.ActualHeight - 100), "(Canvas.Top)");
Play_Area.Children.Add(enemy);
}
private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
{
Storyboard storyboard = new Storyboard () { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
DoubleAnimation animation = new DoubleAnimation()
{
From = from,
To = to,
Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6))),
};
Storyboard.SetTarget(animation, enemy);
Storyboard.SetTargetProperty(animation, new PropertyPath(propertyToAnimate));
storyboard.Children.Add(animation);
storyboard.Begin();
}
}
}
Here is a picture of my document Outline : Document Outline
why do i get the exception ? can anyone help me ?
Property names are case-sensitive. Try to change Canvas.left to Canvas.Left with an upper-case L:
AnimateEnemy(enemy,0,Play_Area.ActualWidth-100,"(Canvas.Left)");
I use naudio for generating a tone in a specified frequency like that:
private void gen_Sinus(double frequency)
{
WaveOut _myWaveOut = new WaveOut();
SignalGenerator mySinus = new SignalGenerator(44100, 1);//using NAudio.Wave.SampleProviders;
mySinus.Frequency = frequency;
mySinus.Type = SignalGeneratorType.Sin;
_myWaveOut.Init(mySinus);
_myWaveOut.Play();
}
I want that when clicking a button it will play that tone for a specific time that will be passed to this method. Let's call it for example:
double toneDuration
I prefer to prevent some sleep methods because it has to be as accurate as possible.
You can use OffsetSampleProvider to do this, and set the Take duration:
var trimmed = new OffsetSampleProvider(signalGenerator);
trimmed.Take = TimeSpan.FromSeconds(10);
waveOut.Init(trimmed);
waveOut.Play();
Use a timer and a wait handler
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Tick += new EventHandler(timer1_Tick);
}
static AutoResetEvent autoEvent = new AutoResetEvent(false);
private void gen_Sinus(double frequency)
{
WaveOut _myWaveOut = new WaveOut();
SignalGenerator mySinus = new SignalGenerator(44100, 1);//using NAudio.Wave.SampleProviders;
mySinus.Frequency = frequency;
mySinus.Type = SignalGeneratorType.Sin;
_myWaveOut.Init(mySinus);
timer1.Interval = 5000;
timer1.Start()
_myWaveOut.Play();
autoEvent.Reset();
autoEvent.WaitOne();
_myWaveOut.Stop();
}
private void timer1_Tick(object sender, EventArgs e)
{
autoEvent.Set();
}
}
}
Getting an "Access Violation" runtime error when trying to get a WebBrowser's .Url property in an Outlook Add-In I'm writing. Need some help on how to get past this please. Research indicates I may need to set "FullTrust" permissionset, have tried that with no success.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security;
using System.Security.Permissions;
namespace MyAddin1
{
public partial class authForm : Form
{
public string currentUrl;
public authForm()
{
InitializeComponent();
}
private void formLoaded(object sender, EventArgs e)
{
WebBrowser browser = new WebBrowser();
browser.Location = new System.Drawing.Point(0, 0);
browser.Width = 870;
browser.Height = 510;
browser.Navigate("https://www.yammer.com/dialog/oauth?client_id=<redacted>&response_type=token");
browser.Show();
//runtime error occurs on following line
currentUrl = browser.Url.ToString();
browser.Url = new Uri("http://www.yahoo.com");
browser.Navigated += new WebBrowserNavigatedEventHandler(checkForToken);
this.Controls.Add(browser);
}
private void checkForToken(object sender, EventArgs e)
{
MessageBox.Show(currentUrl);
}
}
}
browser.Url is initially null, Change your code as below.
if (browser.Url != null)
{
currentUrl = browser.Url.ToString();
}
In my windows phone 7 application, i have created a button to change the default background image and the users can have their own custom skins on the app. It worked perfectly. But when the users exits the app and relaunches it again the application's background image is changed to default. But what i needed is, the application should have the last image that is chosen by the user even is launched no. of times. Can anyone help me with this? Thanks in advance for your hard work!
private void BackgroundBrowserIcon_MouseEnter(object sender, MouseEventArgs e)
{
var PhotoChooser = new PhotoChooserTask();
PhotoChooser.Completed += new EventHandler<PhotoResult>(PhotoChooser_Completed);
PhotoChooser.Show();
}
void PhotoChooser_Completed(object sender, PhotoResult e)
{
{
if (e.TaskResult == TaskResult.OK)
{
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
var app = Application.Current as App;
if (app == null)
return;
var imageBrush = new ImageBrush { ImageSource = bmp, Opacity = 1.0d };
this.LayoutRoot.Background = imageBrush;
app.backchanged = true;
app.appbrush = imageBrush;
}
}
}
Are you using IsolatedStorageSettings to store the last chosen photo, and then loading it on app launch?
Update:
Check out this post, as it explains how to code exactly what you are looking to accomplish: http://www.windowsphonegeek.com/tips/All-about-WP7-Isolated-Storage---Read-and-Save-Captured-Image
Check out this article to learn how to store IsolatedStorageSettings.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO.IsolatedStorage;
namespace F5debugWp7IsolatedStorage
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void button3_Click(object sender, RoutedEventArgs e)
{
IsolatedStorageSettings ISSetting = IsolatedStorageSettings.ApplicationSettings;
if (!ISSetting.Contains("DataKey"))
{
ISSetting.Add("DataKey", txtSaveData.Text);
}
else
{
ISSetting["DataKey"] = txtSaveData.Text;
}
ISSetting.Save();
}
}
}