WPF enqueue and replay key events - wpf

I'm trying to improve the responsiveness of a WPF business application so that when users are "between" screens waiting for a new screen to appear after a server response, they can still be entering data. I'm able to queue the events (using a PreviewKeyDown event handler on background panel) but then I'm having difficulties just throwing the events I dequeue back at the new panel once it's loaded. In particular TextBoxes on the new panel are not picking up the text. I've tried raising the same events (setting Handled to true when capturing them, setting Handled to false when raising them again) creating new KeyDown events, new PreviewKeyDown events, doing ProcessInput, doing RaiseEvent on the panel, setting the focus on the right TextBox and doing RaiseEvent on the TextBox, many things.
It seems like it should be really simple, but I can't figure it out.
Here are some of the things I've tried. Consider a Queue of KeyEventArgs called EventQ:
Here's one thing that doesn't work:
while (EventQ.Count > 0)
{
KeyEventArgs kea = EventQ.Dequeue();
tbOne.Focus(); // tbOne is a text box
kea.Handled = false;
this.RaiseEvent(kea);
}
Here's another:
while (EventQ.Count > 0)
{
KeyEventArgs kea = EventQ.Dequeue();
tbOne.Focus(); // tbOne is a text box
var key = kea.Key; // Key to send
var routedEvent = Keyboard.PreviewKeyDownEvent; // Event to send
KeyEventArgs keanew = new KeyEventArgs(
Keyboard.PrimaryDevice,
PresentationSource.FromVisual(this),
0,
key) { RoutedEvent = routedEvent, Handled = false };
InputManager.Current.ProcessInput(keanew);
}
And another:
while (EventQ.Count > 0)
{
KeyEventArgs kea = EventQ.Dequeue();
tbOne.Focus(); // tbOne is a text box
var key = kea.Key; // Key to send
var routedEvent = Keyboard.PreviewKeyDownEvent; // Event to send
this.RaiseEvent(
new KeyEventArgs(
Keyboard.PrimaryDevice,
PresentationSource.FromVisual(this),
0,
key) { RoutedEvent = routedEvent, Handled = false }
);
}
One strange thing I've noticed is that when using the InputManager method (#2) spaces do appear. But normal text keys do not.

The same resources turned up for me when I did some research, so I think what you do in your answer is pretty valid.
I looked on and have found another way of doing it, using the Win32 API. I had to introduce some threading and small delays, because for some reason the key events were not replayed in the correct sequence without that. Overall I think this solution is easier though, and I also figured out how to include modifier keys (by using the Get/SetKeyboardState function). Uppercase is working, and so should keyboard shortcuts.
Starting the demo app, pressing the keys 1 space 2 space 3 tab 4 space 5 space 6, then clicking the button produces the following:
Xaml:
<UserControl x:Class="WpfApplication1.KeyEventQueueDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" >
<StackPanel>
<TextBox x:Name="tbOne" Margin="5,2" />
<TextBox x:Name="tbTwo" Margin="5,2" />
<Button x:Name="btn" Content="Replay key events" Margin="5,2" />
</StackPanel>
</UserControl>
Code behind:
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interop;
namespace WpfApplication1
{
/// <summary>
/// Structure that defines key input with modifier keys
/// </summary>
public struct KeyAndState
{
public int Key;
public byte[] KeyboardState;
public KeyAndState(int key, byte[] state)
{
Key = key;
KeyboardState = state;
}
}
/// <summary>
/// Demo to illustrate storing keyboard input and playing it back at a later stage
/// </summary>
public partial class KeyEventQueueDemo : UserControl
{
private const int WM_KEYDOWN = 0x0100;
[DllImport("user32.dll")]
static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
[DllImport("user32.dll")]
static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
static extern bool SetKeyboardState(byte[] lpKeyState);
private IntPtr _handle;
private bool _isMonitoring = true;
private Queue<KeyAndState> _eventQ = new Queue<KeyAndState>();
public KeyEventQueueDemo()
{
InitializeComponent();
this.Focusable = true;
this.Loaded += KeyEventQueueDemo_Loaded;
this.PreviewKeyDown += KeyEventQueueDemo_PreviewKeyDown;
this.btn.Click += (s, e) => ReplayKeyEvents();
}
void KeyEventQueueDemo_Loaded(object sender, RoutedEventArgs e)
{
this.Focus(); // necessary to detect previewkeydown event
SetFocusable(false); // for demo purpose only, so controls do not get focus at tab key
// getting window handle
HwndSource source = (HwndSource)HwndSource.FromVisual(this);
_handle = source.Handle;
}
/// <summary>
/// Get key and keyboard state (modifier keys), store them in a queue
/// </summary>
void KeyEventQueueDemo_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (_isMonitoring)
{
int key = KeyInterop.VirtualKeyFromKey(e.Key);
byte[] state = new byte[256];
GetKeyboardState(state);
_eventQ.Enqueue(new KeyAndState(key, state));
}
}
/// <summary>
/// Replay key events from queue
/// </summary>
private void ReplayKeyEvents()
{
_isMonitoring = false; // no longer add to queue
SetFocusable(true); // allow controls to take focus now (demo purpose only)
MoveFocus(new TraversalRequest(FocusNavigationDirection.Next)); // set focus to first control
// thread the dequeueing, because the sequence of inputs is not preserved
// unless a small delay between them is introduced. Normally the effect this
// produces should be very acceptable for an UI.
Task.Run(() =>
{
while (_eventQ.Count > 0)
{
KeyAndState keyAndState = _eventQ.Dequeue();
Application.Current.Dispatcher.BeginInvoke((Action)(() =>
{
SetKeyboardState(keyAndState.KeyboardState); // set stored keyboard state
PostMessage(_handle, WM_KEYDOWN, keyAndState.Key, 0);
}));
System.Threading.Thread.Sleep(5); // might need adjustment
}
});
}
/// <summary>
/// Prevent controls from getting focus and taking the input until requested
/// </summary>
private void SetFocusable(bool isFocusable)
{
tbOne.Focusable = isFocusable;
tbTwo.Focusable = isFocusable;
btn.Focusable = isFocusable;
}
}
}

The enqueue system is something that I've wanted to do myself, as part of my project which allows multi-threaded UI to function without any problems(one thread routes events into another). There is only slight problem, namely WPF does not have public API to inject INPUT events. Here is a copy/paste from one of the Microsoft employees that I talked with, like weeks back:
"WPF does not expose public methods for injecting input events in the proper way. This scenario is just not supported by the public API. You will probably have to do a lot of reflection and other hacking. For example, WPF treats some input as “trusted” because it knows it came from the message pump. If you just raise an input event, the event will not be trusted."
I think you need to rethink your strategy.

Thanks all for your support but I haven't really struck a solution from the SO community so I'm going to answer this myself since this is the closest I seem to get to a solution. The "hack" as Erti-Chris says seems to be what we're left with. I've had some luck decomposing the problem so I don't have the sense I'm writing a whole new keyboard handler. The approach I'm following is to decompose the events into a combination of InputManager handling and of TextComposition. Throwing a KeyEventArgs (either the original one or one I've created myself) doesn't seem to register on a PreviewKeyDown handler.
Part of the difficulty comes from the information in Erti-Chris's post, and another part seems to be related to TextBoxes trying to react to certain keys like arrow keys differently from normal keys like the letter "A".
To move forward with this I found information from this post to be useful:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b657618e-7fc6-4e6b-9b62-1ffca25d186b
Here is the solution that I'm getting some positive results from now:
Keyboard.Focus(tbOne); // the first element on the Panel to get the focus
while (EventQ.Count > 0)
{
KeyEventArgs kea = EventQ.Dequeue();
kea.Handled = false;
var routedEvent = KeyDownEvent;
KeyEventArgs keanew = new KeyEventArgs(
Keyboard.PrimaryDevice,
PresentationSource.FromVisual(tbOne),
kea.Timestamp,
kea.Key) { RoutedEvent = routedEvent, Handled = false };
keanew.Source = tbOne;
bool itWorked = InputManager.Current.ProcessInput(keanew);
if (itWorked)
{
continue;
// at this point spaces, backspaces, tabs, arrow keys, deletes are handled
}
else
{
String keyChar = kea.Key.ToString();
if (keyChar.Length > 1)
{
// handle special keys; letters are one length
if (keyChar == "OemPeriod") keyChar = ".";
if (keyChar == "OemComma") keyChar = ",";
}
TextCompositionManager.StartComposition(new TextComposition(InputManager.Current, Keyboard.FocusedElement, keyChar));
}
}
If anyone can show me a better way I'm delighted to mark your contribution as the answer, but for now this is what I'm working with.

Related

How to make sure MouseEnter fires for all elements

I have a WPF ItemsControl displaying a series of Rectangles.
Each rectangle makes use of MVVM Lights EventToCommand to track the MouseEnter event and set the Rectangle to 'Selected'
I then use this property to highlight the rectangle using triggers in the style.
My problem occurs if the mouse is dragged too quickly.
Working (Slowly dragged):
Not working (quickly dragged):
In this case the event has not fired for the second Rectangle.
How do I make sure the event fires for all controls the mouse moves over?
My suggestion would be to put all the event occurences in a queue. I think your problem occures because when an event fires, you call one method and if the method hasn't finished at the time the next event occurs, it can not be called a second time.
Create a queue and put the event occures in there, then create a thread that waits for the queue to fill and then procceses it it.
Sample:
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
using System.Timers;
using Timer = System.Timers.Timer;
class Program
{
private static Queue<My_Event> EventQueue;
private static Timer t = new Timer(10);
static void Main(string[] args)
{
Task thread = new Task(MarkStuffYellow);
EventQueue = new Queue<My_Event>();
t.Elapsed += t_Elapsed;
t.Start();
t.AutoReset = true;
}
static void t_Elapsed(object sender, ElapsedEventArgs e)
{
EventQueue.Enqueue(new My_Event(sender, e));
}
private static void MarkStuffYellow()
{
/// !!! While (true) is not an solution, if you do it like this,
/// your CPU will be full !!!
while (true)
{
if (EventQueue.Any())
{
My_Event myEvent = EventQueue.Dequeue();
var sender = myEvent.Sender;
var e = myEvent.E;
/// Do Stuff with your event
}
}
}
}
/// Needed to save your event
internal class My_Event
{
public My_Event(object sender, ElapsedEventArgs e)
{
this.Sender = sender;
this.E = e;
}
public object Sender;
public ElapsedEventArgs E;
}
}

MVVM Wait Cursor how to set the.wait cursor during invocation of a command?

Scenario:
User clicks a button on the View
This invokes a command on the ViewModel, DoProcessing
How, and where does the Wait cursor get set, considering the responsibilitues of View and ViewModel?
Just to be clear, I am just looking to change the DEFAULT cursor to an hourglass while the command is running. When the command completes, the cursor mut change back to an arrow. (It is a synchronous operation I am looking for, and I want the UI to block).
I have created an IsBusy property on the ViewModel. How do I ensure that the Application's mouse pointer changes?
I am using it successfully in my application:
/// <summary>
/// Contains helper methods for UI, so far just one for showing a waitcursor
/// </summary>
public static class UIServices
{
/// <summary>
/// A value indicating whether the UI is currently busy
/// </summary>
private static bool IsBusy;
/// <summary>
/// Sets the busystate as busy.
/// </summary>
public static void SetBusyState()
{
SetBusyState(true);
}
/// <summary>
/// Sets the busystate to busy or not busy.
/// </summary>
/// <param name="busy">if set to <c>true</c> the application is now busy.</param>
private static void SetBusyState(bool busy)
{
if (busy != IsBusy)
{
IsBusy = busy;
Mouse.OverrideCursor = busy ? Cursors.Wait : null;
if (IsBusy)
{
new DispatcherTimer(TimeSpan.FromSeconds(0), DispatcherPriority.ApplicationIdle, dispatcherTimer_Tick, System.Windows.Application.Current.Dispatcher);
}
}
}
/// <summary>
/// Handles the Tick event of the dispatcherTimer control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
private static void dispatcherTimer_Tick(object sender, EventArgs e)
{
var dispatcherTimer = sender as DispatcherTimer;
if (dispatcherTimer != null)
{
SetBusyState(false);
dispatcherTimer.Stop();
}
}
}
This has been taken from here. Courtsey huttelihut.
You need to call the SetBusyState method every time you think you are going to perform any time consuming operation. e.g.
...
UIServices.SetBusyState();
DoProcessing();
...
This will automatically change your cursor to wait cursor when the application is busy and back to normal when idle.
A very simple method is to simply bind to the 'Cursor' property of the window (or any other control). For example:
XAML:
<Window
x:Class="Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Cursor="{Binding Cursor}" />
ViewModel Cursor Property (Using Apex.MVVM):
private NotifyingProperty cursor = new NotifyingProperty("Cursor", typeof(System.Windows.Input.Cursor), System.Windows.Input.Cursors.Arrow);
public System.Windows.Input.Cursor Cursor
{
get { return (System.Windows.Input.Cursor)GetValue(cursor); }
set { SetValue(cursor, value); }
}
Then simply change the cursor in your view when needed...
public void DoSomethingLongCommand()
{
Cursor = System.Windows.Input.Cursors.Wait;
... some long process ...
Cursor = System.Windows.Input.Cursors.Arrow;
}
You want to have a bool property in viewmodel.
private bool _IsBusy;
public bool IsBusy
{
get { return _IsBusy; }
set
{
_IsBusy = value;
NotifyPropertyChanged("IsBusy");
}
}
Now you want to set the window style to bind to it.
<Window.Style>
<Style TargetType="Window">
<Setter Property="ForceCursor" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsBusy}" Value="True">
<Setter Property="Cursor" Value="Wait"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Window.Style>
Now whenever a command is being executed and your view model is is busy, it would just set the IsBusy flag and reset it when done. The Window will automatically display the wait cursor and restore the original cursor when done.
You can write the command handler function in view model something like this:
private void MyCommandExectute(object obj) // this responds to Button execute
{
try
{
IsBusy = true;
CallTheFunctionThatTakesLongTime_Here();
}
finally
{
IsBusy = false;
}
}
Command is handled on the view model, so the reasonable decission would be to do folowing:
1) Create a busy indicator service and inject it into the view model (this will allow you to replace the cursor logic with some nasty animation easily)
2) In the command handler call the busy indicator service to notify the user
I might be wrong, but it looks like you are trying to do some heavy calculations or I/O on UI thread. I highly recommend you to perform work on thread pool in this case. You can use Task and TaskFactory to easily wrap work with ThreadPool
There is a great Session(at 50:58) by Laurent Bugnion online (Creator of MVVM Light).
There's also an deepDive session available (alternatively here(at 24:47)).
In at least one of them he live codes a busy Indicator using a is BusyProperty.
The ViewModel should only decide whether it is busy, and the decision about what cursor to use, or whether to use some other technique such as a progress bar should be left up to the View.
And on the other hand, handling it with code-behind in the View is not so desirable either, because the ideal is that Views should not have code-behind.
Therefore I chose to make a class that can be used in the View XAML to specify that the cursor should be change to Wait when the ViewModel is busy. Using UWP + Prism the class definition is:
public class CursorBusy : FrameworkElement
{
private static CoreCursor _arrow = new CoreCursor(CoreCursorType.Arrow, 0);
private static CoreCursor _wait = new CoreCursor(CoreCursorType.Wait, 0);
public static readonly DependencyProperty IsWaitCursorProperty =
DependencyProperty.Register(
"IsWaitCursor",
typeof(bool),
typeof(CursorBusy),
new PropertyMetadata(false, OnIsWaitCursorChanged)
);
public bool IsWaitCursor
{
get { return (bool)GetValue(IsWaitCursorProperty); }
set { SetValue(IsWaitCursorProperty, value); }
}
private static void OnIsWaitCursorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CursorBusy cb = (CursorBusy)d;
Window.Current.CoreWindow.PointerCursor = (bool)e.NewValue ? _wait : _arrow;
}
}
And the way to use it is:
<mvvm:SessionStateAwarePage
x:Class="Orsa.Views.ImportPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mvvm="using:Prism.Windows.Mvvm"
xmlns:local="using:Orsa"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mvvm:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid>
<Grid.RowDefinitions>
.
.
</Grid.RowDefinitions>
<local:CursorBusy IsWaitCursor="{Binding IsBusy}"/>
(other UI Elements)
.
.
</Grid>
</mvvm:SessionStateAwarePage>
IMHO that it is perfectly fine for the wait cursor logic to be next to the command in the viewmodel.
As to the best way to do change the cursor, create a IDisposable wrapper that changes the Mouse.OverrideCursor property.
public class StackedCursorOverride : IDisposable
{
private readonly static Stack<Cursor> CursorStack;
static StackedCursorOverride()
{
CursorStack = new Stack<Cursor>();
}
public StackedCursorOverride(Cursor cursor)
{
CursorStack.Push(cursor);
Mouse.OverrideCursor = cursor;
}
public void Dispose()
{
var previousCursor = CursorStack.Pop();
if (CursorStack.Count == 0)
{
Mouse.OverrideCursor = null;
return;
}
// if next cursor is the same as the one we just popped, don't change the override
if ((CursorStack.Count > 0) && (CursorStack.Peek() != previousCursor))
Mouse.OverrideCursor = CursorStack.Peek();
}
}
Usage:
using (new StackedCursorOverride(Cursors.Wait))
{
// ...
}
The above is a revised version of the solution that I posted to this question.
private static void LoadWindow<T>(Window owner) where T : Window, new()
{
owner.Cursor = Cursors.Wait;
new T { Owner = owner }.Show();
owner.Cursor = Cursors.Arrow;
}

Slider \ ScrollViewer in a touch interface not working properly

In WPF I've got the following XAML:
<ScrollViewer Canvas.Left="2266" Canvas.Top="428" Height="378" Name="scrollViewer1" Width="728" PanningMode="VerticalOnly" PanningRatio="2">
<Canvas Height="1732.593" Width="507.667">
<Slider Height="40.668" x:Name="slider1" Width="507.667" Style="{DynamicResource SliderStyle1}" Canvas.Left="15" Canvas.Top="150" />
</Slider>
</Canvas>
</ScrollViewer>
It's a ScrollViewer containing a Slider. I'm using the following on a touch-screen, and I'm using the panning even to scroll the ScrollViewer vertically. When PanningMode="VerticalOnly" is set, the slider stops working!
I'm assuming the ScollViewer is consuming the touch\slide event and handling it before the slider does (but I think I'm wrong on this front).
Is there any workaround for this?
I just solved this issue in our app.
What is happening is that the ScrollViewer captures the TouchDevice in its PreviewTouchMove handler, which "steals" the TouchDevice from other controls and prevents them from receiving any PreviewTouchMove or TouchMove events.
In order to work around this, you need to implement a custom Thumb control that captures the TouchDevice in the PreviewTouchDown event and stores a reference to it until the PreviewTouchUp event occurs. Then the control can "steal" the capture back in its LostTouchCapture handler, when appropriate. Here is some brief code:
public class CustomThumb : Thumb
{
private TouchDevice currentDevice = null;
protected override void OnPreviewTouchDown(TouchEventArgs e)
{
// Release any previous capture
ReleaseCurrentDevice();
// Capture the new touch
CaptureCurrentDevice(e);
}
protected override void OnPreviewTouchUp(TouchEventArgs e)
{
ReleaseCurrentDevice();
}
protected override void OnLostTouchCapture(TouchEventArgs e)
{
// Only re-capture if the reference is not null
// This way we avoid re-capturing after calling ReleaseCurrentDevice()
if (currentDevice != null)
{
CaptureCurrentDevice(e);
}
}
private void ReleaseCurrentDevice()
{
if (currentDevice != null)
{
// Set the reference to null so that we don't re-capture in the OnLostTouchCapture() method
var temp = currentDevice;
currentDevice = null;
ReleaseTouchCapture(temp);
}
}
private void CaptureCurrentDevice(TouchEventArgs e)
{
bool gotTouch = CaptureTouch(e.TouchDevice);
if (gotTouch)
{
currentDevice = e.TouchDevice;
}
}
}
Then you will need to re-template the Slider to use the CustomThumb instead of the default Thumb control.
i strugled with a similar issue. the workaround was this one (none of the others worked for me): i created a custom thumb, and then i used it inside a scrollbar style in xaml as the PART_Track's thumb.
public class DragableThumb : Thumb
{
double m_originalOffset;
double m_originalDistance;
int m_touchID;
/// <summary>
/// Get the parent scrollviewer, if any
/// </summary>
/// <returns>Scroll viewer or null</returns>
ScrollViewer GetScrollViewer()
{
if (TemplatedParent is ScrollBar && ((ScrollBar)TemplatedParent).TemplatedParent is ScrollViewer)
{
return ((ScrollViewer)((ScrollBar)TemplatedParent).TemplatedParent);
}
return null;
}
/// <summary>
/// Begin thumb drag
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnTouchDown(TouchEventArgs e)
{
ScrollViewer scrollViewer;
base.OnTouchDown(e);
m_touchID = e.TouchDevice.Id;
if ((scrollViewer = GetScrollViewer()) != null)
{
m_originalOffset = scrollViewer.HorizontalOffset;
m_originalDistance = e.GetTouchPoint(scrollViewer).Position.X;
}
}
/// <summary>
/// Handle thumb delta
/// </summary>
/// <param name="e">Event arguments</param>
protected override void OnTouchMove(TouchEventArgs e)
{
ScrollViewer scrollViewer;
double actualDistance;
base.OnTouchMove(e);
if ((scrollViewer = GetScrollViewer()) != null && m_touchID == e.TouchDevice.Id)
{
actualDistance = e.GetTouchPoint(scrollViewer).Position.X;
scrollViewer.ScrollToHorizontalOffset(m_originalOffset + (actualDistance - m_originalDistance) * scrollViewer.ExtentWidth / scrollViewer.ActualWidth);
}
}
}
The following worked for me. I searched around for a long time for something that would work. I adapted this for touch from How to make WPF Slider Thumb follow cursor from any point. This is a much simpler fix and allows you to avoid creating a custom slider/thumb control.
<Slider TouchMove="OnTouchMove" IsMoveToPointEnabled="True"/>
IsMoveToPointEnable must be set to true for this to work.
private void Slider_OnTouchMove(object sender, TouchEventArgs e)
{
Slider slider = (Slider)sender;
TouchPoint point = e.GetTouchPoint (slider );
double d = 1.0 / slider.ActualWidth * point.Position.X;
int p = int(slider.Maximum * d);
slider.Value = p;
}
This is nice and simple and worked for me - although it's worth wrapping up in a generic function and extending to handle the slider minimum value also as it may not be zero. What a pain to have to do though. There are many thing about WPF that are cool, but so many simple things require extra steps it really can be detrimental to productivity.

Can I create a KeyBinding for a sequence of keys in WPF?

Is it possible to define key bindings in WPF for a sequence of key presses like the shortcuts in Visual Studio e.g. Ctrl + R, Ctrl + A is run all tests in current solution
As far as I can see I can only bind single key combinations like Ctrl + S using the element. Can I bind sequences using this or will I have to manually handle the key presses to do this?
You need to create your own InputGesture, by overriding the Matches method.
Something like that:
public class MultiInputGesture : InputGesture
{
public MultiInputGesture()
{
Gestures = new InputGestureCollection();
}
public InputGestureCollection Gestures { get; private set; }
private int _currentMatchIndex = 0;
public override bool Matches(object targetElement, InputEventArgs inputEventArgs)
{
if (_currentMatchIndex < Gestures.Count)
{
if (Gestures[_currentMatchIndex].Matches(targetElement, inputEventArgs))
{
_currentMatchIndex++;
return (_currentMatchIndex == Gestures.Count);
}
}
_currentMatchIndex = 0;
return false;
}
}
It probably needs a little more than that, like ignoring certain events (e.g. KeyUp events between KeyDown events shouldn't reset _currentMatchIndex), but you get the picture...
The answer by #ThomasLevesque is mostly correct, but doesn't deal with repeating keys. (Note that holding the Ctrl key down causes key-repeat events to be generated.) It can also be useful to time out if the user stalls mid-sequence. Here's what I'm using:
public class MultiKeyInputGesture : InputGesture {
private const int MAX_PAUSE_MILLIS = 1500;
private InputGestureCollection mGestures = new InputGestureCollection();
private DateTime mLastWhen = DateTime.Now;
private int mCheckIdx;
public MultiKeyInputGesture(KeyGesture[] keys) {
Debug.Assert(keys.Length > 0);
// Grab a copy of the array contents.
foreach (KeyGesture kg in keys) {
mGestures.Add(kg);
}
}
public override bool Matches(object targetElement, InputEventArgs inputEventArgs) {
if (!(inputEventArgs is KeyEventArgs)) {
// does this actually happen?
return false;
}
DateTime now = DateTime.Now;
if ((now - mLastWhen).TotalMilliseconds > MAX_PAUSE_MILLIS) {
mCheckIdx = 0;
}
mLastWhen = now;
if (((KeyEventArgs)inputEventArgs).IsRepeat) {
// ignore key-repeat noise (especially from modifiers)
return false;
}
if (!mGestures[mCheckIdx].Matches(null, inputEventArgs)) {
mCheckIdx = 0;
return false;
}
mCheckIdx++;
if (mCheckIdx == mGestures.Count) {
mCheckIdx = 0;
inputEventArgs.Handled = true;
return true;
}
return false;
}
}
I'm using this by defining the RoutedUICommand in XAML:
<Window.Resources>
<RoutedUICommand x:Key="MyCommand" Text="My Command"/>
</Window.Resources>
This is referenced from <Window.CommandBindings> and <MenuItem> as usual. Then, in the window constructor, I do:
RoutedUICommand ruic = (RoutedUICommand)FindResource("MyCommand");
ruic.InputGestures.Add(
new MultiKeyInputGesture(new KeyGesture[] {
new KeyGesture(Key.H, ModifierKeys.Control, "Ctrl+H"),
new KeyGesture(Key.C, ModifierKeys.Control, "Ctrl+C")
}) );
I found this forum post helpful.
You will need to add an explicit InputGestureText to any MenuItem, unless you want to try the DisplayString hack in the linked forum post.
NOTE: the key gesture handler "eats" the key that completes the gesture. If you have more than one handler, and the user tries to use two multi-key sequences in a row (e.g. Ctrl+H, Ctrl+C followed immediately by Ctrl+H, Ctrl+D), the second handler won't reset when Ctrl+C is hit. Instead, it'll reset when the second Ctrl+H arrives, and will miss the combo. The actual behavior is dependent upon the order in which the handlers are called. I'm currently handling this by defining a static event that fires when a match is found, and subscribing all instances to it.
Update: one other thing to be aware of: the order of items in <Window.CommandBindings> matters. If you have a Copy handler that fires on Ctrl+C, it must appear in the list after the multi-key gesture for Ctrl+H, Ctrl+C.
<KeyBinding x:Name="mykeybinding" Gesture="CTRL+P" Key="E"
Command="mycommand"/>
That seems to do trick at my end, I have have to press ctrl+P+E to execute "mycommand"
Based on
http://msdn.microsoft.com/en-in/library/system.windows.input.keybinding.aspx

WPF doesn't honor Textbox.MinLines for Auto height calculation

I want to have a TextBox which Height grows as Iam entering lines of Text.
I've set the Height property to "Auto", and so far the growing works.
Now I want that the TextBox's Height should be at least 5 lines.
Now I've set the MinLines property to "5" but if I start the app the TextBox's height is still one line.
Try setting the MinHeight property.
A hack to make the MinLines property work
public class TextBoxAdv : TextBox
{
bool loaded = false;
/// <summary>
/// Constructor
/// </summary>
public TextBoxAdv()
{
Loaded += new RoutedEventHandler( Control_Loaded );
SetResourceReference( StyleProperty, typeof( TextBox ) );
}
void Control_Loaded( object sender, RoutedEventArgs e )
{
if( !loaded )
{
loaded = true;
string text = Text;
Text = "Text";
UpdateLayout();
Text = text;
}
}
}
I propose a different solution that properly respects the MinLines property, rather than forcing you to use MinHeight.
First, start with a convenience method to allow you to Post an action to the window loop. (I'm including both one where you need to pass state and one where you don't.)
public static class Globals {
public static void Post(Action callback){
if(SynchronizationContext.Current is SynchronizationContext currentContext)
currentContext.Post( _ => callback(), null);
else{
callback();
}
}
public static void Post<TState>(TState state, Action<TState> callback){
if(SynchronizationContext.Current is SynchronizationContext currentContext)
currentContext.Post(_ => callback(state), null);
else{
callback(state);
}
}
}
Next, create an extension method for TextBox to 'initialize' the proper size based on MinLines. I put this in a Hacks class because to me, that's what this is and it clearly identifies the code as such.
public static void FixInitialMinLines(this TextBox textBox) {
Globals.Post(() => {
var textBinding = textBox.GetBindingExpression(TextBox.TextProperty)?.ParentBinding;
if (textBinding != null) {
BindingOperations.ClearBinding(textBox, TextBox.TextProperty);
textBox.UpdateLayout();
BindingOperations.SetBinding(textBox, TextBox.TextProperty, textBinding);
}
else {
var lastValue = textBox.Text;
textBox.Text = lastValue + "a";
textBox.UpdateLayout();
textBox.Text = lastValue;
}
});
}
The above code handles both bound and unbound TextBox controls, but rather than simply changing the value like other controls which may cascade that change down through the bindings, it first disconnects the binding, forces layout, then reconnects the binding, thus triggering the proper layout in the UI. This avoids unintentionally changing your bound sources should the binding be two-way.
Finally, simply call the extension method for every TextBox where MinLines is set. Thanks to the Post call in the extension method, You can call this immediately after InitializeComponent and it will still be executed after all other events have fired, including all layout and the Loaded event.
public partial class Main : Window {
public Main() {
InitializeComponent();
// Fix initial MinLines issue
SomeTextBoxWithMinLines.FixInitialMinLines();
}
...
}
Add the above code to your 'library' of functions and you can address the issue with a single line of code in all of your windows and controls. Enjoy!

Resources