moving objects withe key - diagonal - wpf

I need to move an object, I can move it up down and sideways, but fails in a diagonal, it is the way I made my move.
if (e.Key == Key.Up && Canvas.GetTop(Good) > 31)
{
double top = Canvas.GetTop(Good);
Canvas.SetTop(Good, top - 7);
}
if (e.Key == Key.Down && Canvas.GetTop(Good) < CanvasA.ActualHeight - 7 - Good.Height)
{
double down = Canvas.GetTop(Good);
Canvas.SetTop(Good, down + 7);
}
if (e.Key == Key.Left && Canvas.GetLeft(Good) > -2)
{
double left = Canvas.GetLeft(Good);
Canvas.SetLeft(Good, left - 7);
}
if (e.Key == Key.Right && Canvas.GetLeft(Good) < CanvasA.ActualWidth - Good.Width)
{
double right = Canvas.GetLeft(Good);
Canvas.SetLeft(Good, right + 7);
}
}
}
Everything works but can not click on the two buttons to move the character in a diagonal,
The reason that there is less than 31, it's because I did Menu in WPF.

Related

Swipe over table in mobile browser

I and my teammate are writing the game "Battlecity" in dart for mobile browser. The problem is with swipes for tank direction(left to right, right to left, etc) in mobile browser. It works with a great delation(and for some reasond doesn't works in Chrome-Browser).
You can see the problem better, if you start the game on your mobile device(just open link with game: https://javajunikorn.github.io/BattleCity/build/web/html/test.html)
Interesting thing is, that the problem exists only on swipes over gamefield(in our case it's 27*27 html table). If we're swiping out of gamefeeld, than it works great.
Here is code of our Controller:
class Direction{
Point first, last;
Game game;
void startListening(){
window.onTouchStart.listen((ev) {
last = null;
first = ev.touches.first.client;
});
window.onTouchMove.listen((ev){
last = ev.touches.first.client;
});
window.onTouchEnd.listen((ev) {
if(last == null || first.distanceTo(last) < 20)
game.player.shoot();
else {
Point d = first - last;
if(d.x.abs() > d.y.abs()){
//Waagerecht
if( first.x > last.x){
//links
game.player.changeDirection(Directions.left);
}
else{
//rechts
game.player.changeDirection(Directions.right);
}
}
else{
//Senkrecht
if(first.y > last.y){
//Up
game.player.changeDirection(Directions.up);
}
else{
//Down
game.player.changeDirection(Directions.down);
}
}
}
});
window.onKeyPress.listen((k) {
//Shoot
if(k.which == 32) { //spacebar
game.player.shoot();
}
//Up
if(k.which == 119 || k.keyCode == KeyCode.UP){
game.player.changeDirection(Directions.up);
}
//Down
if(k.which == 115 || k.keyCode == KeyCode.DOWN){
game.player.changeDirection(Directions.down);
}
//Left
if(k.which == 97 || k.keyCode == KeyCode.LEFT){
game.player.changeDirection(Directions.left);
}
//Right
if(k.which == 100 || k.keyCode == KeyCode.RIGHT){
game.player.changeDirection(Directions.right);
}
});
}
}

ng-pattern for mobile number validation

I am trying to implement mobile number validation on a Visualforce page using Angular JS, but am having problems getting my head around how to write the regex expression.
The requirements, as given to me, are fairly simple:
The number should be 10 digits long (I've already set the maxlength attribute on the field so this one is kind of taken care of already)
It should start with 04 (as it is an Australian mobile)
Only numbers should be allowed.
The regex expression I am using (in the ng-pattern attribute for my phone number input field) is:
^/(04)[0-9]{10}/$
This works up to a point - it does not allow anything other than numbers and does let me enter a 10 digit number starting with 04. However it also lets me enter numbers starting with, for example, 02, 03 etc....
Probably quite a simple thing I'm missing but I've had a look at quite a few sites, including this one, and can't find the answer.
Any help would be hugely appreciated as this one has caused me a few grey hairs already.
Try using this pattern
Use this in ur HTML file:
<input type="text" (keypress)="keyPress($event)" minlength=10 maxlength=10>
Use this in ur JS file:
keyPress(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.charCode);
if (event.keyCode != 8 && !pattern.test(inputChar)) {
event.preventDefault();
}
}
Try this one:
Mobile Number :
//inside view:
<input type="text" class="form-control" ng-model="mobileNo" name="mobileNo" ng-pattern="regEx" />
//inside controller:
$scope.regEx="/^[0-9]{10,10}$/";
For starters I had to create a whole js function for it... and it does validates as you type. here is my full code I hope this can help you get where you need.
This function gets the string every time a key is beign pressed and it allows the carrete to move front, back, delete and backspace. check it out and let me know if it helps you. you can run it on any situation and this is how I would add the "04" validation
//phone validation 10 digits and parenthesis (344)567-0011
function validatePhone(inputId) {
let validKey = false;
const input = document.getElementById(inputId);
let enteredDigits = input.value;
//switch to remove the country code added by default on autoComplete forms.
if (enteredDigits.length > 10 && enteredDigits[0] == '+') {
switch (enteredDigits.length) {
case 12:
enteredDigits = enteredDigits.slice(2);
break;
case 13:
enteredDigits = enteredDigits.slice(3);
break;
case 14:
enteredDigits = enteredDigits.slice(4);
break;
default:
enteredDigits = enteredDigits.replace(/\D+/g, '');
}
}
let newPhone = enteredDigits.replace(/\D+/g, ''); // This replace any character that is not a number.
const key = event.keyCode || event.charCode; // Get the pressed key.
let caretPosition = input.selectionStart; // get the carret position.
// splits, removes the "-" and converts from array to string and gives the needed digits.
const areaCode = newPhone.split('').splice(0, 3).toString().replace(/,/g, '');
const threeDigit = newPhone.split('').splice(3, 3).toString().replace(/,/g, '');
const fourDigit = newPhone.split('').splice(6, 8).toString().replace(/,/g, '');
// Moving carret on different positions. when the numeric keys are being pressed.
// Key >= 48 && key <= 58 number keys.
// Key >= 96 && key <= 105 numeric path number keys.
if ((key >= 48 && key <= 58) || (key >= 96 && key <= 105)) {
validKey = true;
if (threeDigit.length > 0) {
if (caretPosition == 1) {
caretPosition = caretPosition + 1;
} else if (caretPosition == 4 && newPhone.length == 4) {
caretPosition = caretPosition + 2;
} else if (caretPosition == 4 && newPhone.length >= 5) {
caretPosition = caretPosition + 1;
} else if (caretPosition == 5) {
caretPosition = caretPosition + 1;
} else if (caretPosition >= 2 && caretPosition <= 3 && newPhone.length <= 4) {
caretPosition = caretPosition + 1;
}
}
if (fourDigit.length > 0 && caretPosition == 9) {
caretPosition = caretPosition + 1;
}
}
// Key = 8 = Backspace.
else if (key == 8) {
validKey = true;
if (caretPosition == 3 && newPhone.length == 3) {
caretPosition = caretPosition - 1;
} else if (caretPosition == 2 && newPhone.length == 3) {
caretPosition = caretPosition - 1;
} else if (caretPosition == 1 && newPhone.length == 3 && threeDigit.length == 0) {
caretPosition = caretPosition - 1;
}
}
// Key = 46 = Delete. Key =37 = ArrowLeft. Key = 39 = ArrowRight.
else if (key == 46 || key == 39 || key == 37) {
validKey = true;
// Delete
if (key == 46) {
if (caretPosition == 0 && newPhone.length > 3) {
caretPosition = caretPosition + 1;
} else if (caretPosition == 1 && newPhone.length == 3) {
caretPosition = caretPosition - 1;
} else if (caretPosition == 2 && newPhone.length == 3) {
caretPosition = caretPosition - 1;
} else if (caretPosition == 3 && newPhone.length == 3) {
caretPosition = caretPosition - 1;
} else if ((newPhone.length >= 4 && caretPosition == 4) || (newPhone.length >= 4 && caretPosition == 8)) {
caretPosition = caretPosition + 1;
}
}
}
//here is the validation for the country that you need.
if ((newPhone.length == 1 && newPhone[0] != '0') || (newPhone.length >= 2 && newPhone[1] != '4')) {
alert('Must start with 04');
newPhone = '';
}
// Adding the special character for formatting.
if (threeDigit.length > 0 && fourDigit.length == 0) {
newPhone = '(' + areaCode + ')' + threeDigit;
} else if (fourDigit.length > 0 && threeDigit.length == 3) {
newPhone = '(' + areaCode + ')' + threeDigit + '-' + fourDigit;
}
if (!validKey) {
caretPosition = caretPosition - 1;
}
// Set new values.
newPhone = newPhone.substring(0, 13);
input.value = newPhone;
input.focus();
input.setSelectionRange(caretPosition, caretPosition);
}
<form name="myForm"
onsubmit="return validateForm()"
method="post">
Phone number: <input type="text"
id="phoneNumber"
name="fPhone"
onkeyup="validatePhone('phoneNumber')">
<input type="submit"
value="Submit">
</form>

D3 import .csv to 2Darray & opacity change when hover

I'm currently writing a visualization via D3 and I hope you can help me out.
To get an idea of what I'm making you can view this link: https://dl.dropboxusercontent.com/u/56480311/Data-visualization/index.html
I'm facing two problems: the first is that I can't seem to place .csv data in a 2D array. I found multiplie tutorials about placing it in a normal array but the only solution I came up with if your data is in a table, is to use a 2D array. I couldn't find how to do this so what I thought would help:
var lines = []; //define lines as an array
//retrieve data from .csv file
d3.csv("https://dl.dropboxusercontent.com/u/56480311/Data-visualization/growth-prep.csv", function(data) {
lines = data.map(function(d) {
return d;
});
});
//create 2D array named myArray
var myArray = new Array(10);
for (var i = 0; i < 10; i++) {
myArray[i] = new Array(18);
}
//place each value of .csv file into myArray
for (var j = 0; j < lines.length; j++) {
var values = lines[j].split(";");
for (var k = 0; k < values.length; k++) {
myArray[k][j] = values[k];
}
}
This code doesn't work, however. Console keeps saying that the arrays are undefined and they're empty.
A second problem I'm facing is in visualizing the data. I sum three values that are next to each other (so for example dataset[0][0] + dataset[0][1] + dataset[0][2]). I draw this value as the width of a rectangle. On top of that, I want to draw three different rectangles each with the value of one of three. So in this case there is one rectangle consisting of dataset[0][0] + dataset[0][1] + dataset[0][2] and on top there is a rectangle showing data dataset[0][0], one showing data dataset[0][1] and a third showing data dataset[0][2]. I want the three smaller ones only to appear once the mouse hovers over the 'sum' / parent rectangle.
If you view the link you can see what I mean. Everything is already there, only the three smaller rectangles have opacity 0 so you don't see them yet (but you can find them via inspect elements).
I figured I could do this by setting the opacity of the three rectangles to 0 and to 1 once the mouse hovers. The best solution to me would be to place the three rectangles into one kind of div. Once the mouse hovers over it, its opacity is 1. Only I can't figure out how to easily give different class names without having to do it by hand for each rectangle separately. Does anyone know how to do this or else have a better solution to change the opacity of all three rectangles once the mouse hovers over the 'bigger' rectangle?
This is the code:
var dataset = [[6,6,3,3,3,0,6,6,0,12,6,6,0,0,18,6,3,3],[3,0,0,6,3,0,3,3,0,9,3,0,0,0,18,6,6,6],[3,0,3,6,3,3,6,0,3,9,6,3,0,0,15,6,6,6],[6,6,3,3,0,3,6,6,6,12,6,6,0,0,18,6,6,3],[6,6,0,6,0,0,6,6,6,12,6,6,0,0,24,6,6,0],[3,6,3,6,3,3,6,6,3,3,0,0,0,0,15,3,9,6],[3,3,0,3,0,3,3,3,3,9,3,0,0,0,15,6,3,9],[0,0,0,3,0,6,6,3,3,3,0,3,0,0,24,6,12,6],[6,6,3,6,0,0,9,9,6,12,6,6,0,0,15,3,3,3],[6,6,0,6,3,0,6,6,0,9,6,3,0,0,9,3,6,0]];
var h = 800;
var w = 800;
//create svg of 800x800px
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var xPos = 150;
for (var k = 0; k < 10; k++) { //loop through lines of array
var yPos = 40 + k*80;
for (var j = 0; j < 18; j++) { //loop through rows of array
var count = j + 1;
//assign data of three boxes to value1/value2/value3 with which we will later on draw three separate rectangles to visualize the data
if (count == 1 || count == 4 || count == 7 || count == 10 || count == 13 || count == 16) {
var value1 = dataset[k][j];
}
if (count == 2 || count == 5 || count == 8 || count == 11 || count == 14 || count == 17) {
var value2 = dataset[k][j];
}
if (count == 3 || count == 6 || count == 9 || count == 12 || count == 15 || count == 18) {
var value3 = dataset[k][j];
}
if (count % 3 ==0) {
var sum = dataset[k][j] + dataset[k][j-1] + dataset[k][j-2]; //count the three values to also draw one bigger rectangle of their sum
var rectangle = svg.append("rect")
.attr("x", xPos)
.attr("y", yPos)
.attr("width", sum*5)
.attr("height", 20)
.attr("fill", function(d) {
if (count == 3) {
return "LightSeaGreen";
}
else if (count == 6) {
return "MediumSeaGreen";
}
else if (count == 9) {
return "MediumSpringGreen";
}
else if (count == 12) {
return "LimeGreen";
}
else if (count == 15) {
return "ForestGreen"
}
else if (count == 18) {
return "GreenYellow"
}
});
for (var l = 0; l < 3; l++) { //draw three 'sub' rectangles on top of the one 'sum' rectangle. they should appear when the mouse hovers over their 'sum' rectangle
var rectangle2 = svg.append("rect")
.attr("class", "sqr")
.attr("x", function() {
if (l == 0) {
return xPos;
} else if (l == 1) {
return xPos + value1*5;
} else if (l == 2) {
return xPos + (value1+value2)*5;
}
})
.attr("y", yPos)
.attr("width", function() {
if (l == 0) {
return value1*5;
} else if (l == 1) {
return value2*5;
} else if (l == 2) {
return value3*5;
}
})
.attr("height", 20)
.attr("fill", function() {
if (l == 0) {
return "SteelBlue";
} else if (l == 1) {
return "aquamarine";
} else if (l == 2) {
return "SkyBlue";
}
})
.attr("opacity", 0); //in first instance the rectangles are not visible. Opacity should turn to 1 when the mouse hovers over their according div
}
if (sum > 0) {
xPos = xPos + sum*5 + 5;
}
}
}
xPos = 150;
}

Hook CTRL+ALT+TAB

I've made a WPF application and I was able to hook some of the windows combinations. ALT+TAB is hooked and it is doing nothing when my application is running (as expected). The problem is when I press the CTRL+ALT+TAB I get the same effect as ALT+TAB.
Do you guys have any idea on how to hook this kind of combination?
EDIT:
I have already successfully hooked ALT+TAB. I do want to hook CTRL+ALT+TAB. I've tried this project example to make this happen.
Here's the code that makes the hook:
private static IntPtr KeyboardHookHandler(int nCode, IntPtr wParam,
ref KBHookStruct lParam){
if (nCode == 0)
{
if (((lParam.vkCode == 0x09) && (lParam.flags == 0x20)) || // Alt+Tab
((lParam.vkCode == 0x1B) && (lParam.flags == 0x20)) || // Alt+Esc
((lParam.vkCode == 0x1B) && (lParam.flags == 0x00)) || // Ctrl+Esc
((lParam.vkCode == 0x5B) && (lParam.flags == 0x01)) || // Left Windows Key
((lParam.vkCode == 0x5C) && (lParam.flags == 0x01)) || // Right Windows Key
((lParam.vkCode == 0x73) && (lParam.flags == 0x20)) || // Alt+F4
((lParam.vkCode == 0x20) && (lParam.flags == 0x20))) // Alt+Space
{
return new IntPtr(1);
}
}
return CallNextHookEx(hookPtr, nCode, wParam, ref lParam);}
Answer 1
You can try like below it work for CTRL + SHIFT + TAB and CTRL + TAB
private void HandleKeyDownEvent(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab && (Keyboard.Modifiers & (ModifierKeys.Control | ModifierKeys.Shift)) == (ModifierKeys.Control | ModifierKeys.Shift))
{
MessageBox.Show("CTRL + SHIFT + TAB trapped");
}
if (e.Key == Key.Tab && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
MessageBox.Show("CTRL + TAB trapped");
}
}
Answer 2
should look something like:
((lParam.flags & 33 == 33) && (lParam.flags & 22 == 22))
32 and 22 are arbitrary in this example. You need to figure out what values ALT and CTRL actually are. They will be 1, 2, 4 ... 16, 32 etc. so that they can be OR'ed together into a single value.

WinForms TreeView with both radios and checkboxes

I have a case where I would like TreeView to be able to show radio buttons on multiple root nodes, and checkboxes on their children. There would only be one level of children beneath any root node.
The radios should also behave like a group, ie one root is selected and the others' radios deselect.
I've been trying to fake it with images, but it doesn't look realistic. I originally had a listbox and a separate checkedlistbox, but the usability gods struck it down.
Has anyone implemented this functionality or have another suggestion?
Think of it this way:
(o) McDonalds
[ ] Burger
[ ] Fries
[ ] Drink
(o) Burger King
[ ] Burger
[ ] Fries
[ ] Drink
(*) Wendy's
[x] Burger
[x] Fries
[ ] Drink
You can have one big option, but select 1..n underneath the big option.
I came up with a solution based on the article http://www.codeproject.com/KB/combobox/RadioListBoxDotNetVersion.aspx. My implementation inherits from CheckedListBox and includes the following methods:
protected override void OnDrawItem (DrawItemEventArgs e)
{
// Erase all background if control has no items
if (e.Index < 0 || e.Index > this.Items.Count - 1)
{
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
return;
}
// Calculate bounds for background, if last item paint up to bottom of control
Rectangle rectBack = e.Bounds;
if (e.Index == this.Items.Count - 1)
rectBack.Height = this.ClientRectangle.Top + this.ClientRectangle.Height - e.Bounds.Top;
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), rectBack);
// Determines text color/brush
Brush brushText = SystemBrushes.FromSystemColor(this.ForeColor);
if ((e.State & DrawItemState.Disabled) == DrawItemState.Disabled || (e.State & DrawItemState.Grayed) == DrawItemState.Grayed)
brushText = SystemBrushes.GrayText;
Boolean bIsChecked = this.GetItemChecked(e.Index);
String strText;
if (!string.IsNullOrEmpty(DisplayMember)) // Bound Datatable? Then show the column written in Displaymember
strText = ((System.Data.DataRowView) this.Items[e.Index])[this.DisplayMember].ToString();
else
strText = this.Items[e.Index].ToString();
Size sizeGlyph;
Point ptGlyph;
if (this.GetItemType(e.Index) == ItemType.Radio)
{
RadioButtonState stateRadio = bIsChecked ? RadioButtonState.CheckedNormal : RadioButtonState.UncheckedNormal;
if ((e.State & DrawItemState.Disabled) == DrawItemState.Disabled || (e.State & DrawItemState.Grayed) == DrawItemState.Grayed)
stateRadio = bIsChecked ? RadioButtonState.CheckedDisabled : RadioButtonState.UncheckedDisabled;
// Determines bounds for text and radio button
sizeGlyph = RadioButtonRenderer.GetGlyphSize(e.Graphics, stateRadio);
ptGlyph = e.Bounds.Location;
ptGlyph.X += 4; // a comfortable distance from the edge
ptGlyph.Y += (e.Bounds.Height - sizeGlyph.Height) / 2;
// Draws the radio button
RadioButtonRenderer.DrawRadioButton(e.Graphics, ptGlyph, stateRadio);
}
else
{
CheckBoxState stateCheck = bIsChecked ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal;
if ((e.State & DrawItemState.Disabled) == DrawItemState.Disabled || (e.State & DrawItemState.Grayed) == DrawItemState.Grayed)
stateCheck = bIsChecked ? CheckBoxState.CheckedDisabled : CheckBoxState.UncheckedDisabled;
// Determines bounds for text and radio button
sizeGlyph = CheckBoxRenderer.GetGlyphSize(e.Graphics, stateCheck);
ptGlyph = e.Bounds.Location;
ptGlyph.X += 20; // a comfortable distance from the edge
ptGlyph.Y += (e.Bounds.Height - sizeGlyph.Height) / 2;
// Draws the radio button
CheckBoxRenderer.DrawCheckBox(e.Graphics, ptGlyph, stateCheck);
}
// Draws the text
Rectangle rectText = new Rectangle(ptGlyph.X + sizeGlyph.Width + 3, e.Bounds.Y, e.Bounds.Width - sizeGlyph.Width, e.Bounds.Height);
e.Graphics.DrawString(strText.Substring(4), e.Font, brushText, rectText, this.oAlign);
// If the ListBox has focus, draw a focus rectangle around the selected item.
e.DrawFocusRectangle();
}
protected override void OnItemCheck (ItemCheckEventArgs ice)
{
base.OnItemCheck(ice);
if (ice.NewValue == CheckState.Unchecked)
return;
if (this.GetItemType(ice.Index) == ItemType.Radio) // if they selected a root, deselect other roots and their children
{
for (Int32 i = 0; i < this.Items.Count; ++i)
{
if (i == ice.Index)
continue;
if (this.GetItemType(i) == ItemType.Radio)
{
this.SetItemChecked(i, false);
Int32 j = i + 1;
while (j < this.Items.Count && this.GetItemType(j) == ItemType.Checkbox)
{
this.SetItemChecked(j, false);
j++;
}
}
}
}
else if (this.GetItemType(ice.Index) == ItemType.Checkbox) // they selected a child; select the root too and deselect other roots and their children
{
// Find parent
Int32 iParentIdx = ice.Index - 1;
while (iParentIdx >= 0 && this.GetItemType(iParentIdx) == ItemType.Checkbox)
iParentIdx--;
this.SetItemChecked(iParentIdx, true);
}
}
protected ItemType GetItemType (Int32 iIdx)
{
String strText = this.Items[iIdx].ToString();
if (strText.StartsWith("(o)"))
return (ItemType.Radio);
else if (strText.StartsWith("[x]"))
return (ItemType.Checkbox);
throw (new Exception("Invalid item type"));
}

Resources