User32.dll SetFocus() not working in standalone build

Hi,

I managed to make a little borderless launcher with a custom title bar and a drag&drop function using user32.dll.

I’m dragging the window using :

  // Window drag&drop messages

 [DllImport("User32.dll")] public static extern bool ReleaseCapture(); // Used for window drag&drop
    delegate void SendMessageDelegate(IntPtr hWnd, uint uMsg, UIntPtr dwData, IntPtr lResult);
 [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] static extern bool SendMessageCallback(IntPtr hWnd, int Msg, int wParam, int lParam, SendMessageDelegate lpCallBack, int dwData);
 [DllImport("user32.dll", EntryPoint = "SetForegroundWindow")] static extern bool SetForegroundWindow(IntPtr hWnd);
 [DllImport("user32.dll", SetLastError = true)] static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "FindWindow")] public static extern System.IntPtr FindWindow(string className, string windowName);

// Drag Start
window = GetActiveWindow();
ReleaseCapture();
SendMessageCallback(window, WM_SYSCOMMAND, MOUSE_MOVE, 0, WindowDropCallback, 0);

It works well, except that I have to click twice after the drop, because of the loss of focus.

So i added this in the WindowDropCallback :

SetForegroundWindow(window);
 SetFocus(window);

And it works exactly how I want, but ONLY in the editor !
When I build, the focus is still lost on drop and I still have to click twice.

Do you have an idea ?

Thanks for reading :smile:

2 Likes

Found a workaround :
I simulate a left click on the window using SendInput.
Works very well

1 Like

Thank you for the workaround. I saw your post on StackOverFlow and was asking what you did in the callback. Very sad to read that a workaround is the only solution for the moment. But thank you because I was facing the exact same issue.

Thank you very much for your help _FLX!!
I followed your instructions and solved the problem of twice clicking issue!!
For those who are unclear about how to simulate an input, here is my trick:

void DragEvent(){
SendMessageCallback(window, WM_SYSCOMMAND, MOUSE_MOVE, 0, DropCallBack, 0);
}

[DllImport(“user32.dll”)]
public static extern bool SetForegroundWindow(IntPtr hwnd);
[DllImport(“user32.dll”, SetLastError = true)]
public static extern IntPtr SetFocus(IntPtr hWnd);
[DllImport(“user32.dll”)]
public static extern Boolean SendMessage(IntPtr hwnd, Int32 wMsg, Int32 wParam, Int32 lParam);
public const int WM_LBUTTONDOWN = 0x201;
public const int WM_LBUTTONUP = 0x0202;
private static void DropCallBack(IntPtr hwnd, uint uMsg, int dwData, int lResult)
{
SetForegroundWindow(hwnd);
SetFocus(hwnd);
SendMessage(hwnd, WM_LBUTTONDOWN, 0, 0);
SendMessage(hwnd, WM_LBUTTONUP, 0, 0);
}

2 Likes