Silverlight new TouchPoint() causes a program crash - c#

I want to simulate TouchPoints in Silverlight. The following code already raises an unhandled Exception:
currentTouchPoints[i] = new TouchPoint();
currentTouchPoints[i].SetValue(TouchPoint.PositionProperty,
new Point(x[i]+100+i*100,y[i]+500));
The first call to new TouchPoint() makes the program crash.

i guess you are allowed to call the new TouchPoint(), but its TouchDevice would be not valid and all its properties are readonly, so it would be useless.
I haven't found a solution myself.
I'd create a custom class and use that one instead.
For example if you are using already the normal TouchPoint in your code and don't want to change everything, import this custom namespace instead of System.Windows.Input
namespace MyTouchPoint
{
class TouchPoint
{
public Point Position = new Point (0,0);
public TouchDevice TouchDevice = new TouchDevice();
TouchPoint (int id_, Point position_)
{
TouchDevice.Id = id_;
Position = position_;
}
};
class TouchDevice
{
public int Id = 0;
};
} // end namespace
cheers,
Lorenzo

Related

In WPF, how do I change the source of an image programatically? [duplicate]

This question already has answers here:
How to load image to WPF in runtime?
(2 answers)
Closed 1 year ago.
I have a custom control with a default image that I want to change based on which iteration of the control it is. For example, I have one for "F1" and "NumLock" and so on. In the constructor of the control, I have this:
public FixerBox(Dictionary<string,string> deets)
{
InitializeComponent();
btnOff();
this.FixerTitle.Text = deets["Title"];
this.FixerDesc.Text = deets["Description"];
this.FixerTags.Text = deets["Tags"];
this.FixerImg.Source = new BitmapImage(new Uri(deets["Img"], UriKind.Relative));
}
The bitmap stuff was based on another answer and produces this:
Below is the control itself showing that it's correctly getting the title, tags, and description, but the image is bunk (on the left side, that thin grey line is the border that should be around the image).c#
If I was using HTML/CSS, I could right-click the image to see what exactly its properties are, but I don't know how to get that kind of information using WPF. The best I could manage was in the top area is a status window where I've manually printed a "Tostring" output of the first controls image source data. Near as I can tell, it's all correct, but there's no actual image there. Every subsequent control has the same output (one thin line where the image should be).
EDIT Per comments, here is some more of the information. The main XAML file loads up the controls like so in its constructor:
public partial class MainWindow : Window
{
private Fixers fixers = new Fixers();
// This is the custom control consisting mostly of various boxes
private Dictionary<string,FixerBox> fixerBoxes = new Dictionary<string, FixerBox> { };
public MainWindow()
{
InitializeComponent();
var fixNames = fixers.FixerNames();
foreach (string key in fixNames)
{
fixerBoxes[key] = new FixerBox(fixers.GetFix(key));
FixersArea.Children.Add(fixerBoxes[key]);
}
StatusBox.Text += fixerBoxes["F1"].FixerImg.Source.ToString();
}
}
The fixers variable is of class Fixers which consists of the below (abbreviated to show just the F1 function for brevity):
class Fixers
{
private string ClearWS(string str)
{
var first = str.Replace(System.Environment.NewLine, "");
return first.Replace("\t", "");
}
// Loads registry functions
private Regis regStuff = new Regis();
// Loads preferences from the file
private Prefs prefs = new Prefs();
// A timer to make sure the system behaves
private Timer watcher;
// Watcher action toggles
private bool watchNumL = false;
// Translation array from fix shortname to various data about them
private Dictionary<string, Dictionary<string, string>> fixers = new Dictionary<string, Dictionary<string, string>>
{
["F1"] = new Dictionary<string,string> {
["PrefName"] = "KillF1UnhelpfulHelp",
["Img"] = #"/graphics/F1key.png",
["Title"] = #"Diable F1 ""Help"" function",
["Description"] = #"
Have you ever hit the F1 key by accident and had a distracting and unhelpful window or webpage open as a result?
Windows set the F1 key to a generic help function that basically never helps and always gets in the way.
Enable this control to disable that obnoxious design choice. Note that some programs still respond to F1 on their own accord,
but this will stop the default Windows behavior in things like Windows Explorer at least.
",
["Tags"] = "#Keyboard,#Rage"
},
};
public Fixers()
{
// The readability hack above with multi-line strings introduces a bunch of extra whitespace. Let's clear that out
foreach (var fixKey in fixers.Keys)
{
fixers[fixKey]["Description"] = ClearWS(fixers[fixKey]["Description"]);
}
}
public List<string> FixerNames()
{
return fixers.Keys.ToList();
}
public bool IsFixed(string which)
{
// If we're watching, it's fixed
if ("NumL" == which) return watchNumL;
// For anything registry related
return regStuff.IsFixed(which);
}
public Dictionary<string,string> GetFix(string which)
{
return fixers[which];
}
}
if you use binding, you can create in your ViewModel a string, in which is stored the path of your image, then you can easily change programatically its path.
Then in XAML just bind image's source to the string.
In my case I have a list of objects, with the property `ImageName' :
<Image Source="{Binding DataContext.SelectedMacro.ImageName,
RelativeSource={RelativeSource AncestorType=Window}}"/>

C# XNA if-else and defaulting to first value

So I am developing a custom ButtonGUI class for my game. Here's the initialization of the button object:
// Button code:
ButtonGUI btn1 = new ButtonGUI("Button 1", new Rectangle(150, 300, (int)myFont.MeasureString(menuButtons[0]).X, (int)myFont.MeasureString(menuButtons[0]).Y), myFont, Color.CornflowerBlue);
Now consider this code:
// Draw() method:
btn1.Draw(spriteBatch);
if (btnHover)
{
btn1.btnRect = new Rectangle(140, 300, (int)hoverFont.MeasureString(menuButtons[0]).X, (int)hoverFont.MeasureString(menuButtons[0]).Y);
btn1.btnFont = hoverFont;
btn1.btnColour = Color.Red;
}
else
{
btn1.btnRect = new Rectangle(150, 300, (int)myFont.MeasureString(menuButtons[0]).X, (int)myFont.MeasureString(menuButtons[0]).Y);
btn1.btnFont = myFont;
btn1.btnColour = Color.CornflowerBlue;
}
This would be OK if I had only 1 button... But if I have like 10 buttons or more? This really isn't what DRY suggests. I feel like I'm missing something, there must be a way to return button properties to their default values once the condition is no longer met without doing the whole thing manually, or is there? Thanks in advance!
It may make sense to create a structure to hold all of the values that may change.
class ButtonData
{
// put members corresponding to each member of ButtonGUI you wish
// to change
}
class ButtonSwapper
{
ButtonGUI myButton;
ButtonData hoverData;
ButtonData notHoverData;
void change(bool hover)
{
ButtonData dataToUse = hover ? hoverData : notHoverData;
// set each relevant member of myButton to its pair in
// dataToUse
}
}
then call change as necessary.

Calling a constructor within another constructor using 'this' as an argument

I have the following code
public Insight3DPluginControl(Insight3DPlugin plugin, MapViewModel viewModel)
: base(plugin)
{
InitializeComponent();
RXMouse = new RXMapMouse(this);
eob_tool = new EOBTool(RXMouse);
}
and I've been trying to wrap my head around the use of 'this' in new RXMapMouse() that is being called by 'this's constructor. I'm trying to understand the reason for doing this and what the design pattern would be called.
I understand that the object before being passed to RXMapMouse() is already initialized, but does that mean by changing the current Insight3DPluginControl object when we assign the RXMouse field, will then change the one inside of RXMapMouse()?
The "this" keyword is a "variable" representing the current object.
Maybe this ( :D ) will let you undestand it better:
public Insight3DPluginControl(Insight3DPlugin plugin, MapViewModel viewModel)
: base(plugin)
{
InitializeComponent();
Insight3DPluginControl theControl = this;
RXMouse = new RXMapMouse(theControl);
eob_tool = new EOBTool(RXMouse);
}
So, basically the "RXMapMouse" needs an instance of an "Insight3DPluginControl" int it's constructor and in that line the current Insight3DPluginControl where the code lives is being sent.

How to read a stack.peek in order to put it in an if statement C#

I am trying to create a menu system and i am storing the menus in stacks once they have already been visited. Im trying to use Stack.Peek() to basically say: if menuName = menuStack.Peek, then continue.
menus have a drawRectangle, sprite, and Menuname enumeration associated with them, and all menus are child classes of the Menu class.
public static void GoToMenu(MenuName menuName)
{
Stack<Menu> menuStack = new Stack<Menu>();
Stack<Menu> tempStack = new Stack<Menu>();
if(menuStack.Peek() = MainMenu){
}
}
More or less, if menuStack.Peek returns a mainMenu object. How do i check that?
i just really dont know how to read menuStack.Peek(). I dont know how to apply it to an if statement to check if it equals a mainmenu object, a pausemenu object or whatever.
public static void GoToMenu(MenuName menuName)
{
Stack<Menu> menuStack = new Stack<Menu>();
Stack<Menu> tempStack = new Stack<Menu>();
if(menuStack.Peek().Name == menuName){
menuStack.Pop();
}
}
that is what i needed

Editing properties of a PictureBox from another class

Context: I am trying to make a little game of Backgammon in Windows.Forms. I have 3 classes GameBoard.cs, Points.cs and Checkers.cs (as well as Form1.cs). What I need to be able to do is change values of some properties of a PictureBox using some of my other classes.
Specifically I have this code:
// gameBoard.cs
namespace backgammon
{
public class gameBoard
{
Checker checker1;
Points point1;
Points[] pointsArray;
public gameBoard()
{
// make new checker (ID, PictureBox, startingPoint)
checker1 = new Checker(1, checkerPicBox1, 1);
// make new Point (ID, arrayOfCheckers)
point13 = new Points(1, new Checker[]{checker1 /*,checker2... etc*/});
pointsArray = new Points[MAX_POINTS];
pointsArray[0] = point1;
}
}
}
so this is how I have "setup" the checkers and points. My checker and point classes can get and set on all variables that were passed into its construction.
Problem: what I am trying to achieve is to "highlight" a checker once it is clicked.
In Form1:
// Form1.cs
private void checkerPicBox1_Click(object sender, EventArgs e)
{
int pointNumber = gameBoard.checker1.getPointMember();
// find the top most checker in the checker array so we can highlight it
Checker topMost = gameBoard.pointsArray[pointNumber - 1].getCheckerFromIndex(gameBoard.pointsArray[pointNumber - 1].getCheckerArray().Length - 1);
// get the picturebox and change the image
topMost.getPictureBox().BackgroundImage = global::Backgammon.Properties.Resources.blackCheckerSelected;
}
The code compiles and runs but when it gets to the last line of checkerPicBox_Click nothing seems to happen (the image doesn't change).
What is happening here? Do I not have the correct instance of my PictureBox? Or am I doing this in a weird way/not the way i'm supposed to be?
Since the checkers are connected to the pictureboxes, why not create a new reference property for them in the Checker class?
You could pass the form containing the pictureboxes in the constructor, and use the form to create your references to the right picturebox instances.
// gameBoard.cs
namespace backgammon
{
public class gameBoard
{
Checker checker1;
Points point1;
Points[] pointsArray;
public gameBoard(Form gameForm)
{
// make new checker (ID, PictureBox, startingPoint)
checker1 = new Checker(1, gameForm.checkerPicBox1, 1);
// make new Point (ID, arrayOfCheckers)
point13 = new Points(1, new Checker[]{checker1 /*,checker2... etc*/});
pointsArray = new Points[MAX_POINTS];
pointsArray[0] = point1;
}
}
}
Add the picturebox property to your Checker class:
// checker.cs
public class Checker
{
PictureBox _picturebox;
//... other code here
public Checker(int ID, PictureBox picturebox, Points startingPoint)
{
_picturebox = picturebox;
//...other code here
}
}
Then we can use this in the game form:
gameBoard gameBoard1 = new gameBoard(this);
gameBoard1.checker1._picturebox.BackgroundImage = global::Backgammon.Properties.Resources.blackCheckerSelected;
gameBoard1.checker1._picturebox.Invalidate();

Categories