c# PostMessage not sending and no error - c#

First off,
I'm trying to send keyboard input to a background application(A window that does'nt have focus or might not even appear visible to the user).
I've verified that the winHandle and constants are correct.
Problem is the background application doesn't seem to get the message, UNLESS,
I set a breakpoint on the PostMessage() line, and press F10(step over) or F5(Continue) when it gets there,
then the keystroke magically gets sent.
What gives?
Relevant code:
[DllImport("User32.Dll", EntryPoint = "PostMessageA", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
PostMessage(winHandle, (uint)WM_KEYDOWN, 66, 0);
Using Win7 64 and MS Visual studio 2008 pro, Console application. And the above code is on a Thread if that helps.

Using Win7 64
That's somewhat relevant, the declaration is wrong. Works in 32-bit mode, but troublesome in 64-bit mode. The last two arguments are pointers, not ints. 8 bytes, not 4. Fix:
[DllImport("User32.Dll", EntryPoint = "PostMessageA", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
PostMessage(winHandle, (uint)WM_KEYDOWN, (IntPtr)66, IntPtr.Zero);
However, this may not actually solve your problem. In x64 mode, the first 4 arguments of a non-instance method are passed in registers, not the stack. It just so happens that this method has 4 arguments, you won't get the PInvokeStackImbalance MDA warning. And the upper 32-bits of the 64-bit register values are often zero by accident so it doesn't matter whether the P/Invoke marshaller generates a 32-bit or a 64-bit argument value.
Beware that this approach is quite troublesome in practice. You cannot control the state of the keyboard in the target process. You are sending the keystroke for B. That may turn into B, b, Alt+B or Ctrl+B, depending on the state of the modifier keys. Only SendInput() can work reliably. Well, short from the window focus problem.

Related

AccessibleObjectFromEvent call inside SetWinEventHook callback causes deadlocks

Both the callback and the AccessibleObjectFromEvent call appear to be working as intended, and I'm not using any locking mechanisms, but if AccessibleObjectFromEvent is present in the callback the winforms form will occasionally lock up.
I noticed when it freezes it has this odd property where right-clicking on its taskbar icon unfreezes it.
Pausing with the debugger just takes you to Application.Run(new Form1()), and nothing appears blocked on the .Net side - the debugger's window updates can even trigger some Active Accessibility events and then let you step through those events in the callback - working - all while the form remains frozen!
I note that AccessibleObjectFromEvent works by sending a WM_GETOBJECT message, but the .Net side is never stuck at the AccessibleObjectFromEvent call, and calling AccessibleObjectFromEvent from inside a SetWinEventHook callback is AFAIK a normal way to do Active Accessibility.
I've not noticed any correlation with Active Accessibility events when it freezes, but I don't really have enough information to rule that out. I also tried it compiled x86 (instead of Any), and that made no difference.
I boiled it down to its most minimal form:
using Accessibility;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WindowsFormsApp1 {
static class Program {
// PInvoke declarations, see http://www.pinvoke.net/default.aspx/user32.setwineventhook
[DllImport("user32.dll")]
static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, WinEventFlag dwFlags);
public delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("oleacc.dll")]
public static extern uint AccessibleObjectFromEvent(IntPtr hwnd, uint dwObjectID, uint dwChildID, out IAccessible ppacc, [MarshalAs(UnmanagedType.Struct)] out object pvarChild);
[Flags]
public enum WinEventFlag : uint {
/// <summary>Events are ASYNC</summary>
Outofcontext = 0x0000,
/// <summary>Don't call back for events on installer's thread</summary>
Skipownthread = 0x0001,
/// <summary>Don't call back for events on installer's process</summary>
Skipownprocess = 0x0002,
/// <summary>Events are SYNC, this causes your dll to be injected into every process</summary>
Incontext = 0x0004
}
static IntPtr hookHandle = IntPtr.Zero;
static GCHandle garbageCollectorHandle;
static void AccessibilityEventHandler(IntPtr hWinEventHook, uint eventType, IntPtr hWnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) {
try {
object objChild = null;
IAccessible accWindow = null;
AccessibleObjectFromEvent(hWnd, (uint)idObject, (uint)idChild, out accWindow, out objChild);
Debug.WriteLine("Hook was invoked");
} catch (Exception ex) {
Debug.WriteLine("Exception " + ex);
}
}
[STAThread]
static void Main() {
WinEventDelegate callback = new WinEventDelegate(AccessibilityEventHandler);
// Use the member garbageCollectorHandle to keep the delegate object in memory. Might not be needed, and can't properly pin it because it's not a primitive type.
garbageCollectorHandle = GCHandle.Alloc(callback);
SetWinEventHook(
0x7546, // eventMin (0x7546 = PropertyChanged_IsOffscreen)
0x7546, // eventMax
IntPtr.Zero,
callback,
0,
0,
WinEventFlag.Outofcontext
);
// Two hooks are not necessary to cause a freeze, but with two it can happen much faster - sometimes within minutes
SetWinEventHook(
0x0001, // eventMin (0x0001 = System_Sound)
0x0001, // eventMax
IntPtr.Zero,
callback,
0,
0,
WinEventFlag.Outofcontext
);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
With such a minimal app it's harder to notice the message pump freeze, but you won't be able to drag the window or bring it to the foreground once it's locked. The bug is intermittent, often it happens within 5 minutes, sometimes it takes so long I give up, if you leave it overnight and the form is still responsive in the morning then it might depend on machine/OS (tried on Win 10.0.17174 and 10.0.17763, .net 4.5.2 and 4.6.1).
I'm 99% sure the call to AccessibleObjectFromEvent is required for the app to freeze, but with intermittent freezes there's no way to absolutely know for sure.
Reentrancy
Following Jimi's suggestions in the comments, I ran the minimal app with the flags
WinEventFlag.Outofcontext | WinEventFlag.Skipownthread | WinEventFlag.Skipownprocess
It took a while to freeze, but has still frozen. The Debug.WriteLine() calls indicate it's still responding to Active Accessibility events normally - i.e. no recursive busy-loop is happening through that callback (at least not now that I'm looking), but the form is frozen. It's using 0% CPU in the task manager.
The freeze is slightly different now, in that the task manager doesn't list it as "not responding" and I can bring it to the foreground by left-clicking the taskbar icon - normally the taskbar can't even bring it to the foreground. However the form still can't be moved or resized, and you can't bring the form to the foreground by clicking on it.
I'd also added some Debug.WriteLine in front of the AccessibleObjectFromEvent call, and tracked reentrancy depth, I can see that it is occasionally reentrant, but usually to a depth of only one before unwinding, and no deeper than 13 before fully unwinding. This appears to be caused by there being many events already in the message queue, rather than the hook handler recursively causing events it must then handle. The UI is currently frozen and the hook handler is 0 deep (i.e. not currently reentrant).

Are there any dangers of using Windows API calls in C#

I want to watermark a textbox, and found several different ways of doing it, but one that I liked uses SendMessage and an external DLL. However, I think I heard somewhere that doing it this way can cause BSOD since it isn't managed. Is this true, or is it just hear-say.
http://vidmar.net/weblog/archive/2008/11/05/watermarked-textbox-in-windows-forms-on-.net.aspx
private const uint ECM_FIRST = 0x1500;
private const uint EM_SETCUEBANNER = ECM_FIRST + 1;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, uint wParam, [MarshalAs(UnmanagedType.LPWStr)] string lParam);
The short answer is no. It won't cause a BSOD, although it could crash your program.
WinForms is basically built on top of Windows API calls, so when done right, custom API calls should work good as well.
One other thing to keep in mind is that if you do call the Windows API, it may create portability issues, such as when porting to Mono, as those DLLs will most likely not be available.

c# What are these volume changing codes/messages

I found this script to change the System sound volume and it works. But what are these constant volume codes called and where can I find a full list of these codes that do more things.
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
//Volume codes, or messages, or whatever they are called
const int VOLUME_MUTE = 0x80000;
const int VOLUME_DOWN = 0x90000;
const int VOLUME_UP = 0xA0000;
SendMessage(this.Handle, 0x319, IntPtr.Zero, (IntPtr)VOLUME_UP);
These are AppCommand messages.
0x319 is the Win32 Windows MSG for WM_APPCOMMAND, and the messages are more accurately APPCOMMAND_VOLUME_UP, etc...
AppCommand messages are messages sent to windows, which are handled at a global level and perform certain application functions. These tend to be linked to Keyboard hotkeys and mouse button functions.
Your app gets first crack at processing any such messages, and if you do not handle them then your apps parent does. If that doesn't handle them, then eventually it gets sent to a global message hook to process them. The key point here is that other windows can trap these messages, so it's not a guarantee that sending these messages will accomplish the task. Just like you might have seen where pressing the volume up or down on your keyboard might not always work when certain windows have focus.
You can find the details for all the messages in the Win32 API reference:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms646275(v=vs.85).aspx

SendMessage() only working when window is open, not when minimized

I've been using SendMessage to send mouse clicks to a couple of windows. One being a game(everything works perfectly), but the other window, being a 3rd party tool for the game is having trouble with SendMessage. If the window is 'not minimized' everything works fine, don't matter if window is completely covered up by another. But if that same window is minimized then nothing happens, I checked with spy++ and the messages are indeed getting received but not being processed (correct term?). I've tried to solve this last couple days, doing both searches on here and Google alike, many of topics but nothing helped?
//MyImports
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
And this is how I have it wrapped
public static void LClick(string windowclass, int x, int y)
{
IntPtr WHandle = FindWindow(windowclass, null);
SendMessage(WHandle, (int)WMessages.WM_LBUTTONDOWN, (IntPtr)1, (IntPtr)MakeLParam(x, y));
SendMessage(WHandle, (int)WMessages.WM_LBUTTONUP, (IntPtr)0, (IntPtr)MakeLParam(x, y));
}
I have tried focus, activate. One thing that might be useful info is that the third party program is being loaded as module("Qt5QWindowIcon") of the game.
I tried PostMessage as well, and it does the same thing as SendMessage() same problem when minimized.
This game does allow for macroing and unattended macroing, Hints the third part tool designed to execute the macros (published by the creators) I'm just trying to simulate a mouse click on the program to start the macro.
I would just use SendInput, but the entire purpose of my program is to run in background.
I 've faced same problem .Please change assembly name and project name (Changed name not started with name on that you are throwing/posting windows message)then rebuild it and check it. Now you will able to debug.

Determining the bitness of an IntPtr instance using EnumChildWindows

I posted a similar question here but decided to re-post focusing on part of the question.
I am enumerating windows using EnumWindows and EnumChildWindows on a 64 bit Windows 7 from a 32 bit WinForms application. Here is the declaration:
public delegate int EnumWindowsCallback (System.IntPtr hWnd, System.IntPtr lParam);
[DllImport("user32.Dll")]
public static extern bool EnumWindows (EnumWindowsCallback lpEnumCallbackFunc, IntPtr lParam);
[DllImport("user32")]
public static extern bool EnumChildWindows (IntPtr hWnd, EnumWindowsCallback lpEnumCallbackFunc, IntPtr lParam);
I send [Process.GetProcesses()[i].MainWindowHandle] as a parameter to [EnumWindows] to enumerate all child windows of all processes.
When [EnumChildWindows] is called, the [hWnd] parameter could be a handle to a window running in a 32 or 64 bit process. Since my app is 32 bit, how can I tell whether to call [hWnd.ToInt32()] or [hWnd.ToInt64()]. I need to call one of the two functions to compare one IntPtr to another.
Context: Windows 7 (64 bit), VS 2010, WinForms (32 bit).
You should not need to do anything special, a hwnd is not a pointer its a HANDLE and for this type 64 bit Windows guarantees that only the lower 32 bits are significant so they can be freely shared.

Categories