embededd application host in wpf - c#

I want to set an application to be the child of my WPF application.
My application has 3 window and I would like all windows to be childs of the WPF.
I use this code enter code here
main:
[DllImport("user32.dll")]
private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);
loaded:
var helper = new WindowInteropHelper(this);
SetParent(proc.MainWindowHandle, helper.Handle);
It works just for one of the windows.
What should I do to have all windows in child of WPF?

Each control in WinForm has a unique handle, but WPF elements have not, To solve your problem you can put one or more WindowsFormsHost in the window and use handle of them because each WindowsFormsHost also has a unique handle the same as WinForm controls.
Then use SetParent like this :
SetParent(proc.MainWindowHandle, YourWindowsFormsHost.Handle );

Related

GetWindowText vs Process.MainWindowTitle

I'm trying to obtain process information for the current active application (or window), using .Net/C#.
Currently I'm using
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
To get the current active window.
I understand there's no native way to do this other than use this API function.
From that, I use:
[DllImport("user32")]
private static extern UInt32 GetWindowThreadProcessId(IntPtr hWnd, out Int32 lpdwProcessId);
To get the process name that belongs to that window and then I get further process information.
I also use
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
To get the current Window Text or caption.
Now, using the Process class, I can use
MainWindowTitle
to get the main Window title as well.
The thing is, MainWindowTitle and GetWindowText does not return the same information.
For example, let's say the main application opened is "Toad" with a connection and an editor open.
Then with GetWindowText I get:
"Toad for Oracle - myConnection - Somequery.sql".
and Process.MainWindowTitle returns
"myConnection".
So, the question is how do I get the exact same text as I get using GetWindowText, but using merely .Net classes?
Edit:
I found out that actually the reason is simply because both functions are not querying the same window handle.
The window handle returned in the GetForegroundWindow, is the number 198982.
And the MainWindowHandle property, which I suppose is the one used in the MainWindowTitle propery is the number 198954.
Using Spy++ I could find and confirm those windows handle captions are the one returned by their corresponding function.
So the "problem", if any, is that the Process class does not correctly identify the most foreground window as the Main Window.
GetForegroundWindow gives you the active window the user is working in and that might be a owned window or a modal dialog, not necessarily the applications main/root window.
MainWindow is a .NET concept, native win32 does not have such a thing and there can be 0, 1 or multiple "main windows" in an application.
Some Delphi/C++Builder applications have a HWND for the taskbar button and each form is a owned window belonging to this "invisible" window. Other UI frameworks may pull similar stunts that might confuse "main window" detection.
You can use UI Automation to inspect other applications if you don't want to use p-invoke. Start with the foreground window and walk up the tree of owned and child windows...

user32.dll. How do i find textbox?

So far I make a window - active, to send text using SendKeys, but I want to do it in background using SendMessage
IntPtr main = FindWindow(null, "Label Code (Scan)");
if (!main.Equals(IntPtr.Zero))
{
if (SetForegroundWindow(main))
{
SendKeys.SendWait(code);
SendKeys.SendWait("{ENTER}");
}
}
I have tried something like:
IntPtr main = FindWindow(null, "Label Code (Scan)");
SendMessage(main, 0x000C, 0, "Hello");
But it renames window's title to "Hello". Looks like, I need to find child window, but can't find out about lpszClass.
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
The controls in the window are not real Windows Controls. They are drawn and managed by the Window itselt. However, the window may support the Windows Automation framework to allow interacting with the controls.
Use the tool Inspect to check whether the window supports Windows Automation API.
If it does, use the classes in System.Windows.Automation with the information you see in the Inspect tool to set the text.

How to restore a window without giving it focus using WPF (or interop)

I need to restore ("un-minimize") a WPF window that has already been created but the window that's currently on top (not necessarily WPF) can't lose focus or activation. I have tried using all WIN32 functions I can find, to no avail. Getting really frustrated by now, would really appreciate any pointers and tips.
Obviously just changing to WindowState.Normal in WPF doesn't cut it as this makes the window receive focus and activation as-well. I have also tried all sorts of combinations with setting Hidden and IsEnabled while restoring.
I have tried WIN32 SetWindowPos with HWND_TOP, HWND_TOPMOST etc. but this function is not intended to restore windows and will only change position of already "displayed" windows.
Tried WIN32 ShowWindow and SetWindowPlacement but no luck there either. Tried a desperate attempt at adding a HwndHook to try and listen for WM_SETFOCUS and restoring focus to the original window but i only get zero for the last focused window handle..
Edit - Solution with window extension after tip from Joel Lucsy:
public static class RestoreWindowNoActivateExtension
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool ShowWindow(IntPtr hWnd, UInt32 nCmdShow);
private const int SW_SHOWNOACTIVATE = 4;
public static void RestoreNoActivate(this Window win)
{
WindowInteropHelper winHelper = new WindowInteropHelper(win);
ShowWindow(winHelper.Handle, SW_SHOWNOACTIVATE);
}
}
Call ShowWindow passing the SW_SHOWNOACTIVATE flag.

Attach form window to another window in C#

I want to attach a form to another window (of another process). I try to do this by using
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
setParentWindow(myWindowHwnd, newParentHwnd);
In doing so my form becomes attached, but is also invisible. Question "Attach window .." solves this issue for a WPF Window, basically by using
HwndSourceParameters parameters = new HwndSourceParameters();
...
HwndSource src = new HwndSource(parameters);
I have tried to transfer this to my form, but I am unable to do so (e.g. how to handle src.RootVisual = (Visual)window.Content; ? -> Complete source).
Another comment says, I need to modify the windows style:
For compatibility reasons, SetParent does not modify the WS_CHILD or WS_POPUP window styles of the window whose parent is being changed. Therefore, if hWndNewParent is NULL, you should also clear the WS_CHILD bit and set the WS_POPUP style after calling SetParent. Conversely, if hWndNewParent is not NULL and the window was previously a child of the desktop, you should clear the WS_POPUP style and set the WS_CHILD style before calling SetParent.
Here I miss the corresponding API for doing so, can I do it directly from C# or have I to use another DllImport again?
Good or evil - SetParent() win32 API between different processes advises against attaching windows in different processes at all, but at least I want to try.
Question:
What would I need to do to get the form window visible? If the approach with WS_Child is the correct one, how would I set it? Or is the WPF approach the way to go, but how would I apply it to an windows form?
-- Findings (later added) --
Modify the windows style of another application using winAPI shows how to modify the style from C# / PInvoke
Find all windows styles here, C# syntax at the bottom.
-- Findings due to discussion with Alan --
I did run my program on Win XP to crosscheck (see Alan's answer below and the comments). At least I do now see something. Since I have added the coordinates as of Alan's examples, my window now shines through in notepad when moving over the other window near the left upper corner. You can still see the text typed in notepad as overlay. Under Win 7 (32) I do see nothing at all.
Now I need to find out whether this can be written in a stable way, appearing on Win 7 as well.
Nevertheless, I still cannot click any buttons on my form, needs to be solved too.
Here is a working example. The hosting app is a simple WinForms application with a blank form (not included here), while the "guest app" has a main form (code behind included below) with some controls, including a test button to display a message after changing the guest form's parent.
The usual caveats linked to in the OP's question apply to this, too.
public partial class GuestForm: Form
{
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
public static int GWL_STYLE = -16;
public static int WS_CHILD = 0x40000000;
public GuestForm()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("done");
}
private void button2_Click(object sender, EventArgs e)
{
Process hostProcess = Process.GetProcessesByName("HostFormApp").FirstOrDefault();
if (hostProcess != null)
{
Hide();
FormBorderStyle = FormBorderStyle.None;
SetBounds(0, 0, 0, 0, BoundsSpecified.Location);
IntPtr hostHandle = hostProcess.MainWindowHandle;
IntPtr guestHandle = this.Handle;
SetWindowLong(guestHandle, GWL_STYLE, GetWindowLong(guestHandle, GWL_STYLE) | WS_CHILD);
SetParent(guestHandle, hostHandle);
Show();
}
}
}
#Horst Walter Hey man, I'm not sure if you've fixed the issue, but I just found a solution to this..
For me the issue was the transparency of the main form you want inside the other form.
Just disable transparency and it should work.

Programs as MDI Child windows

Is there a way to use a program as a MDI child window. I am thinking of having one main MDI parent window which can have multipe child windows, some of which will be programs(.exe files) in there own right.
Tim
There is actually a pretty easy way to do this.
First, you need to add a panel to your form. This panel will be used to "host" the application.
Next, you need to the "System.Runtime.InteropServices" and the "System.Diagnostics" namespace to your namespaces:
csharp
using System.Diagnostics;
using System.Runtime.InteropServices;
Now, we need setup our WinAPI functions:
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hwndChild, IntPtr hwndNewParent);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, Int32 wParam, Int32 lParam);
Now, inside a button click event, start the process, and set it's parent to the panel. In this example, I will be using notepad:
// Create a new process
Process proc;
// Start the process
proc = Process.Start("notepad.exe");
proc.WaitForInputIdle();
// Set the panel control as the application's parent
SetParent(proc.MainWindowHandle, this.panel1.Handle);
// Maximize application
SendMessage(proc.MainWindowHandle, 274, 61488, 0);
I have implemented a similar thing a few years ago (.NET Framework 1.1 based, if I recall correctly). Key elements of that implementation were:
We created an extended Form class that exposed some specific functionality, such as an interface for extracting user commands that would invoke the UI.
The main application would scan the dll's in the application directory and inspect them (using Reflection) to find any classes based on our special Form class, and extract information out of them to build menu structures that would invoke the commands.
When a user invoked a command that would lead to a form being displayed, it was created (using Activator.CreateInstance), stripped from form borders and embedded into a container (in our case a TabPage in a TabControl, in your case most likely an "empty" MDI Child form in your application).
This all worked out fairly well I think (I actually think that the framework is still being maintained and used within the company it was created for).
You may want to keep an eye at memory management. For instance, since an assembly cannot be unloaded, if that is a requirement you will need to load external assemblies into separate AppDomains. Also pay attention to any event handlers that are attached dynamically when child window UI's are loaded, so that they are properly detached when the UI's are unloaded.
Import the InteropServices and Threading namespaces
using System.Runtime.InteropServices;
using System.Threading;
Import SetParent from user32.dll
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr child,IntPtr parent);
Create a new process and make it an MDI child of our form using SetParent
Process proc;
// Start the process
proc = Process.Start("calc.exe");
proc.WaitForInputIdle();
Thread.Sleep(500);
// Set the panel control as the application's parent
SetParent(proc.MainWindowHandle, this.panel1.Handle);

Categories