WP7: Suppressing XNA touch input when handled by Silverlight? - silverlight

I've got an XNA + Silverlight game in Mango: Mostly XNA with some Silverlight UI on top. The problem I'm having is that when you hit a button or interact with a Silverlight control, the touch information is still passed along to the XNA game loop. How do you suppress this?

Wrote up a class to do the tracking for me. After your page loads (in the Loaded handler), create this and give it the root element (so it can attach to the LayoutUpdated event). Register any controls that might overlay the game surface during play. Then just call TouchesControl and pass in the touch position to find out if you should ignore that point or not. It caches the regions of the controls and updates them when there's a layout update.
Should work for rectangular elements moving, changing size or collapsing/expanding.
public class ControlTouchTracker
{
private List<FrameworkElement> controls = new List<FrameworkElement>();
private Dictionary<FrameworkElement, ControlRegion> controlBounds = new Dictionary<FrameworkElement, ControlRegion>();
public ControlTouchTracker(FrameworkElement rootElement)
{
rootElement.LayoutUpdated += this.OnLayoutUpdated;
}
public void RegisterControl(FrameworkElement control)
{
controls.Add(control);
}
public void RemoveControl(FrameworkElement control)
{
controls.Remove(control);
controlBounds.Remove(control);
}
private void OnLayoutUpdated(object sender, EventArgs e)
{
foreach (Control control in this.controls)
{
this.RefreshControlBounds(control);
}
}
private void RefreshControlBounds(FrameworkElement control)
{
if (this.ControlIsVisible(control))
{
try
{
GeneralTransform controlTransform = control.TransformToVisual(Application.Current.RootVisual);
Point offset = controlTransform.Transform(new Point(0, 0));
this.controlBounds[control] = new ControlRegion
{
Left = (float)offset.X,
Right = (float)(offset.X + control.ActualWidth),
Top = (float)offset.Y,
Bottom = (float)(offset.Y + control.ActualHeight)
};
}
catch (ArgumentException)
{
}
}
else
{
if (this.controlBounds.ContainsKey(control))
{
this.controlBounds.Remove(control);
}
}
}
private bool ControlIsVisible(FrameworkElement control)
{
// End case
if (control == null)
{
return true;
}
if (control.Visibility == Visibility.Collapsed)
{
return false;
}
return this.ControlIsVisible(control.Parent as FrameworkElement);
}
public bool TouchesControl(Vector2 touchPosition)
{
foreach (ControlRegion region in this.controlBounds.Values)
{
if (touchPosition.X >= region.Left && touchPosition.X <= region.Right &&
touchPosition.Y >= region.Top && touchPosition.Y <= region.Bottom)
{
return true;
}
}
return false;
}
public class ControlRegion
{
public float Left { get; set; }
public float Right { get; set; }
public float Top { get; set; }
public float Bottom { get; set; }
}
}
(edit) Updated example to work with parent elements changing Visibility.

Due to the way interop with XNA works, you will always get the touch input processed both by XNA and Silverlight - to some extent, XNA gets the priority, so the Silverlight acts on top of that. What you could do, if you need to ignore specific gesture locations (e.g. where Silverlight buttons are located), you could check the gesture position:
if (TouchPanel.IsGestureAvailable)
{
if (TouchPanel.ReadGesture().GestureType == GestureType.Tap)
{
if (TouchPanel.ReadGesture().Position == new Vector2(120, 120))
{
}
}
}

Related

How to pop to root

I am writing a WPF application with MvvmCross. I have a custom view presenter that I want to use so that I can pop multiple view models in 1 shot. Here is my view presenter:
public class ViewPresenter : MvxWpfViewPresenter
{
ContentControl _contentControl;
Type _currentViewModelType;
IMvxViewModel _rootViewModel;
public ViewPresenter(ContentControl c) : base(c)
{
_contentControl = c;
AddPresentationHintHandler<SetRootHint>(SetRootHintHandler);
AddPresentationHintHandler<PopToRootHint>(PopToRootHintHandler);
}
protected override void ShowContentView(FrameworkElement element, MvxContentPresentationAttribute attribute, MvxViewModelRequest request)
{
base.ShowContentView(element, attribute, request);
_currentViewModelType = request.ViewModelType;
}
private bool SetRootHintHandler(SetRootHint hint)
{
_rootViewModel = hint.CurrentViewModel;
return true;
}
private bool PopToRootHintHandler(PopToRootHint hint)
{
// How to pop all the way down to _rootViewModel ?
return true;
}
}
How can I pop all the way back to _rootViewModel? Is there a better way of popping back multiple view models in one shot?
I ended up writing a helper class that keeps a reference of all the view models, as well as the one you set as the Root. And then I can just call my PopToRoot method.
public class NavigationStack
{
private readonly List<IMvxViewModel> _stack;
public IMvxViewModel Root { get; set; }
public NavigationStack()
{
_stack = new List<IMvxViewModel>();
}
public void AddToStack(IMvxViewModel viewModel)
{
_stack.Add(viewModel);
}
public async Task PopToRoot(IMvxNavigationService navigationService)
{
if (Root == null)
{
throw new Exception("Can not pop to root because Root is null.");
}
else
{
_stack.Reverse();
foreach (var v in _stack)
{
if (v != Root)
{
await navigationService.Close(v);
}
else
{
break;
}
}
_stack.Clear();
}
}
}
It works, but I'm not sure if this is a good idea since I'm keeping a reference to all the IMvxViewModel in my app, and closing them one after another...does anyone know if this code can cause any problems in the framework?

Transparency in animator control

I'm writing a user control for animation.
Its uses an internal ImageList to store the animation images and paint one after the other in a loop.
This is the whole code:
public partial class Animator : UserControl
{
public event EventHandler OnLoopElapsed = delegate { };
private ImageList imageList = new ImageList();
private Timer timer;
private bool looping = true;
private int index;
private Image newImage;
private Image oldImage;
public Animator()
{
InitializeComponent();
base.DoubleBuffered = true;
timer = new Timer();
timer.Tick += timer_Tick;
timer.Interval = 50;
}
public bool Animate
{
get { return timer.Enabled; }
set
{
index = 0;
timer.Enabled = value;
}
}
public int CurrentIndex
{
get { return index; }
set { index = value; }
}
public ImageList ImageList
{
set
{
imageList = value;
Invalidate();
index = 0;
}
get { return imageList; }
}
public bool Looping
{
get { return looping; }
set { looping = value; }
}
public int Interval
{
get { return timer.Interval; }
set { timer.Interval = value; }
}
private void timer_Tick(object sender, EventArgs e)
{
if (imageList.Images.Count == 0)
return;
Invalidate(true);
index++;
if (index >= imageList.Images.Count)
{
if (looping)
index = 0;
else
timer.Stop();
OnLoopElapsed(this, EventArgs.Empty);
}
}
protected override void OnPaintBackground(PaintEventArgs e)
{
if (oldImage != null)
e.Graphics.DrawImage(oldImage, ClientRectangle);
else
e.Graphics.Clear(BackColor);
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
if (imageList.Images.Count > 0)
{
newImage = imageList.Images[index];
g.DrawImage(newImage, ClientRectangle);
oldImage = newImage;
}
else
{
e.Graphics.Clear(BackColor);
}
}
}
The animation seems very nice and smooth,
but the problem is that its surrounding rectangle is painted black.
What am I missing here?
I've seen very smooth transparent animation done here in WPF,
I've placed some label behind it and they are seen thru the rotating wheel as I hoped.
But I don't know WPF well enough to build such a control in WPF.
Any idea or WPF sample code will be appreciated.
This was solved by removing this line from the constructor:
base.DoubleBuffered = true;
Now the control is fully transparent, even while changing its images.

telerik Busy Indicator is not visible

Hi I am trying to use telerik Busy indicator with MVVM. I have the Busy indicator in Mainwindow. When there is an action(button click) on one of the user controls that is in the window, the user controls view model sends an message to the MinwindowviewModel. On the message the is busy indicator should show up. But this is not working. Why is this not working?
User controls view model
public class GetCustomerVM : ViewModelBase
{
private int _CustomerId;
public int CustomerId
{
get { return _CustomerId; }
set
{
if (value != _CustomerId)
{
_CustomerId = value;
RaisePropertyChanged("CustomerId");
}
}
}
public RelayCommand StartFetching { get; private set; }
public GetCustomerVM()
{
StartFetching = new RelayCommand(OnStart);
}
private void OnStart()
{
Messenger.Default.Send(new Start());
AccountDetails a = AccountRepository.GetAccountDetailsByID(CustomerId);
Messenger.Default.Send(new Complete());
}
}
The User Control View model is:
private bool _IsBusy;
public bool IsBusy
{
get { return _IsBusy; }
set
{
if (value != _IsBusy)
{
_IsBusy = value;
RaisePropertyChanged("IsBusy");
}
}
}
public WRunEngineVM()
{
RegisterForMessages();
}
private void RegisterForMessages()
{
Messenger.Default.Register<Start>(this, OnStart);
Messenger.Default.Register<Complete>(this, OnComplete);
}
private void OnComplete(Complete obj)
{
IsBusy = false;
}
private void OnStart(Start obj)
{
IsBusy = true;
}
In the Main window View, the root element is
<telerik:RadBusyIndicator IsBusy="{Binding IsBusy}" telerik:StyleManager.Theme="Windows7">
What does AccountDetails a = AccountRepository.GetAccountDetailsByID(CustomerId); do? My guess is that whatever is happeneing there is running on the UI thread. Because it is all happeneing on the UI thread, there is never a chance of the UI to refresh and show the RadBusyIndicator. Try moving all of the work on in OnStart to a BackgroundWorker, including sending the messages. You will run into issues here, because the messages will be updating the UI thread from a background thread, so you will need to use the Dispatcher to set IsBusy to true or false.

Add Custom Control To ComboBox

Hi All
I create a custom User control and I want this custom control placed inside a combo box.
I'm using this code:
public class UserControlComboBox : ComboBox, IMessageFilter
{
public readonly NimaDatePickerUC.MiladiNimaDatePickerUC UserControl = new NimaDatePickerUC.MiladiNimaDatePickerUC();
protected override void WndProc(ref Message m)
{
if ((m.Msg == 0x0201) || (m.Msg == 0x0203))
{
if (DroppedDown)
HideUserControl();
else
ShowUserControl();
}
else
{
base.WndProc(ref m);
}
}
public bool PreFilterMessage(ref Message m)
{
// intercept mouse events
if ((m.Msg >= 0x0200) && (m.Msg <= 0x020A))
{
if (this.UserControl.RectangleToScreen(this.UserControl.DisplayRectangle).Contains(Cursor.Position))
{
// clicks inside the user control, handle normally
return false;
}
else
{
// clicks outside the user controlcollapse it.
if ((m.Msg == 0x0201) || (m.Msg == 0x0203))
this.HideUserControl();
return true;
}
}
else return false;
}
public new bool DroppedDown
{
get { return this.UserControl.Visible; }
}
protected void ShowUserControl()
{
if (!this.Visible)
return;
this.UserControl.Anchor = this.Anchor;
this.UserControl.BackColor = this.BackColor;
this.UserControl.Font = this.Font;
this.UserControl.ForeColor = this.ForeColor;
// you can be cleverer than this if you need to
this.UserControl.Top = this.Bottom;
this.UserControl.Left = this.Left;
this.UserControl.Width = Math.Max(this.UserControl.Width, this.Width);
this.Parent.Controls.Add(this.UserControl);
this.Parent.Controls[0].BringToFront();
this.UserControl.Visible = true;
this.UserControl.BringToFront();
base.OnDropDown(EventArgs.Empty);
// start listening for clicks
Application.AddMessageFilter(this);
}
protected void HideUserControl()
{
Application.RemoveMessageFilter(this);
base.OnDropDownClosed(EventArgs.Empty);
this.UserControl.Visible = false;
this.Parent.Controls.Remove(this.UserControl);
// you probably want to replace this with something more sensible
this.Text = this.UserControl.Text;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.UserControl.Dispose();
}
base.Dispose(disposing);
}
}
this code works well but if I'm using Combo Box inside a CONTAINER and the container smaller than comboBox size+My Custom control ,my custom control does not appear well and appear beneath the group box.
How I can show my custom control in front of all controls and containers?
This may seem intuitive but have you tried the
[controlname].BringToFront();
also found here

Adding button into a Listview in WinForms

Is there a way to add a button control to a cell in inside a ListView in a WinForms app?
Here is a code of a class ListViewExtender that you can reuse. It's not a derived class of ListView, basically you just declare that a specific column is displayed as buttons instead of text. The button's text is the subItem's text.
It allows big sized list views without problems, does not use p/invoke, and also works with horizontal scrollbars (some code proposed as answers here don't or are quite slow with a great number of items). Note it requires the extended ListView to have FullRowSelect set to true and view type set to Details.
This is a sample code that uses it:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); // you need to add a listView named listView1 with the designer
listView1.FullRowSelect = true;
ListViewExtender extender = new ListViewExtender(listView1);
// extend 2nd column
ListViewButtonColumn buttonAction = new ListViewButtonColumn(1);
buttonAction.Click += OnButtonActionClick;
buttonAction.FixedWidth = true;
extender.AddColumn(buttonAction);
for (int i = 0; i < 10000; i++)
{
ListViewItem item = listView1.Items.Add("item" + i);
item.SubItems.Add("button " + i);
}
}
private void OnButtonActionClick(object sender, ListViewColumnMouseEventArgs e)
{
MessageBox.Show(this, #"you clicked " + e.SubItem.Text);
}
}
}
Here is the ListViewExtender code and associated classes:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace WindowsFormsApplication1
{
public class ListViewExtender : IDisposable
{
private readonly Dictionary<int, ListViewColumn> _columns = new Dictionary<int, ListViewColumn>();
public ListViewExtender(ListView listView)
{
if (listView == null)
throw new ArgumentNullException("listView");
if (listView.View != View.Details)
throw new ArgumentException(null, "listView");
ListView = listView;
ListView.OwnerDraw = true;
ListView.DrawItem += OnDrawItem;
ListView.DrawSubItem += OnDrawSubItem;
ListView.DrawColumnHeader += OnDrawColumnHeader;
ListView.MouseMove += OnMouseMove;
ListView.MouseClick += OnMouseClick;
Font = new Font(ListView.Font.FontFamily, ListView.Font.Size - 2);
}
public virtual Font Font { get; private set; }
public ListView ListView { get; private set; }
protected virtual void OnMouseClick(object sender, MouseEventArgs e)
{
ListViewItem item;
ListViewItem.ListViewSubItem sub;
ListViewColumn column = GetColumnAt(e.X, e.Y, out item, out sub);
if (column != null)
{
column.MouseClick(e, item, sub);
}
}
public ListViewColumn GetColumnAt(int x, int y, out ListViewItem item, out ListViewItem.ListViewSubItem subItem)
{
subItem = null;
item = ListView.GetItemAt(x, y);
if (item == null)
return null;
subItem = item.GetSubItemAt(x, y);
if (subItem == null)
return null;
for (int i = 0; i < item.SubItems.Count; i++)
{
if (item.SubItems[i] == subItem)
return GetColumn(i);
}
return null;
}
protected virtual void OnMouseMove(object sender, MouseEventArgs e)
{
ListViewItem item;
ListViewItem.ListViewSubItem sub;
ListViewColumn column = GetColumnAt(e.X, e.Y, out item, out sub);
if (column != null)
{
column.Invalidate(item, sub);
return;
}
if (item != null)
{
ListView.Invalidate(item.Bounds);
}
}
protected virtual void OnDrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
e.DrawDefault = true;
}
protected virtual void OnDrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
ListViewColumn column = GetColumn(e.ColumnIndex);
if (column == null)
{
e.DrawDefault = true;
return;
}
column.Draw(e);
}
protected virtual void OnDrawItem(object sender, DrawListViewItemEventArgs e)
{
// do nothing
}
public void AddColumn(ListViewColumn column)
{
if (column == null)
throw new ArgumentNullException("column");
column.Extender = this;
_columns[column.ColumnIndex] = column;
}
public ListViewColumn GetColumn(int index)
{
ListViewColumn column;
return _columns.TryGetValue(index, out column) ? column : null;
}
public IEnumerable<ListViewColumn> Columns
{
get
{
return _columns.Values;
}
}
public virtual void Dispose()
{
if (Font != null)
{
Font.Dispose();
Font = null;
}
}
}
public abstract class ListViewColumn
{
public event EventHandler<ListViewColumnMouseEventArgs> Click;
protected ListViewColumn(int columnIndex)
{
if (columnIndex < 0)
throw new ArgumentException(null, "columnIndex");
ColumnIndex = columnIndex;
}
public virtual ListViewExtender Extender { get; protected internal set; }
public int ColumnIndex { get; private set; }
public virtual Font Font
{
get
{
return Extender == null ? null : Extender.Font;
}
}
public ListView ListView
{
get
{
return Extender == null ? null : Extender.ListView;
}
}
public abstract void Draw(DrawListViewSubItemEventArgs e);
public virtual void MouseClick(MouseEventArgs e, ListViewItem item, ListViewItem.ListViewSubItem subItem)
{
if (Click != null)
{
Click(this, new ListViewColumnMouseEventArgs(e, item, subItem));
}
}
public virtual void Invalidate(ListViewItem item, ListViewItem.ListViewSubItem subItem)
{
if (Extender != null)
{
Extender.ListView.Invalidate(subItem.Bounds);
}
}
}
public class ListViewColumnMouseEventArgs : MouseEventArgs
{
public ListViewColumnMouseEventArgs(MouseEventArgs e, ListViewItem item, ListViewItem.ListViewSubItem subItem)
: base(e.Button, e.Clicks, e.X, e.Y, e.Delta)
{
Item = item;
SubItem = subItem;
}
public ListViewItem Item { get; private set; }
public ListViewItem.ListViewSubItem SubItem { get; private set; }
}
public class ListViewButtonColumn : ListViewColumn
{
private Rectangle _hot = Rectangle.Empty;
public ListViewButtonColumn(int columnIndex)
: base(columnIndex)
{
}
public bool FixedWidth { get; set; }
public bool DrawIfEmpty { get; set; }
public override ListViewExtender Extender
{
get
{
return base.Extender;
}
protected internal set
{
base.Extender = value;
if (FixedWidth)
{
base.Extender.ListView.ColumnWidthChanging += OnColumnWidthChanging;
}
}
}
protected virtual void OnColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e)
{
if (e.ColumnIndex == ColumnIndex)
{
e.Cancel = true;
e.NewWidth = ListView.Columns[e.ColumnIndex].Width;
}
}
public override void Draw(DrawListViewSubItemEventArgs e)
{
if (_hot != Rectangle.Empty)
{
if (_hot != e.Bounds)
{
ListView.Invalidate(_hot);
_hot = Rectangle.Empty;
}
}
if ((!DrawIfEmpty) && (string.IsNullOrEmpty(e.SubItem.Text)))
return;
Point mouse = e.Item.ListView.PointToClient(Control.MousePosition);
if ((ListView.GetItemAt(mouse.X, mouse.Y) == e.Item) && (e.Item.GetSubItemAt(mouse.X, mouse.Y) == e.SubItem))
{
ButtonRenderer.DrawButton(e.Graphics, e.Bounds, e.SubItem.Text, Font, true, PushButtonState.Hot);
_hot = e.Bounds;
}
else
{
ButtonRenderer.DrawButton(e.Graphics, e.Bounds, e.SubItem.Text, Font, false, PushButtonState.Default);
}
}
}
}
The ListView itself (or ListViewItem) does not function as a container of any kind so no way to add controls directly, however it is doable. I have used this extended ListView with a lot of success: Embedding Controls in a ListView.
This is the BEST custom listview control for WinForms.
ObjectListView
To make the extender of Simon Mourier working is missing the following line:
extender.AddColumn(buttonAction);
This is, it should look like:
ListViewExtender extender = new ListViewExtender(listSummary);
ListViewButtonColumn buttonAction = new ListViewButtonColumn(2);
buttonAction.Click += OnButtonActionClick;
buttonAction.FixedWidth = true;
extender.AddColumn(buttonAction);
Maybe this could be of interest?
http://www.codeproject.com/KB/list/extendedlistviews.aspx
No, a standard Windows Forms ListView doesn't support embedded controls. You could try to build your own custom control, or you could use something like http://www.codeproject.com/KB/list/EXListView.aspx.
No and yes, ListView itself does not support such functionality, but you can create a button on top of it, so that it appears to the user as integral part of the listview. (I suppose this is what the ExtendedListView mentioned above does too).
Maybe it worths mentioning, the list view control might be designed in WPF as an usercontrol/custom control with buttons in its ListViewItems, and then use this control in the WinForms application, in an ElementHost control.
I accidentally come across a discussion before, hope this help: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/ee232cc4-68c5-4ed3-9ea7-d4d999956504/
You could use a GlacialList. It allow you to put ANY control inside a list cell and it's simple to use. You will just need to join a GlacialList.dll document to the reference part of your Solution. If you click the link it will show you how it works and how to use it and download it.
If you have a System.IO.FileNotFoundException on the InitializeComponent() just download source code from the above link, compile and use this .dll (inside bin/Debug subfolder) to your project .
Here is an example of what it looks like:
This looks like the simplest answer I have come across... just added an ItemCommand to the ListView.
See this link: handle-the-button-click-event-from-an-asp-net-listview-control

Resources