I am working on a UI for a Windows 8.1 tablet, which has a full version of Windows on it. There is a keyboard icon at the bottom of windows 8.1, which brings up a keyboard, and I want that to automatically trigger after clicking a numericUpDown box. I then would also like it to close after leaving or clicking off of the box.
I am basically just trying to focus it when it is clicked, but this does not seem to bring up the keyboard. Also, note, I am setting some other numericUpDown box to the one in the function so I can call it outside, so I hope that doesn't make it difficult to see what's going on, let me know if you need any clarifications and thank you for the help. Here is what I have so far:
copiedNUD.Click += CopiedNudPass_Focus;
//copy copied nud
CopiedNudPass = copiedNUD;
...
void CopiedNudPass_Focus(object sender, EventArgs e)
{
CopiedNudPass.Focus();
}
I tried looking around a bit, but some of the solutions weren't too clear to me. I really appreciate the help. Thank you.
I figured it out. Here is my code specifically for a tablet with window 8 or higher:
copiedNUD.Click += CopiedNudPass_Focus;
//copy copied nud
CopiedNudPass = copiedNUD;
...
//Launch keyboard
void CopiedNudPass_Focus(object sender, EventArgs e)
{
Version win8version = new Version(6, 2, 9200, 0);
if (Environment.OSVersion.Version >= win8version)
{
string progFiles = #"C:\Program Files\Common Files\Microsoft Shared\ink";
string keyboardPath = Path.Combine(progFiles, "TabTip.exe");
Process.Start(keyboardPath);
}
}
//Close keyboard
void CopiedNudPass_LostFocus(object sender, EventArgs e)
{
Version win8version = new Version(6, 2, 9200, 0);
if (Environment.OSVersion.Version >= win8version)
{
Process[] oskProcessArray = Process.GetProcessesByName("TabTip");
foreach (Process onscreenProcess in oskProcessArray)
{
onscreenProcess.Kill();
}
Refresh();
}
}
My only problem right now is that when the keyboard closes my main form in the background gets cut off and I tried to refresh it using Refresh(); , but that did not seem to work :(.
Here is a better closing function:
After killing the process for TabletKeyboard(TabTip.exe) application doesn't bring back to its original size in wpf
Here is my new close code:
//Close keyboard
void CopiedNudPass_LostFocus(object sender, EventArgs e)
{
Version win8version = new Version(6, 2, 9200, 0);
if (Environment.OSVersion.Version >= win8version)
{
uint WM_SYSCOMMAND = 274;
uint SC_CLOSE = 61536;
IntPtr KeyboardWnd = FindWindow("IPTip_Main_Window", null);
PostMessage(KeyboardWnd.ToInt32(), WM_SYSCOMMAND, (int)SC_CLOSE, 0);
}
}
I also had to add a reference to WindowsBase and add external functions to the project. The steps and additional code are in the url I linked to in this post. Here's how you add a reference for WindowsBase to get using System.Windows.Interop; to work:
Right click on project
Highlight Add and click Reference
Ensure you have Framework selected under Assemblies
Scroll down and check in "WindowsBase" and hit ok
Add using System.Windows.Interop; at the top of your code and your done
This worked for me (in Java & eclipse RCP)
text.addFocusListener(new FocusListener()
{
#Override
public void focusLost(FocusEvent arg0)
{
LogUtil.logInfo("Closing OSK");
try
{
if(Settings.getBoolean(Settings.OSK_USETABTIP)) {
Runtime.getRuntime().exec("cmd /c taskkill /IM tabtip.exe");
} else {
Runtime.getRuntime().exec("cmd /c taskkill /IM osk.exe");
}
}
catch (IOException e)
{
LogUtil.logError(e.toString());
}
}
#Override
public void focusGained(FocusEvent arg0)
{
try
{
String sysroot = System.getenv("SystemRoot");
if(Settings.getBoolean(Settings.OSK_USETABTIP)) {
LogUtil.logInfo("Opening TabTip");
ProcessBuilder pb = new ProcessBuilder("C:/pathtotabtip/tabtip.exe");
pb.start();
} else {
LogUtil.logInfo("Opening OSK");
ProcessBuilder pb = new ProcessBuilder(sysroot + "/system32/osk.exe");
pb.start();
}
}
catch (Exception e)
{
LogUtil.logError(e.toString());
}
}
});
Related
Debug versions (86, 64, ARM) all work fine, release versions build fine, but when they run all that happens is my app window opens and remains blank (white background). The only errors I see in the output are a whole bunch of:
...PDB file was not present when IL code was compiled to native.
I'm not sure if the missing .pdb files are the culprit - pretty sure they're not, cause they're just for debugging purposes right?
Anyways, this is the first UWP app I have tried to get ready for the Windows Store, and not completely sure if I have to do anything special like sign it to test release versions on my own computer?
Edit 1: Thank you #Alan for your suggestions, manually uninstalling the app sometimes gets me past the blank window to load the app bar, but then I am getting these errors when it doesn't hang on the splash screen:
Debugger Error 1,
Debugger Error 2
I have done nothing special to the splash screen, loaded all my visual assets using the built in tools in manifest, and have not modified App.xaml.cs from its default. Here is my Mainpage.cs:
using Sublist.Classes;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Sublist
{
public sealed partial class MainPage : Page
{
const string TAG = "MainPage: ";
// for loading and saving user data and settings
public static DataHandler dataHandler;
public static MasterList<Entry> masterList;
//public static int listViewSelectedIndex = -1;
public MainPage()
{
this.InitializeComponent();
dataHandler = new DataHandler(this);
masterList = new MasterList<Entry>();
// load user data
if (dataHandler.userDataList != null)
masterList = dataHandler.userDataList;
masterList.UpdateListView(this);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
dataHandler.LoadUserSettings();
}
private void AppBarAdd_Click(object sender, RoutedEventArgs e)
{
masterList.AddRow(this);
}
private void AppBarRemove_Click(object sender, RoutedEventArgs e)
{
if (!(mainListView.SelectedIndex < 0))
{
masterList.RemoveRow(this);
}
}
private void AppBarMoveDown_Click(object sender, RoutedEventArgs e)
{
}
private void AppBarMoveUp_Click(object sender, RoutedEventArgs e)
{
}
private void AppBarIndent_Click(object sender, RoutedEventArgs e)
{
// indent the row control if currently selected index is a list view item
if (-1 < mainListView.SelectedIndex && mainListView.SelectedIndex < mainListView.Items.Count)
{
// but don't allow more than one indent past above row's indent level
RowControl rc = (RowControl)mainListView.Items[mainListView.SelectedIndex];
int indexMinus1 = mainListView.SelectedIndex - 1;
if (-1 < indexMinus1 && rc.indentProp <= masterList[indexMinus1].indent)
{
rc.indentProp++;
}
}
// then update list view
masterList.UpdateListView(this);
}
private void AppBarUnindent_Click(object sender, RoutedEventArgs e)
{
// unindent the row control if currently selected index is a list view item
if (-1 < mainListView.SelectedIndex && mainListView.SelectedIndex < mainListView.Items.Count)
{
// but don't allow unindenting off left side of page
RowControl rc = (RowControl)mainListView.Items[mainListView.SelectedIndex];
if (rc.indentProp > 0)
{
rc.indentProp--;
}
}
// then update list view
masterList.UpdateListView(this);
}
public void AppBarShowCompl_Click(object sender, RoutedEventArgs e)
{
dataHandler.SaveUserSettings();
masterList.UpdateListView(this);
}
public void AppBarMarkAsCompleted_Click(object sender, RoutedEventArgs e)
{
// toggle hidden state of active entry
if (-1 < mainListView.SelectedIndex && mainListView.SelectedIndex < masterList.Count)
{
masterList[mainListView.SelectedIndex].completed = (masterList[mainListView.SelectedIndex].completed) ? false : true;
masterList.UpdateListView(this);
}
}
}
}
I have added the FileService and SettingsService classes from the opensource Template10 to the project.
The build setting "compile with .NET Native tool chain" was unchecked, I've tried deploying with it checked/unchecked for both debug/release versions, and now the debug version also often hangs on the splash screen? With it checked, I get a whole bunch of these errors as well:
'Sublist.exe' (Win32): Loaded 'C:\Windows\System32\biwinrt.dll'. Skipped loading symbols. Module is native, and native debugging is currently disabled.
I've tried downloading the server symbols with no success...
I found the hang happens at the following line in GetIfFileExitsAsync.
retval = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(key);
I made the following change in you code and it should work now.
In DataHandler's constructor, use Task.Run to initialize the userDataList.
public DataHandler(MainPage mp)
{
mainPage = mp;
settingsHelper = new SettingsHelper();
fileHelper = new FileHelper();
LoadUserSettings();
Task.Run(() =>
{
userDataList = LoadUserData();
});
Task.WaitAll();
}
I am still not sure why the .net native compile will make this issue, but will try to simplify the project and report it in MS internal channel.
So I'm making a Kinect application using buttons, and to navigate the app, I'm making new windows for each button. I'm come across an issue I haven't been able to find any help at all on, and would appreciate any help.
So to open the new window, I'm using this:
private void button1_Click(object sender, RoutedEventArgs e)
{
//SUPPOSED to uninitialize the Kinect
UninitializeKinectSensor(this.Kinect;
//To open the new window
Window1 newwindow = new Window1();
newwindow.Show();
//To close the first window...
Close();
{
SO that one line is supposed to uninitialize the Kinect so it'll be free for the new window to use, but when it goes to the new window, the Kinect freezes. If I use the mouse to go back to the first window, it works on the first window again, which it shouldn't.
I also added in this line in the initialization phase
public Window1()
{
//Other init code is here, but this is the line I added. It doesn't seem to do anything.
InitializeKinectSensor(this.Kinect);
}
Any help is greatly appreciated!! I'm sure it's something simple and I just failed miserably haha XD
Do you really have to create a new window instead of using pages?
In your MainWindow you create a frame that takes all the window and use this frame to navigate between pages. This way, you'll keep the focus of the kinect in your whole application.
Depends alot on what UninitializeKinectSensor is actually doing. Just as a quick fix, though, you can try calling uninitialize on a background worker and see if that helps at all.
Instead of using the "Show()" use "ShowDialog()".It's better if you can create a static class or method to initialize and uninitialized kinect.
public static void start()
{
KinectSensor.KinectSensors.StatusChanged += kinectSensorsStatusChanged;
DiscoverSensor();
}
private static void kinectSensorsStatusChanged(object sender, StatusChangedEventArgs e)
{
KinectSensor oldSensor = Kinect;
if (oldSensor != null)
{
UninitializeKinect();
}
var status = e.Status;
if (Kinect == null)
{
//updateStatus(status);
if (e.Status == KinectStatus.Connected)
{
Kinect = e.Sensor;
DiscoverSensor();
}
}
else
{
if (Kinect == e.Sensor)
{
//updateStatus(status);
if (e.Status == KinectStatus.Disconnected ||
e.Status == KinectStatus.NotPowered)
{
Kinect = null;
sensorConflict = false;
DiscoverSensor();
}
}
}
}
private static DispatcherTimer readyTimer;
private static void UninitializeKinect()
{
if (speechRecognizer != null && Kinect != null)
{
Kinect.AudioSource.Stop();
Kinect.SkeletonFrameReady -= kinect_SkeletonFrameReady;
Kinect.SkeletonStream.Disable();
Kinect.Stop();
//this.FrameSkeletons = null;
speechRecognizer.RecognizeAsyncCancel();
speechRecognizer.RecognizeAsyncStop();
}
if (readyTimer != null)
{
readyTimer.Stop();
readyTimer = null;
}
}
I'm trying to write an application that senses when someone taps and holds something. I am using windows forms. I tried using the mouse down even but it doesn't appear to fire all the time. This is also going to be a multi touch application. I'm going to have two buttons , and the user can tap and hold one button, while they press on the other button. Or Just press one button. I'm not even sure how a windows form app can handle that.
All the examples inhave seen for a windows touch app use xaml. Is this really the only way to capture tap and hold ??
I'm essentially making an onscreen keyboard here, and I don't think that isnpossible WITHOUT windows forms. Correct me if I am wrong here.
Any help or guidance in this is greatly appreciated. Thanks.
If your program is running on Windows 8, you can use the WM_POINTER API to get the input you need. Override WndProc to capture the messages. You will have to do some P/Invoke to get it working, but it's not terribly hard. Here's some incomplete code to get you started, you'll need to add cases for up, down, and update events for each type of pointer you want to track. Keep track of the pointer IDs to process multi touch. To handle the press-and-hold you'll need to track the time yourself from WM_POINTERDOWN to WM_POINTERUP and act accordingly. Hope this helps.
public const int WM_POINTERDOWN = 0x0246;
public const int WM_POINTERUP = 0x0247;
public const int WM_POINTERUPDATE = 0x0245;
public enum POINTER_INPUT_TYPE : int
{
PT_POINTER = 0x00000001,
PT_TOUCH = 0x00000002,
PT_PEN = 0x00000003,
PT_MOUSE = 0x00000004
}
public static uint GET_POINTERID_WPARAM(uint wParam) { return wParam & 0xFFFF; }
[DllImport("User32.dll")]
public static extern bool GetPointerType(uint pPointerID, out POINTER_INPUT_TYPE pPointerType);
protected override void WndProc(ref Message m)
{
bool handled = false;
uint pointerID;
POINTER_INPUT_TYPE pointerType;
switch(m.Message)
{
case WM_POINTERDOWN:
pointerID = User32.GET_POINTERID_WPARAM((uint)m.WParam);
if (User32.GetPointerType(pointerID, out pointerType))
{
switch (pointerType)
{
case POINTER_INPUT_TYPE.PT_PEN:
// Stylus Down
handled = true;
break;
case POINTER_INPUT_TYPE.PT_TOUCH:
// Touch down
handled = true;
break;
}
}
break;
}
if (handled)
m.Result = (IntPtr)1;
base.WndProc(ref m);
}
This question has been around for a while and might benefit from a simple approach. You can simulate the "tap and hold" (or click and hold) by measuring the time between the MouseDown event and the Click event (which fires before MouseUp). If the time is greater than some value then you cancel the Click and (perhaps) fire your own TapAndHold event. I have created a test control that anyone can use to try this approach out. Just add a UserControl to your test app (I called mine TestTapAndHold) and then paste in the following:
public partial class TestTapAndHold : UserControl
{
private string showText = "Tap Me";
private DateTime mouseDown;
private const int holdTime = 500;
public TestTapAndHold()
{
InitializeComponent();
this.Paint += drawText;
}
public delegate void OnTapAndHold(EventArgs e);
public event OnTapAndHold TapAndHold;
private void drawText(object sender, PaintEventArgs e)
{
using (var drawBrush = new SolidBrush(Color.Black))
{
e.Graphics.DrawString(showText, Font, drawBrush, new Point(5,3));
}
}
protected override void OnClick(EventArgs e)
{
if (DateTime.Now.Subtract(mouseDown).Milliseconds >= holdTime)
{
showText = "Tap Hold";
TapAndHold?.Invoke(e);
} else
{
base.OnClick(e);
showText = "Tapped";
}
Invalidate();
}
private void TestTapAndHold_MouseDown(object sender, MouseEventArgs e)
{
mouseDown = DateTime.Now;
}
}
Build the app and then pop one of the test controls onto a form. You can then add an event handler to your form like:
private void testTapAndHold1_TapAndHold(EventArgs e)
{
MessageBox.Show("You tapped and Held");
}
This general approach enabled me to add "Tap and Hold" functionality to a Windows Forms app running on a Microsoft Surface 4
I've got a .Net 3.5 C# Winforms app. It's got no GUI as such, just a NotifyIcon with a ContextMenu.
I've tried to set the NotifyIcon to visible=false and dispose of it in the Application_Exit event, as follows:
if (notifyIcon != null)
{
notifyIcon.Visible = false;
notifyIcon.Dispose();
}
The app gets to the code inside the brackets, but throws a null ref exception when it tries to set Visible = false.
I've read in a few places to put it in the form closing event, but that code never gets hit (maybe as I don't have a form showing as such?).
Where can I put this code so it actually works? If I don't put it in, I get the annoying lingering icon in the tray until you move the mouse over it.
Cheers.
EDIT
Just something extra I've noticed...........
I'm using ClickOnce in the app.........if I just exit the app via the ContextMenu on the NotifyIcon, no exception is logged.
Just when the Application_Exit event is fired after the applicaiton has checked for an upgrade here..
private void CheckForUpdate()
{
EventLogger.Instance.LogEvent("Checking for Update");
if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.CheckForUpdate())
{
EventLogger.Instance.LogEvent("Update available - updating");
ApplicationDeployment.CurrentDeployment.Update();
Application.Restart();
}
}
Does this help?
On Windows 7, I had to also set the Icon property to null. Otherwise, the icon remained in the tray's "hidden icons" popup after the application had closed. HTH somebody.
// put this inside the window's class constructor
Application.ApplicationExit += new EventHandler(this.OnApplicationExit);
private void OnApplicationExit(object sender, EventArgs e)
{
try
{
if (trayIcon != null)
{
trayIcon.Visible = false;
trayIcon.Icon = null; // required to make icon disappear
trayIcon.Dispose();
trayIcon = null;
}
}
catch (Exception ex)
{
// handle the error
}
}
This code works for me, but I don't know how you are keeping your application alive, so... without further ado:
using System;
using System.Drawing;
using System.Windows.Forms;
static class Program
{
static System.Threading.Timer test =
new System.Threading.Timer(Ticked, null, 5000, 0);
[STAThread]
static void Main(string[] args)
{
NotifyIcon ni = new NotifyIcon();
ni.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
ni.Visible = true;
Application.Run();
ni.Visible = false;
}
static void Ticked(object o) {
Application.Exit();
}
}
This is what I'm doing in WPF.
I am using this in conjunction to David Anson's Minimize to tray sample app, which lets you hook up a tray icon to a window (you may have multiple windows open).
Just added this code to the constructor for MinimizeToTrayInstance.
_window.Closed += (s, e) =>
{
if (_notifyIcon != null)
{
_notifyIcon.Visible = false;
_notifyIcon.Dispose();
_notifyIcon = null;
}
};
Sometimes Application_Exit event can be raised several times
Just put notifyIcon = null; in the end
if (notifyIcon != null)
{
notifyIcon.Visible = false;
notifyIcon.Dispose();
notifyIcon = null;
}
This code worked for me
this.Closed += (a, b) =>
{
if (notifyIcon1 != null)
{
notifyIcon1.Dispose();
notifyIcon1.Icon = null;
notifyIcon1.Visible = false;
}
};
Have you overridden the dispose method of the object where you've initialised the notifyIcon to also dispose the notifyIcon?
protected override void Dispose(bool disposing)
{
if (disposing)
{
notifyIcon.Dispose();
notifyIcon = null;
}
base.Dispose(disposing);
}
before im sorry for my bad english.
if u use "end" for exit program. then dont close notify icon.
before u will close notifyicon later close form.
u need to use me.close() for run form closing
example
its work...
notifyIcon1.Icon = Nothing
notifyIcon1.Visible = False
notifyIcon1.Dispose()
Me.Close()
but its not work
End
or only
Me.Close()
The 'click sound' in question is actually a system wide preference, so I only want it to be disabled when my application has focus and then re-enable when the application closes/loses focus.
Originally, I wanted to ask this question here on stackoverflow, but I was not yet in the beta. So, after googling for the answer and finding only a little bit of information on it I came up with the following and decided to post it here now that I'm in the beta.
using System;
using Microsoft.Win32;
namespace HowTo
{
class WebClickSound
{
/// <summary>
/// Enables or disables the web browser navigating click sound.
/// </summary>
public static bool Enabled
{
get
{
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string keyValue = (string)key.GetValue(null);
return String.IsNullOrEmpty(keyValue) == false && keyValue != "\"\"";
}
set
{
string keyValue;
if (value)
{
keyValue = "%SystemRoot%\\Media\\";
if (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor > 0)
{
// XP
keyValue += "Windows XP Start.wav";
}
else if (Environment.OSVersion.Version.Major == 6)
{
// Vista
keyValue += "Windows Navigation Start.wav";
}
else
{
// Don't know the file name so I won't be able to re-enable it
return;
}
}
else
{
keyValue = "\"\"";
}
// Open and set the key that points to the file
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, keyValue, RegistryValueKind.ExpandString);
isEnabled = value;
}
}
}
}
Then in the main form we use the above code in these 3 events:
Activated
Deactivated
FormClosing
private void Form1_Activated(object sender, EventArgs e)
{
// Disable the sound when the program has focus
WebClickSound.Enabled = false;
}
private void Form1_Deactivate(object sender, EventArgs e)
{
// Enable the sound when the program is out of focus
WebClickSound.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Enable the sound on app exit
WebClickSound.Enabled = true;
}
The one problem I see currently is if the program crashes they won't have the click sound until they re-launch my application, but they wouldn't know to do that.
What do you guys think? Is this a good solution? What improvements can be made?
const int FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
const int SET_FEATURE_ON_PROCESS = 0x00000002;
[DllImport("urlmon.dll")]
[PreserveSig]
[return: MarshalAs(UnmanagedType.Error)]
static extern int CoInternetSetFeatureEnabled(int FeatureEntry,
[MarshalAs(UnmanagedType.U4)] int dwFlags,
bool fEnable);
static void DisableClickSounds()
{
CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS,
SET_FEATURE_ON_PROCESS,
true);
}
I've noticed that if you use WebBrowser.Document.Write rather than WebBrowser.DocumentText then the click sound doesn't happen.
So instead of this:
webBrowser1.DocumentText = "<h1>Hello, world!</h1>";
try this:
webBrowser1.Document.OpenNew(true);
webBrowser1.Document.Write("<h1>Hello, world!</h1>");
You disable it by changing Internet Explorer registry value of navigating sound to "NULL":
Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","NULL");
And enable it by changing Internet Explorer registry value of navigating sound to "C:\Windows\Media\Cityscape\Windows Navigation Start.wav":
Registry.SetValue("HKEY_CURRENT_USER\\AppEvents\\Schemes\\Apps\\Explorer\\Navigating\\.Current","","C:\Windows\Media\Cityscape\Windows Navigation Start.wav");
Definitely feels like a hack, but having done some research on this a long time ago and not finding any other solutions, probably your best bet.
Better yet would be designing your application so it doesn't require many annoying page reloads.. for example, if you're refreshing an iframe to check for updates on the server, use XMLHttpRequest instead. (Can you tell that I was dealing with this problem back in the days before the term "AJAX" was coined?)
If you want to use replacing Windows Registry, use this:
// backup value
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current");
string BACKUP_keyValue = (string)key.GetValue(null);
// write nothing
key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, "", RegistryValueKind.ExpandString);
// do navigation ...
// write backup key
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"AppEvents\Schemes\Apps\Explorer\Navigating\.Current", true);
key.SetValue(null, BACKUP_keyValue, RegistryValueKind.ExpandString);