I am building a Dotnet Core 3.1 Console application where i want to get and set system's mouse double click speed.
I got success to get the speed using
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern int GetDoubleClickTime();
But not able to set desired values for the same.
I have tried following options but did not get success
SetDoubleClickTime
current system values is 550 received from above method
Passing 200 as Arg1 value to modify.
received output of below method as true but value did not change
Implementation:
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
static extern bool SetDoubleClickTime(uint Arg1);
SystemParametersInfo
I have also tried with SystemParametersInfo
received output of below method as true but value did not change
Implementation:
[DllImport("User32.dll")]
static extern bool SystemParametersInfo(int uiAction, int uiParam, IntPtr ipParam, int fWinIni);
var result= SystemParametersInfo(20, 200, IntPtr.Zero, 2);
This one worked for me even for values as low as 100ms. Did you try to GetDoubleClickTime() after setting it to check whether your value was actually set?
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll")]
public static extern int GetDoubleClickTime();
[DllImport("user32.dll")]
public static extern bool SetDoubleClickTime(uint Arg1);
public static void Main()
{
var time = GetDoubleClickTime();
Console.WriteLine(time);
SetDoubleClickTime(4200);
time = GetDoubleClickTime();
Console.WriteLine(time);
}
}
Related
As the title
I would like the effect like UAC's background
Here is a code I found from web.
using System;
using System.Runtime.InteropServices;
namespace cleandesktop
{
internal static class Program
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SystemParametersInfo(uint uAction, uint uParam, StringBuilder lpvParam, uint init);
const uint SPI_GETDESKWALLPAPER = 0x0073;
static void Main(string[]) args
{
StringBuilder wallPaperPath = new StringBuilder(200);
if (SystemParametersInfo(SPI_GETDESKWALLPAPER, 200, wallPaperPath, 0))
{
MessageBox.Show(wallPaperPath.ToString());
}
}
}
}
This code get the path of the wallpaper picture, but this code only works when users hadn't delete their wallpaper picture.
PaintDesktop
The PaintDesktop function fills the clipping region in the specified device context with the desktop pattern or wallpaper.
all!
Please, help me with any advice with my problem: I build GUI WinForms application and now I want to attach console to it. I found this is not as much easy as it seems before. But I found good solution here: How do I show a console output/window in a forms application? Below the code from rag answer.
using System;
using System.Runtime.InteropServices;
namespace SomeProject
{
class GuiRedirect
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(StandardHandle nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetStdHandle(StandardHandle nStdHandle, IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern FileType GetFileType(IntPtr handle);
private enum StandardHandle : uint
{
Input = unchecked((uint)-10),
Output = unchecked((uint)-11),
Error = unchecked((uint)-12)
}
private enum FileType : uint
{
Unknown = 0x0000,
Disk = 0x0001,
Char = 0x0002,
Pipe = 0x0003
}
private static bool IsRedirected(IntPtr handle)
{
FileType fileType = GetFileType(handle);
return (fileType == FileType.Disk) || (fileType == FileType.Pipe);
}
public static void Redirect()
{
if (IsRedirected(GetStdHandle(StandardHandle.Output)))
{
var initialiseOut = Console.Out;
}
bool errorRedirected = IsRedirected(GetStdHandle(StandardHandle.Error));
if (errorRedirected)
{
var initialiseError = Console.Error;
}
AttachConsole(-1);
if (!errorRedirected)
SetStdHandle(StandardHandle.Error, GetStdHandle(StandardHandle.Output));
}
}
This code works as charm except one downside: non-latin letters outputs to console in strange encoding (but if redirected to file, they are in right encoding). I need to redirect both StdOut and StdErr, and if I change any part of the code it stops redirecting.
Thanks to all who share their wisdom with me in comments!
SetConsoleOutputCP was the answer.
Don't forget put this to other definitions of the class.
[DllImport("kernel32.dll")]
static extern bool SetConsoleOutputCP(uint wCodePageID);
And than add call of the SetConsoleOutputCP(desired codepage); to Redirect() method.
Is there a way to call "IsWow64Process" function from kernel32 capitalized? Like "ISWOW64PROCESS"? Or completely lowered like "iswow64process"?
And if no, are there any hack-arrounds to achieve this task? Thanks!
C# is a case sensitive language, but you can define the pinvoke call any way you like, you just need to be consistent. You can map the EntryPoint in your PInvoke call and define the function to be all uppercase like this:
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi, EntryPoint = "IsWow64Process")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool ISWOW64PROCESS([In] IntPtr processHandle,
[Out, MarshalAs(UnmanagedType.Bool)] out bool wow64Process);
private void button1_Click_2(object sender, EventArgs e)
{
bool is64;
ISWOW64PROCESS(Process.GetCurrentProcess().Handle, out is64);
MessageBox.Show(is64.ToString());
}
The DllImportAttribute.EntryPoint field allows you to specify the real name of the imported function.
Directly from the example at that link are two lines that show how you can rename the MessageBox function:
[DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "MessageBox")]
public static extern int MyNewMessageBoxMethod(IntPtr hWnd, String text, String caption, uint type);
I have a C dll with exported functions
I can use the command-line tool dumpbin.exe /EXPORTS to extract the list of exported functions, and then use them in my C# code to (successfully) call these functions.
Is there a way to get this exported-functions-list directly from .NET, without having to use an external command-line tool?
Thanks
As far as I know there is no class in the .Net Framework that
provides the information you need.
However you can use the platform invocation services (PInvoke) of the .Net platform to
use the functions of the Win32 dbghelp.dll DLL. This DLL is part of
the Debugging Tools for the Windows platform. The dbghelp DLL provides
a function called SymEnumerateSymbols64 which allows you to enumerate all
exported symbols of a dynamic link library. There is also a
newer function called SymEnumSymbols which also allows to enumerate
exported symbols.
The code below shows a simple example on how to use the SymEnumerateSymbols64
function.
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SymInitialize(IntPtr hProcess, string UserSearchPath, [MarshalAs(UnmanagedType.Bool)]bool fInvadeProcess);
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SymCleanup(IntPtr hProcess);
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern ulong SymLoadModuleEx(IntPtr hProcess, IntPtr hFile,
string ImageName, string ModuleName, long BaseOfDll, int DllSize, IntPtr Data, int Flags);
[DllImport("dbghelp.dll", SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SymEnumerateSymbols64(IntPtr hProcess,
ulong BaseOfDll, SymEnumerateSymbolsProc64 EnumSymbolsCallback, IntPtr UserContext);
public delegate bool SymEnumerateSymbolsProc64(string SymbolName,
ulong SymbolAddress, uint SymbolSize, IntPtr UserContext);
public static bool EnumSyms(string name, ulong address, uint size, IntPtr context)
{
Console.Out.WriteLine(name);
return true;
}
static void Main(string[] args)
{
IntPtr hCurrentProcess = Process.GetCurrentProcess().Handle;
ulong baseOfDll;
bool status;
// Initialize sym.
// Please read the remarks on MSDN for the hProcess
// parameter.
status = SymInitialize(hCurrentProcess, null, false);
if (status == false)
{
Console.Out.WriteLine("Failed to initialize sym.");
return;
}
// Load dll.
baseOfDll = SymLoadModuleEx(hCurrentProcess,
IntPtr.Zero,
"c:\\windows\\system32\\user32.dll",
null,
0,
0,
IntPtr.Zero,
0);
if (baseOfDll == 0)
{
Console.Out.WriteLine("Failed to load module.");
SymCleanup(hCurrentProcess);
return;
}
// Enumerate symbols. For every symbol the
// callback method EnumSyms is called.
if (SymEnumerateSymbols64(hCurrentProcess,
BaseOfDll, EnumSyms, IntPtr.Zero) == false)
{
Console.Out.WriteLine("Failed to enum symbols.");
}
// Cleanup.
SymCleanup(hCurrentProcess);
}
In order to keep the example simple I did not use the
SymEnumSymbols function. I've also did the example
without using such classes as the SafeHandle class of
the .Net framework. If you need a example for the
SymEnumSymbols function, just let me know.
I'm curious if it is possible to write a program that monitors my text selection. One possible use would be to write an editor/IDE agnostic code formatter:
Application/Service, P, is launched and somehow hooks into windows such that it gets notified when text is selected in any window.
Some other application, A, is launched.
User selects text in A.
P is notified with the text that is selected.
--> I'd be happy to get this far...
This is not possible without specific knowledge of each control/application that will be in use as they can all handle/treat it differently.
I don't think you can register any sort of hook. I think you'll need to constantly poll the "focused" or selected window.
You can probably use the Windows Automation API to do this, which is as far as I am aware superceeded the older Accesibility API:
http://msdn.microsoft.com/en-us/library/ms747327.aspx
I have used this API to automate GUI tests. I am a bit rusty with it so I don't know for sure, but I am reasonably confident you could use it for what you are trying to do. Basically the API allows you to traverse the tree of automation objects with the root at the desktop. Each automation element tends to be a windows control of some kind and different controls implement different patterns. You can also get at elements beneath the mouse cursor and possibly you can get straight to the currently selected/focused element.
After that I notice the TextPattern class for example has a GetSelection() method which is documented as "Retrieves a collection of disjoint text ranges associated with the current text selection or selections.". I bet the automation object for textboxes implement the TextPattern.
http://msdn.microsoft.com/en-us/library/system.windows.automation.textpattern.aspx
This code help you to get focused control text in focused window, i hope that helps :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace TextFocusedns
{
public partial class TextFocusedFrm : Form
{
#region APIs
[DllImport("user32.dll")]
public static extern bool GetCursorPos(out Point pt);
[DllImport("user32.dll", EntryPoint = "WindowFromPoint", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr WindowFromPoint(Point pt);
[DllImport("user32.dll", EntryPoint = "SendMessageW")]
public static extern int SendMessageW([InAttribute] System.IntPtr hWnd, int Msg, int wParam, IntPtr lParam);
public const int WM_GETTEXT = 13;
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
internal static extern IntPtr GetFocus();
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int GetWindowThreadProcessId(int handle, out int processId);
[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
internal static extern int AttachThreadInput(int idAttach, int idAttachTo, bool fAttach);
[DllImport("kernel32.dll")]
internal static extern int GetCurrentThreadId();
[DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);
#endregion
private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer() { Interval = 100, Enabled = true };
public TextFocusedFrm()
{
InitializeComponent();
}
private void TextFocusedFrm_Load(object sender, EventArgs e)
{
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
try
{
MultiLineTextBox.Text = GetTextFromFocusedControl();
}
catch (Exception exp)
{
MultiLineTextBox.Text += exp.Message;
}
}
//Get the text of the focused control
private string GetTextFromFocusedControl()
{
try
{
int activeWinPtr = GetForegroundWindow().ToInt32();
int activeThreadId = 0, processId;
activeThreadId = GetWindowThreadProcessId(activeWinPtr, out processId);
int currentThreadId = GetCurrentThreadId();
if (activeThreadId != currentThreadId)
AttachThreadInput(activeThreadId, currentThreadId, true);
IntPtr activeCtrlId = GetFocus();
return GetText(activeCtrlId);
}
catch (Exception exp)
{
return exp.Message;
}
}
//Get the text of the control at the mouse position
private string GetTextFromControlAtMousePosition()
{
try
{
Point p;
if (GetCursorPos(out p))
{
IntPtr ptr = WindowFromPoint(p);
if (ptr != IntPtr.Zero)
{
return GetText(ptr);
}
}
return "";
}
catch (Exception exp)
{
return exp.Message;
}
}
//Get the text of a control with its handle
private string GetText(IntPtr handle)
{
int maxLength = 512;
IntPtr buffer = Marshal.AllocHGlobal((maxLength + 1) * 2);
SendMessageW(handle, WM_GETTEXT, maxLength, buffer);
string w = Marshal.PtrToStringUni(buffer);
Marshal.FreeHGlobal(buffer);
return w;
}
}
}