Disabling Windows keys while UWP is running - c#

I'm building a universal Windows app and need to lock down the desktop so that the user can't escape out of the program. So I need to temporarily disable the Windows key and ctrl + alt + del.
I was able to add a event handler like so:
Window.Current.CoreWindow.KeyDown += (s, e) =>
{
if(e.VirtualKey == VirtualKey.LeftWindows || e.VirtualKey == VirtualKey.RightWindows)
{
e.Handled = true;
}
}
But the keypress event still fires.
I also found a method using what I believe are Windows hooks from the user32 lib.
[DllImport("user32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool RegisterHotKey(IntPtr hwnd, int id, uint fsModifiers, uint vk);
[DllImport("user32", SetLastError = true)]
public static extern int UnregisterHotKey(IntPtr hwnd, int id);
[DllImport("kernel32", SetLastError = true)]
I found some sample code here, but I think I'll have to tweak it for a simple Windows key press.
Is the Windows hook method (as used in the example link) the way to go?

I think Kiosk apps for assigned access was very close to your requirement. This document describes how to implement a kiosk app. You could use the Lock framework and assigned access to create a kiosk app that enables users to interact with a single app on a device.
Set up a kiosk on Windows 10 Pro, Enterprise, or Education for your reference.

Related

How to make Console App listen for keypresses from other processes?

I'm new to C# programming and I'm attempting to write a Console App that will run in the background and perform an action when a key is pressed (ideally I would like to know how to do this for any key but, if that's not possible, then a specific key).
Here's an idea of what I want (please excuse and feel free to correct any bad coding as I'm just starting out).
public static void Main(string[] args)
{
while(true)
{
ConsoleKeyInfo cki = Console.ReadKey();
if( cki.Key == ConsoleKey.R )
{
Console.WriteLine("Run me");
}
}
}
The above seems to work but only if the Console App is in focus. I would like it to happen even if the app isn't in focus.
I've done some research and read about registering 'hotkeys' but also read that this is dangerous in case another application is requiring that key?
I've also read similar questions on here but they seem to deal with Windows Forms and not just Console Apps.
Can anyone help shed any light on this?
You need to use
[DllImport("user32", SetLastError = true)]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32", SetLastError = true)]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
But to make it work from console you'll need to create hidden form that will handle messages for you. Check out this class. It does exactly what you want.

Resize windows using Java or C#

I'd like to create an application where I can resize Windows forms.
I can iterate through windows and get certain properties like so for example:
How to iterate through window elements using JNA?
I've found similar ones, but can I resize and relocate these windows rather than just getting their attributes like title and rect? I'd like to sort all visible windows as a tile but I can't figure out how I can manipulate their position.
For example, I want to grab and resize Total Commander and Notepadd++ (the 2 visible windows) to be on the left and right half of the screen.
Is it possible? If anyone can show me a snippet I'd be grateful.
Easiest way would be to enumerate all window instances in system and call proper WinAPI function like described here
C#: You can obtain all the windows you can use this code:
internal static class WindowsEnumeratorNativeMethods {
[return: MarshalAs(UnmanagedType.Bool)]
internal delegate Boolean EnumerationCallback(IntPtr handle, IntPtr parameter);
[DllImport("User32.dll",
CallingConvention = CallingConvention.Winapi,
ExactSpelling = true,
EntryPoint = "EnumWindows",
CharSet = CharSet.Unicode,
SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern Boolean EnumWindows(EnumerationCallback lpEnumFunc,
IntPtr lParam);
}
...
List<IntPtr> handles = new List<IntPtr>();
WindowsEnumeratorNativeMethods.EnumWindows(
(h, p) => {
handles.Add(h);
return true;},
IntPtr.Zero);
Next you should find out the required windows (Notepad++ etc). You can do it
by looking for windows' captions (see GetWindowText API function); to move/size
the window use SetWindowPos API function.
While implementing API wrappers, you may find this useful:
http://www.pinvoke.net/

User32.dll: RegisterHotkey not found

I recently made a program in Visual C# .NET 2010 as Windows Forms Application using Visual Studio 2010. This program uses global Hotkeys through the user32.dll-function "RegisterHotkey".
Everything worked just fine.
I was able to show a MessageBox when a registered Hotkey was pressed (for example).
Then, today, after some strange Errors in Visual Studio (which had nothing to do with Hotkey) (in fact it was just an image that wasn't loaded) the RegisterHotkey function doesn't work anymore.
I didn't change anything in the hotkey code.
When I debug in Visual Studio, I get no exception.
With a breakpoint I found out that the code stopped at the RegisterHotkey function.
When I execute the .exe file from the "debug" folder of the project the program shows an error that states that the "entry point "RegisterHotkey" wasn't found in the "user32" DLL".
Which is strange, cause it worked the whole time.
To check if my project or code was the reason, I created a new Windows Forms Application and entered the code:
using System.Runtime.InteropServices;
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int RegisterHotkey(IntPtr Hwnd, int ID, int Modifiers, int Key);
[DllImport("kernel32", EntryPoint = "GlobalAddAtomA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern short GlobalAddAtom(string IDString);
private void Form1_Load(object sender, EventArgs e)
{
int atomid = GlobalAddAtom("hallo");
RegisterHotkey(this.Handle, atomid, 0, (int)Keys.A);
}
}
}
Which produced the same error. The error occurs when trying to call the RegisterHotkey function. I tried to enter the least amount of code possible this time.
The form has no controls and all it is supposed to do it registering a hotkey in its Load event.
My question is:
Can anybody tell me why RegisterHotkey isn't found anymore all of sudden?
Did I make a mistake anywhere?
And what can I do to make it work again?
I tried to import "user32.dll" instead of "user32" but it didn't change anything except for the text in the error message. There, "user32" was replaced by "user32.dll".
EDIT: I don't know if it's relevant or not but I use Windows 7 Professional 64 bit version and .NET framework 4.0 (not the client profile)
It probably happens because the function name is RegisterHotKey, with capital K, not RegisterHotkey.
Try to declare it exactly as described on pinvoke.net:
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

Programmatically change cursor speed in windows

Since getting a satisfactory answer on SuperUser is very difficult, I want to rephrase this question and ask:
Is there any way to programmatically detect a mouse was plugged in the usb port, and change the cursor speed in windows (perhaps through an API)?
I'd like to use C#, but I'm open to any language that can run on a windows 7 machine.
I don't know about the detection but you can use P/Invoke to the SystemParametersInfo api using
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SystemParametersInfo(SPI uiAction, uint uiParam, String pvParam, SPIF fWinIni);
with the uiAction as (SPI_SETMOUSESPEED) = 0x0071

Accessing GPS Data From a .Net Winform Application

Does anyone out there have any experience programatically retreiving the lat/long from a GPS attached to a mobile PC? A team I'm on is currently looking at hardware options--as the programmer who will eventually have to live with whatever is selected I was wondering if anyone out there has had experience writing .Net programs that interface with a GPS? Any recomendations for hardware and/or programming would be greatly appreciated.
As I envision it, my application will need to ask the GPS for the current lat/long perhaps once every 10 to 20 seconds.
I've written such an application before.
As Henk said, you listen on a COM port. Build a component that reads the com stream in, in say a 1024 buffer. that'll be plenty to contain at least 1 complete NMEA sentence. From there, read the input until you find the start of a sentence and parse it. If for some reason you don't have the full sentence, read in another buffer, append and continue/try again.
If you're willing to be dependent on Windows 7, there's a Location API that handles the NMEA decoding for you.
If the Gps is integrated within your windows CE PC or windows mobile phone, you can simply use the GPS Intermediate Driver to pool for information.
Since you are in a .net environment, you could create a .Net wrapper to this native API.
public class GpsHardware
{
private const string gpsLibraryName = "gpsapi.dll";
private const string coreLibraryName = "coredll.dll";
[DllImport(GpsHardware.coreLibraryName, SetLastError = false)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EventModify(IntPtr hEvent, uint function);
[DllImport(GpsHardware.gpsLibraryName, SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr GPSOpenDevice(IntPtr hNewLocationData, IntPtr hDeviceStateChange, string szDeviceName, uint dwFlags);
[DllImport(GpsHardware.gpsLibraryName, SetLastError = true)]
private static extern uint GPSCloseDevice(IntPtr hGPSDevice);
[DllImport(GpsHardware.gpsLibraryName, SetLastError = true)]
private static extern uint GPSGetPosition(IntPtr hGPSDevice, IntPtr pGPSPosition, uint dwMaximumAge, uint dwFlags);
[DllImport(GpsHardware.gpsLibraryName, SetLastError = true)]
private static extern uint GPSGetDeviceState(IntPtr pGPSDevice);
...
}
Of course you will have to deal with marshaling and all the great interop things :)

Categories

Resources