I'm trying to make a Unity3D Application that can control the volume of another application. So far I've gotten it to work to change the volume of ALL applications, but I'm having trouble to get it to change just one, e.g. Spotify. This is on Windows 8, but I'd like it to work for Windows 7 as well.
private const int APPCOMMAND_VOLUME_UP = 0xA0000;
private const int APPCOMMAND_VOLUME_DOWN = 0x90000;
private const int WM_APPCOMMAND = 0x319;
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr FindWindow(string strClassName, string strWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
[DllImport("user32.dll")]
public static extern IntPtr GetActiveWindow();
public void DecreaseVolume()
{
IntPtr hWnd = FindWindow("SpotifyMainWindow", "Spotify");
if (hWnd == IntPtr.Zero)
return;
uint pID;
GetWindowThreadProcessId(hWnd, out pID);
Debug.Log(pID);
SendMessage(hWnd, WM_APPCOMMAND, hWnd, (IntPtr)APPCOMMAND_VOLUME_DOWN);
}
public void IncreaseVolume()
{
// same as above, but with APPCOMMAND_VOLUME_UP
}
I'm pretty sure I'm getting the correct handle (hWnd) from FindWindow() because the pID printed out matches the PID of Spotify in my Task Manager, however all this does is change the volume of everything instead of just Spotify. This is the same result as if I didn't specify a specific handle e.g.
SendMessage(IntPtr.Zero, WM_APPCOMMAND, IntPtr.Zero, (IntPtr)APPCOMMAND_VOLUME_DOWN);
or if I use GetActiveWindow().
I've never messed around with these windows api stuff until today, so any help would be very appreciated!
Related
I'm trying to Postmessage send key inputs to an application. The issue is that the message is being sent only when the application becomes active or gains focus.
Here is my goal:
I need the application to receive inputs either while it is not focused, or via some pseudo-focus called via postmessage before the input is sent (I have tried: NativeMethods.PostMessage(mainHwnd, 0x0007, 0, 0); "0x0007" is WM_SETFOCUS but this doesn't do anything). Any assistance would be very helpful, I've been at this for more hours than I care to count.🙏
Here is all of the relevant code I'm using:
using System.Runtime.InteropServices;
using System;
using System.Windows.Forms;
using System.Threading;
internal static class NativeMethods
{
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32.dll", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, Int32 wParam, Int32 lParam);
[DllImport("User32.dll")]
public static extern int SendMessage(IntPtr hWnd, UInt32 uMsg, Int32 wParam, Int32 lParam);
}
class Test
{
const int WM_KEYDOWN = 0x0100;
const int WM_KEYUP = 0x0101;
//const int WM_SETFOCUS = 0x0007;
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);
public static void SendKey()
{
IntPtr mainHwnd = NativeMethods.FindWindow(null, "Test Application");
NativeMethods.PostMessage(mainHwnd, WM_KEYDOWN, (int)Keys.A, 0);
Thread.Sleep(50);
NativeMethods.PostMessage(mainHwnd, WM_KEYUP, (int)Keys.A, 0);
}
}
class TryTheThing{
public void Send() {
Test.SendKey();
}
}
Windows does not allow you to send keystrokes to non-focused applications. Your only option is to force the window to be focused first. This can be achieved by P/Invoking SetForegroundWindow():
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
NativeMethods.SetForegroundWindow(mainHwnd);
The goal
I developed a keyboard in Unity3D (C#) and want it to pop up when the users click on "EDIT" type control such as a address bar or an input field. Therefore, I need to detect when an "EDIT" control is clicked.
What I've tried
Currently I use SetWinEventHook and listen to event EVENT_OBJECT_FOCUS to get the handle of the object which gets the focus. After that, I use GetClassName to see if the focused object is an "EDIT" control which displays a flashing caret when clicked. However, take Google Chrome as an example, I always get Chrome_WidgetWin_1 whether I click the address bar or the plain text of the page. After doing some googling I found this blog post What makes RealGetWindowClass so much more real than GetClassName? saying that RealGetWindowClass can get the base class which I think it will be something like "EDIT" or "COMBOBOX" listed here. Things were not going so well. I tried using RealGetWindowClass and still get the same result Chrome_WidgetWin_1.
The problem
Why do GetÂClassÂName and RealÂGetÂWindowÂClass return the same value? How should I make RealÂGetÂWindowÂClass return the base class?
The code
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWinEventHook(int eventMin, int eventMax, IntPtr hmodWinEventProc, WinEventProc lpfnWinEventProc, int idProcess, int idThread, int dwflags);
[DllImport("user32.dll", SetLastError = true)]
private static extern int UnhookWinEvent(IntPtr hWinEventHook);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint RealGetWindowClass(IntPtr hwnd, [Out] StringBuilder pszType, uint cchType);
private delegate void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hWnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
private const int WINEVENT_SKIPOWNPROCESS = 2;
private IntPtr windowEventHook;
private const int EVENT_OBJECT_FOCUS = 0x8005;
private void Start()
{
if (windowEventHook == IntPtr.Zero)
{
windowEventHook = SetWinEventHook(
EVENT_OBJECT_FOCUS,
EVENT_OBJECT_FOCUS,
IntPtr.Zero,
WindowEventCallback,
0,
0,
WINEVENT_SKIPOWNPROCESS);
if (windowEventHook == IntPtr.Zero)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
}
private void OnDestroy()
{
UnhookWinEvent(windowEventHook);
}
private void WindowEventCallback(IntPtr hWinEventHook, uint eventType, IntPtr hWnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
UnityEngine.Debug.Log($"[EventType]: {(EventEnum)eventType} [Class Name]: {GetClassName(hWnd)} [Real Class]: {RealGetWindowClassM(hWnd)}");
// Will print out the same log whether I click an address bar or plain text.
// [EventType]: EVENT_OBJECT_FOCUS [Class Name]: Chrome_WidgetWin_1 [Real Class]: Chrome_WidgetWin_1
}
private string GetClassName(IntPtr hWnd)
{
StringBuilder className = new StringBuilder(256);
GetClassName(hWnd, className, className.Capacity);
return className.ToString();
}
private string RealGetWindowClassM(IntPtr hWnd)
{
StringBuilder className = new StringBuilder(256);
RealGetWindowClass(hWnd, className, (UInt32)className.Capacity);
return className.ToString();
}
I borrowed the following code I found online (the comments aren't even mine). When I click a button on my form, it waits and detects my next mouse click. Whatever I click on, it gets that information in the winHandle object inside the HookCallback method:
private static LowLevelMouseProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
static IntPtr hHook = IntPtr.Zero;
private delegate IntPtr LowLevelMouseProc(int nCode, IntPtr wParam, IntPtr lParam);
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && MouseMessages.WM_LBUTTONDOWN == (MouseMessages)wParam)
{
// The application runs to here when you click on the window whose handle you want to get
POINT cusorPoint;
bool ret = GetCursorPos(out cusorPoint);
// cusorPoint contains your cusor’s position when you click on the window
// Then use cusorPoint to get the handle of the window you clicked
IntPtr winHandle = WindowFromPoint(cusorPoint);
// winHandle is the Hanle you need
// Now you have get the handle, do what you want here
// ………………………………………………….
Debug.WriteLine("Handle: " + winHandle.ToString());
// Because the hook may occupy much memory, so remember to uninstall the hook after
// you finish your work, and that is what the following code does.
UnhookWindowsHookEx(hHook);
hHook = IntPtr.Zero;
// Here I do not use the GetActiveWindow(). Let's call the window you clicked "DesWindow" and explain my reason.
// I think the hook intercepts the mouse click message before the mouse click message delivered to the DesWindow's
// message queue. The application came to this function before the DesWindow became the active window, so the handle
// abtained from calling GetActiveWindow() here is not the DesWindow's handle, I did some tests, and What I got is always
// the Form's handle, but not the DesWindow's handle. You can do some test too.
//IntPtr handle = GetActiveWindow();
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
private const int WH_MOUSE_LL = 14;
private enum MouseMessages
{
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_MOUSEMOVE = 0x0200,
WM_MOUSEWHEEL = 0x020A,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205
}
[StructLayout(LayoutKind.Sequential)]
private struct POINT
{
public int x;
public int y;
}
[StructLayout(LayoutKind.Sequential)]
private struct MSLLHOOKSTRUCT
{
public POINT pt;
public uint mouseData;
public uint flags;
public uint time;
public IntPtr dwExtraInfo;
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook,
LowLevelMouseProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("user32.dll")]
static extern IntPtr WindowFromPoint(POINT Point);
private void GetProcess_Click(object sender, EventArgs e)
{
if (IntPtr.Zero == hHook){
using (Process curProcess = Process.GetCurrentProcess())
using (ProcessModule curModule = curProcess.MainModule)
{
hHook = SetWindowsHookEx(WH_MOUSE_LL, _proc,
GetModuleHandle(curModule.ModuleName), 0);
}
}
}
The problem is I need to use the information from that object elsewhere in my code. But, since it doesn't return that information, I'm not sure how I could get access to it.
I don't think I can return it because it goes instead over to the CallNextHookEx method; I've tried putting it in its own class, but inside the HookCallBack method I don't have access to this. or datasets or anything else.
So what can I do to get that information from outside the static method HookCallback?
This is with reference to this question:
How to read output and give input to a program from c program?
I found the answer to the above question very useful. In the same way, can I do it for windows applications? Like can I give input into a Windows form (like .net, C# applications) application's text box programmatically? Can I do the action of button click from a program?
If so, can I do it from a C program (with Tiny C compiler or any other on windows platform)? If not, how and in which language can I do it? Please don't take it as a silly question. Any example codes will be very much appreciated.
Edit: Can I do the same with web applications and web pages?
If your application mainly just needs to manipulate other windows, by sending keystrokes etc. i would use AutoIt. It's mainly function is exactly this job and it does it very well.
So maybe you should give it a try, cause not every problem is a nail and can be solved with a hammer (C#) ;-))
You can enumerate all the windows of the system.
You can send windows messages to any window.
E.g. to set the text of a textbox you have to send a WM_SETTEXT message.
FYI: Winspector is a very interesting tool which makes heavy use of this as well (also to debug or otherwise first inspect the windows you're trying to programmatically access).
You might also be interested in this:
AutoIt v3 is a freeware BASIC-like scripting language designed for automating the Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks in a way not possible or reliable with other languages (e.g. VBScript and SendKeys). AutoIt is also very small, self-contained and will run on all versions of Windows out-of-the-box with no annoying "runtimes" required!
As fretje pointed out, you can certainly do it.
It's much more challenging for windows apps. Because individual controls also count as windows, the total window count will be much higher than you might expect; and finding the specific control you want to send input to can take a lot of work.
But you can programmatically move, resize, check, fill, maximize or otherwise affect an app's windows, once you know which one is your target.
I wrote code to do the discovery process a few years ago. It found all the windows of a target app, then using their size & location data, produced a translucent overlay of each child window, along with the handle number. So I could visually tell which control went with which handle.
EDIT: Added some code. This is some basic C# interop code that will let you make easy calls into user32.dll, which holds the fns to which fretje referred. This just gives you the basic calls for discovery and manipulation; you'll still have to do the hard work of enumerating and examining what you find. If you can find a 3rd-party package that does the job for you, save yourself the trouble; I only did it as a learning experience, and it was pretty laborious.
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Text;
namespace WinAPI
{
[Flags] public enum WindowStyleFlags : uint
{
WS_OVERLAPPED = 0x00000000,
WS_POPUP = 0x80000000,
// more...
}
[Flags] public enum ExtendedWindowStyleFlags: int
{
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_NOPARENTNOTIFY = 0x00000004,
// more...
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct POINT
{
public int Left;
public int Top;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct FLASHWINFO
{
public int cbSize;
public IntPtr hwnd;
public int dwFlags;
public int uCount;
public int dwTimeout;
}
public delegate int EnumWindowsCallback( IntPtr hwnd, int lParam );
public class User32Dll
{
// Constants & fields
public const int FLASHW_STOP = 0;
public const int FLASHW_CAPTION = 0x00000001;
// lots, lots more, web search for them...
// Self-added, don't know if correct
[DllImport("user32")]
public extern static bool CloseWindow( IntPtr hWnd );
[DllImport("user32")]
public extern static IntPtr GetDesktopWindow();
[DllImport("user32")]
public extern static IntPtr GetForegroundWindow();
[DllImport("user32")]
public extern static int GetDlgItem( IntPtr hWnd, int wMsg );
[DllImport("user32")]
public extern static int GetListBoxInfo( IntPtr hWnd );
[DllImport("user32")]
public extern static bool MoveWindow( IntPtr hWnd, int X, int Y, int Width, int Height, bool Repaint );
[DllImport( "user32" )]
public static extern int SendMessage( IntPtr hWnd, int uMsg, IntPtr wParam, StringBuilder lpString );
[DllImport("user32")]
public static extern bool SetWindowPos( IntPtr hWnd, IntPtr afterWnd, int X, int Y, int cX, int cY, uint uFlags );
[DllImport("user32")]
public extern static int BringWindowToTop (IntPtr hWnd);
[DllImport("user32")]
public extern static int EnumWindows( EnumWindowsCallback lpEnumFunc, int lParam );
[DllImport("user32")]
public extern static int EnumChildWindows( IntPtr hWndParent, EnumWindowsCallback lpEnumFunc, int lParam );
[DllImport( "user32.dll" )]
public static extern int EnumThreadWindows( IntPtr hWndParent, EnumWindowsCallback callback, int lParam );
[DllImport( "user32.dll" )]
public static extern int FindWindow( string lpClassName, string WindowName );
[DllImport( "user32.dll" )]
public static extern int FindWindowEx( IntPtr hWnd, IntPtr hWnd2, string lpsz, string lpsz2 );
[DllImport("user32")]
public extern static int FlashWindow ( IntPtr hWnd, ref FLASHWINFO pwfi);
[DllImport("user32")]
public extern static IntPtr GetAncestor( IntPtr hWnd, uint gaFlags );
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int GetClassName ( IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static uint GetWindowLong( IntPtr hwnd, int nIndex);
[DllImport("user32")]
public extern static int GetClientRect( IntPtr hWnd, ref RECT lpRect);
[DllImport("user32")]
public extern static int GetWindowRect( IntPtr hWnd, ref RECT lpRect);
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int GetWindowText( IntPtr hWnd, StringBuilder lpString, int cch );
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int GetWindowTextLength( IntPtr hWnd );
[DllImport("user32")]
public extern static int IsIconic(IntPtr hWnd);
[DllImport("user32")]
public extern static int IsWindowVisible( IntPtr hWnd );
[DllImport("user32")]
public extern static int IsZoomed(IntPtr hwnd);
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int PostMessage( IntPtr hWnd, int wMsg, int wParam, int lParam);
[DllImport( "user32.dll" )]
public static extern int RealGetWindowClass( IntPtr hWnd, StringBuilder pszType, uint bufferSize );
[DllImport("user32")]
public extern static int ScreenToClient( IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32", CharSet = CharSet.Auto)]
public extern static int SendMessage( IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public extern static int SetForegroundWindow (IntPtr hWnd);
[DllImport( "user32.dll" )]
public static extern int SetWindowText( IntPtr hWnd, string lpsz );
}
}
Check out the following SO question. There are numerous vendor and open-source tools to do this for you, so you don't have to code at to the Win32 API.
automated-testing-of-windows-forms
Hopefully this is a simple one, but can anyone provide some simple c# code that will launch the currently configured screensaver?
Here is a good site showing how to work with all aspects of the screensaver. See the comments at the end for the code to start the screensaver.
http://www.codeproject.com/KB/cs/ScreenSaverControl.aspx
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
private static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
//...
private const int SC_SCREENSAVE = 0xF140;
private const int WM_SYSCOMMAND = 0x0112;
//...
public static void SetScreenSaverRunning()
{
SendMessage
(GetDesktopWindow(), WM_SYSCOMMAND, SC_SCREENSAVE, 0);
}