Click here to Skip to main content
15,910,981 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to relocate the position of an external application, i.e. On-Screen Keyboard. It only works correctly if I place a breakpoint. If I run it either from VS without the breakpoint or by running the executable, it doesn't function. Why?

What I have tried:

C#
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll", SetLastError = true)]
static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

const uint SWP_NOSIZE = 0x0001;

public void SetWindowPosition(string txtAppTitle, string txtWidth, string txtHeight, string txtX, string txtY)
{
    IntPtr hWnd = FindWindow(null, txtAppTitle);

    // If found, position it.
    if (hWnd != IntPtr.Zero)
    {
        // Move the window to (txtX, txtY) without changing its size.
        int x = int.Parse(txtX);
        int y = int.Parse(txtY);
        SetWindowPos(hWnd, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE);
    }
}

private void btnOnScreenKeyboard_Click(object sender, EventArgs e)
{
    SetWindowPosition("On-Screen Keyboard", "0", "0", "155", "545");
}
Posted
Updated 22-Jan-18 5:51am
v2
Comments
mocodeproject 22-Jan-18 1:42am    
I've tried System.Threading.Thread.Sleep(30); at the beginning of SetWindowPosition method and it seems to fix the problem but is there a better way to fix this rather then using Thread.Sleep
Dotnet_Dotnet 22-Jan-18 1:43am    
sir run each application with separate thread
mocodeproject 22-Jan-18 2:57am    
Could you please be more specific about each "application"
Richard MacCutchan 22-Jan-18 4:18am    
Why are you sending strings instead of integer values for the numbers? You can find out why it is not working by adding some debug/logging code to the application.
mocodeproject 22-Jan-18 7:23am    
I did add some debug/logging to the code
bool success = SetWindowPos(hWnd, IntPtr.Zero, x, y, width, height, 0);
int err = Marshal.GetLastWin32Error();

and I get success = false and err=1400 which means ERROR_INVALID_WINDOW_HANDLE = 1400 after reading a bit the GUI is needs more time to load before my method so I need some kind of delay at the beginning of me method any ideas what the best way is. I've tried System.Threading.Thread.Sleep(50); and it fixed the problem but is there a better way then Thread.Sleep.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900