I am new to c# and I am trying to learn Windows Phone development. What I am trying to do is simply be able to move a rectangle with your finger but I get this error:
Error 1 No overload for 'Drag_ManipulationDelta' matches delegate 'System.EventHandler<Windows.UI.Xaml.Input.ManipulationDeltaEventHandler>' C:\Users\Zach\documents\visual studio 2013\Projects\App2\App2\MainPage.xaml.cs 35 46 App2
I have seen this 'No overload for method matches delegate' question asked before but since I am new I am a little confused on what is going on.
Here is the full code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows;
using System.Windows.Input;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Shapes;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641
namespace App2
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
private int buttonCount = 0;
private TranslateTransform dragTranslation; // For changing position of myRectangle
private SolidColorBrush redRect = new SolidColorBrush(Windows.UI.Colors.Red);
public MainPage()
{
this.InitializeComponent();
myRectangle.ManipulationDelta += new EventHandler<ManipulationStartedEventHandler>(Drag_ManipulationDelta);
//myRectangle.ManipulationDelta += new System.EventHandler<ManipulationDeltaEventArgs>(Drag_ManipulationDelta);
dragTranslation = new TranslateTransform();
myRectangle.RenderTransform = this.dragTranslation;
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
// < Called when myButton is pressed >
private void myButton_Click(object sender, RoutedEventArgs e)
{
buttonCount += 1;
myRectangle.Fill = redRect;
resultText.Text = "";
// Determines visibility of myRectangle
if(buttonCount % 2 != 0)
{
myRectangle.Visibility = Visibility.Visible;
}
else
{
myRectangle.Visibility = Visibility.Collapsed;
}
}
// < Called when myRectangle is pressed >
private void myRectangle_PointerPressed(object sender, PointerRoutedEventArgs e)
{
resultText.Text = "You touched the rectangle.";
}
void Drag_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
// Move the rectangle.
dragTranslation.X += e.Delta.Translation.X;
dragTranslation.Y += e.Delta.Translation.Y;
//dragTranslation.Y += e.DeltaManipulation.Translation.Y;
}
}
}
Thanks
Neither version of the event subscription you show in your post – the commented-out one, and especially the one before that (using an event handler delegate type itself as the type parameter for the EventHandler<T> type just makes no sense at all in any context) – use a type that is consistent with your actual method, hence the error.
The compiler complains that no overload matches, because it is theoretically possible to have multiple methods having the same name. So an error that simply says "the method" doesn't match wouldn't make sense. It is the case that none of the available methods with that name match; in this case, it just happens there's only one available method.
Without the declaration for the myRectangle object and its type, and in particular the ManipulationDelta event, it's not possible to know for sure what you need to do.
However, most likely you can just get rid of the explicit delegate type altogether:
myRectangle.ManipulationDelta += Drag_ManipulationDelta;
Then you don't need to guess as to what type to use for the delegate instance initialization. The compiler will infer the correct type and even the delegate instantiation on your behalf.
If that doesn't work, then you need to fix the method declaration so that it does match the event's delegate type. Without seeing the event declaration and its type, I can't offer any specific advice about that.
EDIT:
Per your explanation that you are trying to follow the example at Quickstart: Touch input for Windows Phone 8, I can see that your method declaration is incorrect.
The event is declared as EventHandler<ManipulationDeltaEventArgs>, but your method uses ManipulationDeltaRoutedEventArgs as the type for its second parameter. Why Microsoft chose to change the name between the older Phone API and the new XAML/WinRT API I don't know. But it's important to keep the right type:
void Drag_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
Note that my previous comment still applies as well; you don't need to specify the delegate type when subscribing. You can write the event subscription as I showed originally above.
Related
I can't get OnNewIntent to fire. I've read dozens of articles on the issue and tried all combinations of code.
Regardless of whether I use LaunchMode.SingleTask or SingleTop it won't fire and always passes through the OnCreate method.
What am I doing wrong here? Am I missing something? What do I need to add to get it to work?
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;
using System;
using System.Threading.Tasks;
using Xamarin.Forms;
using static MyApp.ClipboardMgr;
namespace MyApp.Droid
{
//[Activity(Label = "SplashActivity")]
[Activity(LaunchMode = LaunchMode.SingleTask, Theme = "#style/Theme.Splash",
MainLauncher = true, NoHistory = true)]
//Can't get this to work with LaunchMode.SingleTop or SingleTask. Always creates a new instance.
[IntentFilter(new[] { Intent.ActionProcessText },
Categories = new[] { Intent.CategoryDefault },
DataMimeType = #"text/plain", Icon = "#drawable/icon", Label = "MyApp")]
public class SplashActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
try
{
//taking these out for readability
//AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
//TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
//AndroidEnvironment.UnhandledExceptionRaiser += AndroidEnvironment_UnhandledExceptionRaiser;
base.OnCreate(savedInstanceState);
// Create your application
StartActivity(typeof(MainActivity));
//don't want to do this here, better to do it in event
if (Intent.Action == Intent.ActionProcessText)
{
//always comes here
HandleProcessTextIntent();
}
}
catch(Exception e)
{
App.LogException(e);
throw;
}
}
/// <summary>
/// this is not firing!
/// </summary>
/// <param name="intent"></param>
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
HandleProcessTextIntent();
}
void HandleProcessTextIntent()
{
string input = Intent.GetStringExtra(Intent.ExtraProcessText).Trim();
if (input == string.Empty)
return;
ClipMgr.SetText(input);
}
}
}
You didn't miss anything since when I test with my own intent to start your activity, it works well and the OnNewIntent() is called when SingleTask or SingleTop used, here's how I call the activity from another project(I did this in native Android):
ComponentName component = new ComponentName("com.example.textHandlerDemo", "com.example.textHandlerDemo.TextHandlerActivity");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PROCESS_TEXT);
intent.setComponent(component);
startActivity(intent);
I did some research and find something that may explain why the OnNewIntent() never gets fired:
According to the guidance of ACTION_PROCESS_TEXT, it mentioned:
You can use this as a hint to offer the ability to return altered text to the sending app, replacing the selected text. This works as your Activity was actually started with startActivityForResult()
So, when you click your app's label in the floating text selection toolbar, Android will start your activity registered with ActionProcessText with startActivityForResult(), and by using startActivityForResult(), your activity will be started as a sub-activity of current activity(implied from Android doc of startActivityForResult), that is to say, rather than redirecting to your app which is already running, Android will put your activity into current app's stack.
This way, your target activity will still be called from OnCreate() since it's isolated from your running app.
Moreover, the floating text selection toolbar is used to provide a quick in-app experience for text operations like translation as mentioned in this blog, I didn't find any swich to enable/disable redirect to app, you may need to handle the intent in both OnCreate() and OnNewIntent() if you're using LaunchMode.SingleTask or SingleTop.
I am new here as well as to C#. I'm trying to learn it better and as a basic programming challenge for myself, I'm trying to understand how to move or return certain values from user input/text boxes after being submitted to a table that is displayed in a list.
Here is my "challenge" I'm trying to create a simple program that has 2 text boxes one for a name of the new value to a list (not an array I've learned that the hard way) and one for a name of a searched value in a said list. Submit button for each of those text boxes with a message stating either "Value Added" when it was added, or "Found" "Doesn't Exist" for the search button. Then on a side of said boxes and buttons I actually want to display my list with a scrollable 2 column window / box, First column as position in a table like value in which its at and then the actual name of the said value that was added. (Oh an also a clear button for the list itself)
So here is what I've gathered so far. I understand I have to transform all input into a string and then push it to the list. I know how to display the MessageBox.Show("") however I don't know how to code conditions to it. I would try a simple if () but I would first need to be able to program a working search function which requires pushing and pulling data from the list. I know JavaScript has array.push and array.indexof which makes finding and pushing things into an array rather simple, but to my knowledge, C# does not have that function.
I am new to this so any tips on a material to read that would help me learn C# or any tips on how to make this work properly will be appreciated. My biggest struggle is to return a value from the said text box into another private void and using it in my var, in other words pushing the product of a function into another function (like in the example below pushing the Add_Text.Text into the var names = new List<string>(); which is in another void above it. Anyway here is my coding or failed attempt at making this somewhat "work".
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;
namespace ArrayApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// ARRAY CODING / LIST CODING
public class Values
{
public string Position { get; set; } = string.Empty;
public string Name { get; set; } = string.Empty;
}
public void App()
{
var names = new List<string>();
}
// BUTTON CLICKS / BUTTON ACTION CODING
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
List_Box.Content = Add_Text.Text;
MessageBox.Show("Value Added");
Add_Text.Clear();
}
private void Search_Button_Click(object sender, RoutedEventArgs e)
{
}
// TEXT BOXES / WHAT BUTTON ACTUALLY INPUTS INTO OUR DISPLAY
private void Add_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void Search_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
// DISPLAY - List_Box not added yet
}
}
Let's walk through this. As you've already mentioned, you need something to store your data. List is a good idea since you don't know the size.
Currently, you're creating a List of the type string, that would work.
There's actually no need for the Values class because because you can get the index of an item with a function called IndexOf - but later more.
Now, once you show the MessageBox when adding an item, you also have to actually add it to your names list. In order to do so, declare the List in your class and initialize it in your constructor. That way you're able to access if from everywhere in your class.
private List<string> names;
public void MainWindow()
{
InitializeComponent();
names = new List<string>();
}
Adding items can be done with the .Add method, it's pretty straight forward.
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
List_Box.Content = Add_Text.Text;
MessageBox.Show("Value Added");
names.Add(Add_Text.Text); // Adding the content of Add_text.Text
Add_Text.Clear();
}
Searching for an item is pretty easy, too. Just use Contains if you want to know whether the item exists or IndexOf if you want to have the index as well. Note: IndexOf returns -1 if nothing can be found.
private void Search_Button_Click(object sender, RoutedEventArgs e)
{
if(names.Contains( SEARCH_TEXT.TEXT /* or wherever you get your pattern from */ )){
// found, display this in some way
} else {
// not found, display this is some way
}
}
SEARCH_TEXT.TEXT contains the pattern you're looking for. I don't know how you named your control, simply replace it.
That's pretty much it.
So, after doing some reading and also your comments helped a lot, I think I got hang of it and got some basic understanding of C# at least how it works logically. This is the "final" version of the AMAZING program I was trying to create. Thanks for the help everyone!
P.S. The comments are for me to learn and reference in the future when I'm learning C# or forget things :)
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;
/* QUICK TERMINOLOGY
List = An Array that constantly adjusts its maximum size
names = Our actual "database" or table with our values that we've inputted
List_Box = The display table that is visible on the program itself
var = Variable... You know...
"public" or "private" = Those define whether the function is visible to the rest of the program or other "sheets" in the program
void = Defines whether the return value or the output of a function should be something, void means not specified,
if you want string you put string, if you want an integer you put int... etc etc.
*/
namespace ArrayApp
{
public partial class MainWindow : Window
{
/* Private Function for Creating the List which will be a String
We are using a List instead of an Array as an Array needs
a specific amount of indexes so if we have a specific number of data or
a maximum amount of data that a user can input then array would be used
but since we don't know how many indexes we need a list will automatically
adjust the maximum size of our table to suit our needs. I.e. limitless */
private List<string> names;
public MainWindow()
{
InitializeComponent();
names = new List<string>();
}
/* Class for our Items in our list this is not referring the list above but...
the list that it displays as we have a search on demand
but also allows us to search for specific people in the List (array/table) rather than
display over 100+ people, if our database was to get to that size.
Our class function defines what data can be put into our Display List ( List_Box )
Therefore the index can only be an integer and name can only be a string
more on this later. */
class Items
{
public int Index { get; set; }
public string Name { get; set; }
}
/* The Add Button Function
This button takes the content of the TextBox that is right next to it and
adds it to our list called "names" but does not update our display, instead
it shows us a message stating that the value was added to the list.
If we were using an Array with a limited size, we could use an IF to check
if there is a space available and output a message saying "Full" or "Failed" */
private void Add_Button_Click(object sender, RoutedEventArgs e)
{
names.Add(Add_Text.Text); // Adds the value
Add_Text.Clear(); // Clears the text box
MessageBox.Show("Value Added"); // Displays a message
}
/* Firstly...
* We have an IF function that checks whether "names" contains the content
of the search box, so if its a letter "a", it checks if its in our list.
* It then creates a variable "SearchText" that we can later use that simply
means that instead of writing the whole code we can just refer to it by our new name
* Another variable! This one defines our Index in our list, it takes
our previous variable and looks for it in our list and finds what
the index number of that value is.
* Now, since its Search on demand we essentially have two Lists (arrays) now
that we have the name of the value we looking for in string format,
we also have our index as integer (defined earlier in class). We need to take that data
and add it to our display List and for that we have our function.
Adds new Items to our list using the Items Class and also defines
what data should be put into each column.
* It then clears the search text box
* and shows us that the value has been found.
We then move to ELSE which is simple really...
* Didn't find data
* Clears search text box
* Displays message that its not been found... */
private void Search_Button_Click(object sender, RoutedEventArgs e)
{
if (names.Contains(Search_Text.Text)) // Our If statement
{
var SearchText = Search_Text.Text; // First Variable
var FindIndex = names.IndexOf(SearchText); // Second Variable
List_Box.Items.Add(new Items() { Index = FindIndex, Name = SearchText}); // Adding items to display list
Search_Text.Clear(); // Clear search text box
MessageBox.Show("Data Found"); // Display message
}
else
{
Search_Text.Clear();
MessageBox.Show("Not Found");
};
}
/* Lastly a simple clear button for our display list.
* Once a user searches for many values and wants to clear the display list
* he can do it by hitting a single button.
*
* This button DOES NOT delete anything from our "names" list it only
* clears the display data meaning that the user can search for more data
* that has been added already. */
private void Clear_Button_Click(object sender, RoutedEventArgs e)
{
List_Box.Items.Clear();
}
private void Add_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void Search_Text_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
Here is how it looks, simple but you get the idea, I'm learning...
Please help me, I have ran into a problem. I'm new in UWP coding
problem : I have build a simple application which consists of a button. When the button is pressed it will display a message
Error : Cannot find typre System.Collections.CollectionBase in module CommonLanguageRuntimeLibrary
Here is my code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Windows.MessageBox;
using System.Windows.Forms;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("HI");
}
}
}
There is no MessageBox in UWP but there is a MessageDialog:
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Popups;
using System;
namespace App1
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
var dialog = new MessageDialog("Hi!");
await dialog.ShowAsync();
}
}
}
I strongly recommend you to use a separate, function to display a popup message.
UWP uses the namespace Windows.UI.Popups and not System.Windows.MessageBox, since it's only used for Win32 or WinForms applications
Here's a good way to display your desired message:
// Other namespaces (essential)
...
// Required namespaces for this process
using Windows.UI.Popups;
using System.Runtime.InteropServices;
namespace PopupMessageApp
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
// I will only comment those that are not obvious to comprehend.
private async void ShowMessage(string title, string content, [Optional] object[][] buttons)
{
MessageDialog dialog = new MessageDialog(content, title);
// Sets the default cancel and default indexes to zero. (incase no buttons are passed)
dialog.CancelCommandIndex = 0;
dialog.DefaultCommandIndex = 0;
// If the optional buttons array is not empty or null.
if (buttons != null)
{
// If there's multiple buttons
if (buttons.Length > 1)
{
// Loops through the given buttons array
for (Int32 i = 0; i < buttons.Length; i++)
{
/* Assigns text and handler variables from the current index subarray.
* The first object at the currentindex should be a string and
* the second object should be a "UICommandInvokedHandler"
*/
string text = (string)buttons[i][0];
UICommandInvokedHandler handler = (UICommandInvokedHandler)buttons[i][1];
/* Checks whether both variables types actually are relevant and correct.
* If not, it will return and terminate this function and not display anything.
*/
if (handler.GetType().Equals(typeof(UICommandInvokedHandler)) &&
text.GetType().Equals(typeof(string)))
{
/* Creates a new "UICommand" instance which is required for
* adding multiple buttons.
*/
UICommand button = new UICommand(text, handler);
// Simply adds the newly created button to the dialog
dialog.Commands.Add(button);
}
else return;
}
}
else
{
// Already described
string text = (string)buttons[0][0];
UICommandInvokedHandler handler = (UICommandInvokedHandler)buttons[0][1];
// Already described
if (handler.GetType().Equals(typeof(UICommandInvokedHandler)) &&
text.GetType().Equals(typeof(string)))
{
// Already described
UICommand button = new UICommand(text, handler);
// Already described
dialog.Commands.Add(button);
}
else return;
}
/* Sets the default command index to the length of the button array.
* The first, colored button will become the default button or index.
*/
dialog.DefaultCommandIndex = (UInt32)buttons.Length;
}
await dialog.ShowAsync();
}
private async void MainPage_Load(object sender, EventArgs e)
{
/* Single object arrays with a string object and a "UICommandInvokedHandler" handler.
* The ShowMessage function will only use the first and second index of these arrays.
* Replace the "return" statement with a function or whatever you desire.
* (The "return" statement will just return and do nothing (obviously))
* (Edit: Changed 'e' to 'h' in UICommandInvokedHandler's)
*/
object[] button_one = { "Yes", new UICommandInvokedHandler((h) => { return; }) };
object[] button_two = { "No", new UICommandInvokedHandler((h) => { return; }) };
/* Object arrays within an object array.
* The first index in this array will become the first button in the following message.
* The first button will also get a different color and will become the default index.
* For instance, if you press on the "enter" key, it will press on the first button.
* You can add as many buttons as the "Windows.UI.Popups.MessageDialog" wants you to.
*/
object[][] buttons = new object[][]
{
button_one,
button_two
};
// Displays a popup message with multiple buttons
ShowMessage("Title", "Content here", buttons);
/* Displays a popup message without multiple buttons.
* The last argument of the ShowMessage function is optional.
* because of the definition of the namespace "System.Runtime.InteropServices".
*/
ShowMessage("Title", "Content here");
// PS, I have a life, just trying to get points xD // BluDay
}
}
}
This way, you can display a message dialog with or without passing an object array with subarrays that contains of buttons. This method is extremely efficient. If you like this, make sure you fully understand it!
Okay. For the iLab my class and I are doing this week, we are working with GUIs. The second program we must design is a guessing game. The program is supposed to randomly generate a number, 0 through 100, and pass that number on to be used later. Here is the code I already have.
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;
namespace Guessing_game
{
public partial class Form1 : Form
{
int target();
public Form1()
{
InitializeComponent();
Random r = new Random();
int target = r.Next(0, 100);
}
private void btnEvaluate_Click(object sender, EventArgs e)
{
if (txtGuess.Text == target)
{
}
}
}
}
}
Mind you, the "btnEvaluate_Click" area is not done. This is because the variable "Target" that should be accessible by the program is unable to be read later on.
After reading through some of the comments, I was able to tweak the code so I get one more error: "Field 'Guessing_game.Form1.target' is never assigned to, and will always have its default value 0" IF anyone is going to try and replicate this, I can tell you exactly how to write it. The GUI should have a label, a text box, and a button. The button needs to get the value given to "target" so it can check the user's guess against target's value. I'm using Visual Studio 2010, if it helps.
Try this, You need to declare target public
Random r = new Random();
int target = r.Next(0, 100);
public Form1()
{
InitializeComponent();
}
private void btnEvaluate_Click(object sender, EventArgs e)
{
if (txtGuess.Text == target)
{
}
}
You have to put int target outside of the public Form(). Inside your event, change target to target.ToString().
The parentheses {} define a scope. You've declared the target variable within the scope of the constructor (Form1). Therefore, in order to make it accessible throughout the class, you can make it a class level variable. For example
int target;
public Form1()
{
InitializeComponent();
Random r = new Random();
target = r.Next(0, 100);
}
(Although if you plan to use the Random object again, you'd want to make that a class level variable as well). Also, you're trying to compare an int to a string. It should be
if (txtGuess.Text == target.ToString())
{
}
That's because target is local to the constructor and therefore can't be seen anywhere else. Make target a field in Form1 instead. Because this is homework, I'll let you try that out on your own; let us know if you're still stumped.
I try to play jpg (in loop), after click mp4 should be played after end, that jpg should play again. I dont know why but after I play in axWindowsMediaPlayer1_PlayStateChange vido play and then stop. Help.
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;
namespace Video
{
public partial class Form1 : Form
{
bool clicked = false;
public Form1()
{
InitializeComponent();
axWindowsMediaPlayer1.URL = "wait2.JPG";
}
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded & clicked== true)
{
clicked = false;
axWindowsMediaPlayer1.settings.setMode("Loop", true);
axWindowsMediaPlayer1.URL = "wait2.JPG";
axWindowsMediaPlayer1.Ctlcontrols.play();
}
}
private void axWindowsMediaPlayer1_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e)
{
axWindowsMediaPlayer1.settings.setMode("Loop", false);
axWindowsMediaPlayer1.URL = "video.MP4";
axWindowsMediaPlayer1.Ctlcontrols.play();
clicked = true;
}
}
}
I wish someone had replied to this question the time it was posted. It took me a lot of time to figure out why I was not able to start a new video by setting the URL property. I finally found the answer to this issue here:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd562470%28v=vs.85%29.aspx
The problem is with setting the URL property from within the axWindowsMediaPlayer1_PlayStateChange() event handler. According to the above msdn document:
"Do not call this method from event handler code. Calling URL from an event handler may yield unexpected results."
So the URL property has to be set outside of the even handler. I also tried Dispatcher.Invoke() and even starting a new thread from within the event handler to set the URL property; but that too did not help. It really has to come from outside of the event handler!