Dynamically changing Mouse speed - c#

Guys, I have a C# Winforms application with a panel inside the form. What I want to do is, whenever the mouse pointer enters this panel, I want to slow the movement speed of the mouse by 50%. Once the pointer moves outside this panel, I want to speed of the mouse to resume normal 100% speed. How can I accomplish this in C#?

This article might help
Here's the code from the article:
using System;
using System.Runtime.InteropServices;
namespace MouseSpeedSwitcher
{
class Program
{
public const UInt32 SPI_SETMOUSESPEED = 0x0071;
[DllImport("User32.dll")]
static extern Boolean SystemParametersInfo(
UInt32 uiAction,
UInt32 uiParam,
UInt32 pvParam,
UInt32 fWinIni);
static void Main(string[] args)
{
SystemParametersInfo(
SPI_SETMOUSESPEED,
0,
uint.Parse(args[0]),
0);
}
}
}

using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public const UInt32 SPI_GETMOUSESPEED = 0x0070;
const UInt32 SPIF_UPDATEINIFILE = 0x01;
const UInt32 SPIF_SENDWININICHANGE = 0x02;
[DllImport("User32.dll")]
static extern Boolean SystemParametersInfo(
UInt32 uiAction,
UInt32 uiParam,
IntPtr pvParam,
UInt32 fWinIni);
static unsafe void Main(string[] args)
{
MouseOptions m = new MouseOptions();
MouseOptions.GetDefaults();
int speed;
SystemParametersInfo(SPI_GETMOUSESPEED, 0, new IntPtr(&speed), 0);
Console.WriteLine(speed);
MouseOptions.SetDefaults();
SystemParametersInfo(SPI_GETMOUSESPEED, 0, new IntPtr(&speed), 0);
Console.WriteLine(speed);
Console.ReadLine();
}
public class MouseOptions
{
[DllImport("user32.dll")]
public static extern int SystemParametersInfo( int uAction, int uParam, IntPtr lpvParam, int fuWinIni );
[DllImport("kernel32.dll")]
public static extern int GetLastError();
public const int SPI_GETMOUSESPEED = 112;
public const int SPI_SETMOUSESPEED = 113;
private static int intDefaulSpeed = 10;
private static int intCurrentSpeed;
private static int intNewSpeed;
public static void GetDefaults()
{
intCurrentSpeed = GetMouseSpeed();
}
public static void SetDefaults()
{
if ( intCurrentSpeed == 20 )
{
SetMouseSpeed(intDefaulSpeed);
}
else if ( intCurrentSpeed < 10 )
{
SetMouseSpeed(intDefaulSpeed);
}
}
public static int GetMouseSpeed()
{
int intSpeed = 0;
IntPtr ptr;
ptr = Marshal.AllocCoTaskMem(4);
SystemParametersInfo(SPI_GETMOUSESPEED, 0, ptr, 0);
intSpeed = Marshal.ReadInt32(ptr);
Marshal.FreeCoTaskMem(ptr);
return intSpeed;
}
public static void SetMouseSpeed( int intSpeed )
{
IntPtr ptr = new IntPtr(intSpeed);
int b = SystemParametersInfo(SPI_SETMOUSESPEED, 0, ptr, 0);
if (b == 0)
{
Console.WriteLine("Not able to set speed");
}
else if ( b == 1 )
{
Console.WriteLine("Successfully done");
}
}
}
}
}

As it was not very clear how to use code from the answers, I found more concise solution for changing Mouse speed. Add this code to class where you want to change the speed:
[DllImport("user32.dll", CharSet = CharSet.Auto),]
public static extern int SystemParametersInfo(uint uiAction, uint uiParam, uint pvParam, uint fWinIni);
And then call SystemParametersInfo with required Mouse speed:
//SPEED is an integer value between 0 and 20. 10 is the default.
SystemParametersInfo(113,0,SPEED,0);
Not forget to add using System.Runtime.InteropServices; Credits.

Related

Mouse move in game window by outer C# code

I am playing a game, every time I need to move mouse and click into the game's screen to earn game point, so I am trying to write code by c# to click and move mouse in game's screen automatically ..
I got some help, so mouse click problems solved, but I am unable to move mouse in game's screen..
Can you please advice me what should I do ??
Should I use "SetWindowsHookEx" or other methods to move mouse in game window ??
Please advice me what should I do..
"Click" code below which I got, it's working fine :
public class ClickGameScreen
{
[DllImport("user32.dll")]
static extern bool ClientToScreen(IntPtr hWnd, ref Point lpPoint);
[DllImport("user32.dll")]
internal static extern uint SendInput(uint nInputs, [MarshalAs(UnmanagedType.LPArray), In] INPUT[] pInputs, int cbSize);
internal struct INPUT
{
public UInt32 Type;
public MOUSEKEYBDHARDWAREINPUT Data;
}
[StructLayout(LayoutKind.Explicit)]
internal struct MOUSEKEYBDHARDWAREINPUT
{
[FieldOffset(0)]
public MOUSEINPUT Mouse;
}
internal struct MOUSEINPUT
{
public Int32 X;
public Int32 Y;
public UInt32 MouseData;
public UInt32 Flags;
public UInt32 Time;
public IntPtr ExtraInfo;
}
public static void ClickScreen(IntPtr W_Handle , Point C_Point)
{
var oldPos = Cursor.Position;
ClientToScreen(W_Handle, ref C_Point);
Cursor.Position = new Point(C_Point.X, C_Point.Y);
var inputDown = new INPUT();
inputDown.Type = 0;
inputDown.Data.Mouse.Flags = 0x0002;
var inputUp = new INPUT();
inputUp.Type = 0;
inputUp.Data.Mouse.Flags = 0x0004;
var inputs = new INPUT[] { inputDown, inputUp };
SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
Cursor.Position = oldPos;
}
}
==============
ClickScreen(this.Handle, new Point(375, 340));
===============
I solved my problem, code below :
[DllImport("user32.dll")]
static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
private const int MOUSEEVENTF_MOVE = 0x0001;
public static void Move(int xDelta, int yDelta)
{
mouse_event(MOUSEEVENTF_MOVE, xDelta, yDelta, 0, 0);
}
//=========================================
Move(830, 160);
//=========================================

Create a full screen application

We want our application to run in full screen mode with no title bar on a Win CE 5.0 powered device. The application is being developed using .NET Compact Framework 3.5 (C#).
I have followed this tutorial, but I encountered an error. Here is my code:
namespace DatalogicDeviceControl
{
public partial class Form1 : Form
{
public const int SWP_ASYNCWINDOWPOS = 0x4000;
public const int SWP_DEFERERASE = 0x2000;
public const int SWP_DRAWFRAME = 0x0020;
public const int SWP_FRAMECHANGED = 0x0020;
public const int SWP_HIDEWINDOW = 0x0080;
public const int SWP_NOACTIVATE = 0x0010;
public const int SWP_NOCOPYBITS = 0x0100;
public const int SWP_NOMOVE = 0x0002;
public const int SWP_NOOWNERZORDER = 0x0200;
public const int SWP_NOREDRAW = 0x0008;
public const int SWP_NOREPOSITION = 0x0200;
public const int SWP_NOSENDCHANGING = 0x0400;
public const int SWP_NOSIZE = 0x0001;
public const int SWP_NOZORDER = 0x0004;
public const int SWP_SHOWWINDOW = 0x0040;
public const int HWND_TOP = 0;
public const int HWND_BOTTOM = 1;
public const int HWND_TOPMOST = -1;
public const int HWND_NOTOPMOST = -2;
public Form1()
{
InitializeComponent();
HideStartBar();
}
[DllImport("coredll.dll", EntryPoint = "FindWindowW", SetLastError = true)]
private static extern IntPtr FindWindowCE(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
public void HideStartBar()
{
IntPtr handle;
try
{
// Find the handle to the Start Bar
handle = FindWindowCE("HHTaskBar", null);
// If the handle is found then hide the start bar
if (handle != IntPtr.Zero)
{
// Hide the start bar
SetWindowPos(handle, 0, 0, 0, 0, 0, SWP_HIDEWINDOW);
}
}
catch
{
MessageBox.Show("Could not hide Start Bar.");
}
}
}
}
I have encountered the following error:
The best overloaded method match for 'DatalogicDeviceControl.Form1.SetWindowPos(System.IntPtr, int, int, int, int, uint)' has some invalid arguments
#dzerow: Your answer is correct: Windows Mobile does not support the user32.dll library.
Use the coredll.dll library instead.
private const int SRCCOPY = 0x00CC0020;
private const string CORE_DLL = "coredll.dll";
private static IntPtr _taskBar;
private static IntPtr _sipButton;
private static string _deviceId, _deviceIp;
private static DateTime _lastUpdateCheck, _startTime;
[DllImport(CORE_DLL)]
public static extern int BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop);
[DllImport(CORE_DLL)]
public static extern bool CeRunAppAtEvent(string appName, int Event);
[DllImport(CORE_DLL, EntryPoint = "FindWindowW", SetLastError = true)]
public static extern IntPtr FindWindowCE(string lpClassName, string lpWindowName);
[DllImport(CORE_DLL)]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport(CORE_DLL)]
public static extern bool MessageBeep(int uType);
[DllImport(CORE_DLL, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
Below is a lot of the code from an application I used to manage. Parts of it may be incomplete and there could be too much info. If something is missing, just comment and I will fill that in.
Basically, the routine I have written enables you to call ShowWindowsMenu(bool enable) to either enable or disable the HHTaskBar (task bar) and the MS_SIPBUTTON (soft input button).
public static void ShowWindowsMenu(bool enable) {
try {
if (enable) {
if (_taskBar != IntPtr.Zero) {
SetWindowPos(_taskBar, IntPtr.Zero, 0, 0, 240, 26, (int)WindowPosition.SWP_SHOWWINDOW); // display the start bar
}
} else {
_taskBar = FindWindowCE("HHTaskBar", null); // Find the handle to the Start Bar
if (_taskBar != IntPtr.Zero) { // If the handle is found then hide the start bar
SetWindowPos(_taskBar, IntPtr.Zero, 0, 0, 0, 0, (int)WindowPosition.SWP_HIDEWINDOW); // Hide the start bar
}
}
} catch (Exception err) {
ErrorWrapper(enable ? "Show Start" : "Hide Start", err);
}
try {
if (enable) {
if (_sipButton != IntPtr.Zero) { // If the handle is found then hide the start bar
SetWindowPos(_sipButton, IntPtr.Zero, 0, 0, 240, 26, (int)WindowPosition.SWP_SHOWWINDOW); // display the start bar
}
} else {
_sipButton = FindWindowCE("MS_SIPBUTTON", "MS_SIPBUTTON");
if (_sipButton != IntPtr.Zero) { // If the handle is found then hide the start bar
SetWindowPos(_sipButton, IntPtr.Zero, 0, 0, 0, 0, (int)WindowPosition.SWP_HIDEWINDOW); // Hide the start bar
}
}
} catch (Exception err) {
ErrorWrapper(enable ? "Show SIP" : "Hide SIP", err);
}
}
Be sure to turn these features back on when your program exits, or the user will have to reboot the device to get those re-enabled.
EDIT: I forgot the WindowPosition enumerated value I created:
public enum WindowPosition {
SWP_HIDEWINDOW = 0x0080,
SWP_SHOWWINDOW = 0x0040
}
Sorry about that.
Anything else?
Unfortunately Windows Mobile doesn't contain user32.dll, as well as many other normal Windows API DLLs. I had to P/Invoke into coredll.dll instead. For signatures, see PInvoke.net's section (at the bottom left) for "Smart Device Functions".

Emulating of keyboard events not working C#

I'm trying to emulate some key events by using WinAPI. I want to press a WIN-key, but my code is not working. In example i use VK_F1 for every proc.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ConsoleApplication69
{
class Program
{
const UInt32 WM_KEYDOWN = 0x0100;
const UInt32 WM_KEYUP = 0x0101;
const int VK_F1 = 112;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
static void Main(string[] args)
{
Process[] processes = Process.GetProcesses();
foreach (Process proc in processes)
{
SendMessage(proc.MainWindowHandle, WM_KEYDOWN, new IntPtr(VK_F1), IntPtr.Zero);
SendMessage(proc.MainWindowHandle, WM_KEYUP, new IntPtr(VK_F1), IntPtr.Zero);
}
}
}
}
To simulate keyboard input, use SendInput. That's exactly what this API does. "Sending F1 to every window" is not a good idea, because you'll be sending keystrokes to windows that don't have keyboard focus. Who knows how they'll respond.
There are a lot more nuances to keyboard input than you're accounting for; See this question for considerations about emulating keyboard input.
So I used code from this url: SendKeys.Send and Windows Key
And it works fine!
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ConsoleApplication69
{
class Program
{
static void Main(string[] args)
{
KeyboardSend.KeyDown(Keys.LWin);
KeyboardSend.KeyUp(Keys.LWin);
}
}
static class KeyboardSend
{
[DllImport("user32.dll")]
private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
private const int KEYEVENTF_EXTENDEDKEY = 1;
private const int KEYEVENTF_KEYUP = 2;
public static void KeyDown(Keys vKey)
{
keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY, 0);
}
public static void KeyUp(Keys vKey)
{
keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
}
}
tnx for help everybody!

SetupDiEnumDeviceInterfaces() always returns false - C# WPF

I am trying to connect to a USB device that is detected as a CDC device on my system using the following code :
(I have presented only the part of the code relevant to my problem)
The code compiles fine and SetupDiGetClassDevs function runs ok too.
But SetupDiEnumDeviceInterfaces always returns false and because of this I am not able to move any further. Please tell me where it is wrong. Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO.Ports;
//**************************************************************
// Static class for access to USB dll for all the activity
// related to USB device
//**************************************************************
namespace USBDeviceConnect
{
#region Unmanaged
public class Native
{
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetupDiGetClassDevs(
ref Guid ClassGuid,
IntPtr Enumerator,
IntPtr hwndParent,
UInt32 Flags);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern bool SetupDiEnumDeviceInterfaces(
IntPtr hDevInfo,
SP_DEVINFO_DATA devInfo,
ref Guid interfaceClassGuid,
UInt32 memberIndex,
ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
[DllImport(#"setupapi.dll", CharSet = CharSet.Auto)]
public static extern Boolean SetupDiEnumDeviceInterfaces(
IntPtr hDevInfo,
IntPtr devInfo,
ref Guid interfaceClassGuid,
UInt32 memberIndex,
ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern int SetupDiDestroyDeviceInfoList(
IntPtr DeviceInfoSet);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern bool SetupDiEnumDeviceInfo(
IntPtr DeviceInfoSet,
UInt32 MemberIndex,
ref SP_DEVINFO_DATA DeviceInfoData);
//SP_DEVINFO_DATA
[StructLayout(LayoutKind.Sequential)]
public struct SP_DEVINFO_DATA
{
public int cbSize;
public Guid ClassGuid;
public int DevInst;
public ulong Reserved;
}
[StructLayout(LayoutKind.Sequential)]
public class SP_DEVICE_INTERFACE_DATA
{
public int cbSize;
public Guid interfaceClassGuid;
public int flags;
public ulong reserved;
};
//PARMS
public const int DIGCF_ALLCLASSES = (0x00000004);
public const int DIGCF_PRESENT = (0x00000002);
public const int DIGCF_PROFILE = (0x00000008);
public const int DIGCF_DEVICEINTERFACE = (0x00000010);
public const int INVALID_HANDLE_VALUE = -1;
public const int MAX_DEV_LEN = 1000;
public const int DEVICE_NOTIFY_WINDOW_HANDLE = (0x00000000);
public const int DEVICE_NOTIFY_SERVICE_HANDLE = (0x00000001);
public const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = (0x00000004);
public const int DBT_DEVTYP_DEVICEINTERFACE = (0x00000005);
public const int DBT_DEVNODES_CHANGED = (0x0007);
public const int WM_DEVICECHANGE = (0x0219);
public const int DIF_PROPERTYCHANGE = (0x00000012);
public const int DICS_FLAG_GLOBAL = (0x00000001);
public const int DICS_FLAG_CONFIGSPECIFIC = (0x00000002);
public const int DICS_ENABLE = (0x00000001);
public const int DICS_DISABLE = (0x00000002);
public const long ERROR_NO_MORE_ITEMS = 259L;
public const int ERROR_SUCCESS = 0;
}
#endregion
/****************************************************************************/
static class AccessUSB
{
public static void Main()
{
ConnectToDevice();
}
/* Execution starts here */
public static void ConnectToDevice()
{
/* Get the info of all connected devices */
//Globally Unique Identifier (GUID) for CDC class devices.
Guid InterfaceClassGuid = new Guid("a5dcbf10653011d2901f00c04fb951ed");
IntPtr DeviceInfoTable = (IntPtr)Native.INVALID_HANDLE_VALUE;
Native.SP_DEVICE_INTERFACE_DATA InterfaceDataStructure = new Native.SP_DEVICE_INTERFACE_DATA();
Native.SP_DEVINFO_DATA DevInfoData = new Native.SP_DEVINFO_DATA();
uint InterfaceIndex = 0;
uint ErrorStatus;
StringBuilder DeviceName = new StringBuilder();
DeviceInfoTable = Native.SetupDiGetClassDevs(ref InterfaceClassGuid, IntPtr.Zero, IntPtr.Zero, Native.DIGCF_PRESENT | Native.DIGCF_DEVICEINTERFACE);
if (DeviceInfoTable.ToInt32() != Native.INVALID_HANDLE_VALUE)
{
//Initialize an appropriate SP_DEVINFO_DATA structure.
DevInfoData.cbSize = Marshal.SizeOf(DevInfoData);
while (true)
{
InterfaceDataStructure.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(InterfaceDataStructure);
bool bRslt = Native.SetupDiEnumDeviceInterfaces(DeviceInfoTable, IntPtr.Zero, ref InterfaceClassGuid, InterfaceIndex, ref InterfaceDataStructure);
if (bRslt == true)
{
ErrorStatus = (uint)System.Runtime.InteropServices.Marshal.GetLastWin32Error();
if (Native.ERROR_NO_MORE_ITEMS == ErrorStatus)
{
Native.SetupDiDestroyDeviceInfoList(DeviceInfoTable);//Clean up the old structure we no longer need.
return;
}
}
else //Else some other kind of unknown error ocurred...
{
ErrorStatus = (uint)System.Runtime.InteropServices.Marshal.GetLastWin32Error();
Native.SetupDiDestroyDeviceInfoList(DeviceInfoTable); //Clean up the old structure we no longer need.
return;
}
InterfaceIndex++;
}//end of while(true)
}
}
}
}
I'm not sure why you are trying to use SetupAPI. If it is a detected as a CDC ACM device, then it should have the usbser.sys driver associated with it, and it should show a COM port number in the Device Manager, and you can connect to that COM port using the .NET SerialPort class:
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx

how to use RegisterHotKey() in C#? [duplicate]

This question already has answers here:
Global hotkey in console application
(4 answers)
Closed 8 years ago.
I'm trying to register a hot key, I'm translating this C++ code into C#:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("user32.dll")]
public static extern
bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, int vk);
[DllImport("user32")]
public static extern
bool GetMessage(ref Message lpMsg, IntPtr handle, uint mMsgFilterInMain, uint mMsgFilterMax);
public const int MOD_ALT = 0x0001;
public const int MOD_CONTROL = 0x0002;
public const int MOD_SHIFT = 0x004;
public const int MOD_NOREPEAT = 0x400;
public const int WM_HOTKEY = 0x312;
public const int DSIX = 0x36;
static void Main(string[] args)
{
if (!RegisterHotKey(IntPtr.Zero, 1, MOD_ALT | MOD_NOREPEAT, DSIX))
{
Console.WriteLine("failed key register!");
}
Message msg = new Message();
while (!GetMessage(ref msg, IntPtr.Zero, 0, 0))
{
if (msg.message == WM_HOTKEY)
{
Console.WriteLine("do work..");
}
}
Console.ReadLine();
}
}
public class Message
{
public int message { get; set; }
}
}
but RegisterHotKey() never returns false.
I'm not sure about the arguments passed in the method, IntPtr.Zero should be null, and message class constructor's second argument requires an object. any help is very appreciated!
This might help:
Hotkey in console app
Basically, you have to create a "hidden" form to make it work

Categories