Wpf and Hwnd unique name - wpf

we have a wpf application that should be 'piloted' by a legacy win32 winform application. (We don't own the code ;) )
The legacy application should pilot our application (minimize, bring to front, shut, etc) via windowsclass name we should provide as a configuration parameter written into an ini file.
The problem is we cannot make it work with wpf since if we insert the classname Spy++ gives us, nothing happens. The point is Spi++ returns something like this
HwndWrapper[MyWpfProgram.exe;;16978ce2-3b8d-4c46-81ee-e1c6d6de4e6d]
where the guid is randomly generated at every run.
Is there any way to solve this issue?
Thank you.

There is no way to do what I asked. But we found a walkaround. "Simply" embedding the xaml windows within a windows form.
These are the steps we followed:
1 - Add a Windows Form to the project.
2 - Remove the app.xaml and make the new form the entry point of the application.
3 - Since we need the hwnd of the main.xaml we added this prop to its code behind
public IntPtr Hwnd
{
get { return new WindowInteropHelper(this).Handle; }
}
4 - then from the constructor of the form we create an instance of the wpf window class
private Main app;
public ContainerForm()
{
InitializeComponent();
app = new Main();
ElementHost.EnableModelessKeyboardInterop(app);
}
we needed
ElementHost.EnableModelessKeyboardInterop(app);
since we want all the keyboard input to pass from the the windows form to the xaml window
5 - now we want to bond the xpf window to the winform. In order to do that we need to use Windows Api and we do it at the OnShow event of the form (the reason why will be explicated later).
[DllImport("user32.dll", SetLastError = true)]
private static extern long SetFocus(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
private static extern long SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);
[DllImport("user32.dll", EntryPoint = "SetWindowLongA", SetLastError = true)]
private static extern long SetWindowLong(IntPtr hwnd, int nIndex, long dwNewLong);
private const int GWL_STYLE = (-16);
private const int WS_VISIBLE = 0x10000000;
private void ContainerForm_Shown(object sender, EventArgs e)
{
app.Show();
SetParent(app.Hwnd, this.Handle);
SetWindowLong(app.Hwnd, GWL_STYLE, WS_VISIBLE);
MoveWindow(app.Hwnd, 0, 0, this.Width, this.Height, true);
SetFocus(app.Hwnd);
}
with
SetParent(app.Hwnd, this.Handle);
wo do the magic, then with
SetWindowLong(app.Hwnd, GWL_STYLE, WS_VISIBLE);
we remove al the chrome from the wpf window (there is a border even if the window is defined borderless, don't ask me why)
then we make the wpf window fill all the client area of the winform
MoveWindow(app.Hwnd, 0, 0, this.Width, this.Height, true);
and then we focus the wpf window
SetFocus(app.Hwnd);
that's the reason why we do everything in the show event. Since if we do it at form's constructor, then the wpf window will loose its focus since the in winform the main window got the focus from the operating system.
We didn't understand why we needed to add the other api calls at this point, but if we left them at constructor's the trick didn't work.
Anyway,
problem solved ;)

Use HwndSource.
You can use native Windows API calls to create a window with the expected classname, then use HwndSource to add WPF content to it:
var source = HwndSource.FromHwnd(nativeWindowHandle);
source.RootVisual = mainGrid;
If you need to use a WPF window, I think you could still solve this with a "proxy" window, but it wouldn't be pretty:
Have your WPF application spawn a native message-only window.
Use HwndSource.AddHook to handle messages like WM_CLOSE, WM_SIZE on the native window and pass them along to the "real" WPF window.

For the window handles, titles, and class names, Spy++ uses fairly simple Windows APIs.
FindWindowEx http://msdn.microsoft.com/en-us/library/windows/desktop/ms633500%28v=vs.85%29.aspx
EnumWindows http://msdn.microsoft.com/en-us/library/windows/desktop/ms633497%28v=vs.85%29.aspx
GetClassName http://msdn.microsoft.com/en-us/library/windows/desktop/ms633582%28v=vs.85%29.aspx
You can create a "loader" program that will...
Start the wpf app
Use the above APIs to get the proper class names and windows handles
Edit the legacy INI
Start the legacy app

Related

Draw on Desktop from WPF application

I would draw a rectangle on desktop from my WPF application. I've searched but i didn't find a good solution and a good example.
I would draw a rectangle at the edges of the screen and changes its color when something of specific happen.
How i can i do this in a correct way?
I found this code :
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
class Program {
[DllImport("User32.dll")]
static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("User32.dll")]
static extern void ReleaseDC(IntPtr dc);
static void Main(string[] args) {
IntPtr desktop = GetDC(IntPtr.Zero);
using (Graphics g = Graphics.FromHdc(desktop)) {
g.FillRectangle(Brushes.Red, 0, 0, 100, 100);
}
ReleaseDC(desktop);
}
}
But i don't have a console application and i don't understand how i can re-paint / refresh my rectangle or change its color from this code.
thank all.
You can create a full screen WPF Application that has a transparent Window. You can find out how to do that from the Creating Border-less Windows in WPF page on Paul Sherrif's Blog. In short though, to get a borderless window, you need to set the following attributes on your Window:
•WindowStyle="None"
•ShowInTaskbar="False"
•AllowsTransparency="True"
•Background="Transparent"
Then you simply do the drawing in the WPF Application, but it will look like the drawing is on the Desktop.
This code cannot be applied to WPF in any manner. WPF is a retained-mode API, unlike Windows Forms, so you can't draw it like this (actually you can use HWND interop or DrawingVisual). But it shouldn't bother you as you don't need to draw it by yourself, just declare required rectangles and any other stuff using XAML.

WPF Window and WndProc

The code snipper below is taken from "WPF 4 Unleashed". it demonstrates hwo in windows 7 it's possible to create the Aero Glass effect using WIN32 API. In this demo, the WndProc events procedure is used with respect to the Window instance. I noticed that in this routine there is no invocation of the default window procedure, as if there are no other events that need to be handled by that WPF window.
What brings me to post that question -- which is more of a general question regarding WPF -- is whether the events that are normally handles by WPF window (and I am sure there are many of them) are handled by some other procedure. In other words, is WPF window different than WinForms --- does it gets messages from Operating system (mouse clicking, mouse movements) by other means ?
[StructLayout(LayoutKind.Sequential)]
public struct MARGINS
{
public MARGINS(Thickness t)
{
Left = (int)t.Left;
Right = (int)t.Right;
Top = (int)t.Top;
Bottom = (int)t.Bottom;
}
public int Left;
public int Right;
public int Top;
public int Bottom;
}
public class GlassHelper
{
[DllImport("dwmapi.dll", PreserveSig=false)]
static extern void DwmExtendFrameIntoClientArea( IntPtr hWnd, ref MARGINS pMarInset);
[DllImport("dwmapi.dll", PreserveSig=false)]
static extern bool DwmIsCompositionEnabled();
public static bool ExtendGlassFrame(Window window, Thickness margin)
{
if (!DwmIsCompositionEnabled())
return false;
IntPtr hwnd = new WindowInteropHelper(window).Handle;
if (hwnd == IntPtr.Zero)
throw new InvalidOperationException(
"The Window must be shown before extending glass.");
// Set the background to transparent from both the WPF and Win32 perspectives
window.Background = Brushes.Transparent;
HwndSource.FromHwnd(hwnd).CompositionTarget.BackgroundColor =Colors.Transparent;
MARGINS margins = new MARGINS(margin);
DwmExtendFrameIntoClientArea(hwnd, ref margins);
return true;
}
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
// This can’t be done any earlier than the SourceInitialized event:
GlassHelper.ExtendGlassFrame(this, new Thickness(-1));
// Attach a window procedure in order to detect later enabling of desktop
// composition
IntPtr hwnd = new WindowInteropHelper(this).Handle;
HwndSource.FromHwnd(hwnd).AddHook(new HwndSourceHook(WndProc));
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_DWMCOMPOSITIONCHANGED)
{
// Reenable glass:
GlassHelper.ExtendGlassFrame(this, new Thickness(-1));
handled = true;
}
return IntPtr.Zero;
}
private const int WM_DWMCOMPOSITIONCHANGED = 0x031E;
WPF window is the same as WinForms window in terms of using WndProc. I had no problem to put the snippet into my WPF app. In fact, I didn't find any WndProc related code, that didn't work in WPF so far.
WPF windows are like Windows Forms windows and like classic Windows windows in that they all have a Message Loop for receiving messages and a WindowProc (the actual name can be whatever the programmer chooses to make it) to process them. All the windows can be subclassed (as in About Window Procedures), at least at the level below WPF. I don't know if WndProc for Windows Forms or for WPF are subclassing the relevant windows but they might be.

Get the handle of the form the mouse is currently on in VB.net

Is it possible to get a forms handle (regardless if it is my program or not) based on position (i.e. the mouse position)?
Try:
[DllImport("user32.dll", EntryPoint = "WindowFromPoint")]
static public extern IntPtr WindowFromPoint(Point Point);
and pass Cursor.Position to get the handle over the current 'visible' window.

How to apply WS_EX_TRANSPARENT in WPF?

I want to make a splash screen, which cannot be clicked/selected by mouse/UI.
As such how to I apply
Win32.ExtendedWindowStyles.WS_EX_TRANSPARENT
on Windows Presentation Foundation Window?
In Forms I'd do this.
public const int WS_EX_TRANSPARENT = 0x00000020;
public const int GWL_EXSTYLE = (-20);
[DllImport("user32.dll")]
public static extern int GetWindowLong(IntPtr hwnd, int index);
[DllImport("user32.dll")]
public static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle);
public static void ToTransparentWindow(this Window x)
{
x.SourceInitialized +=
delegate
{
// Get this window's handle
IntPtr hwnd = new WindowInteropHelper(x).Handle;
// Change the extended window style to include WS_EX_TRANSPARENT
int extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE);
SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT);
};
}
You can use a forms host to host a win form if you really want, then you can use anything win forms related in WPF.
But keep in mind WPF is built on direct X. However, there is already a splash screen class that is not based on WPF and will render while the .Net runtime does its thing. To my knowledge it doesn't have the same routed event pipeline that WPF windows have. You might try looking there before going down the forms host route.
in Win32 Api you can assign style on CreateWindow(Ex) or later by using SetWindowLong maybe there is some kinfd of wrapper on WPF

Custom properties on a win32 window

I've heard (well read, at http://www.ddj.com/windows/184416861), that it's possible to set custom properties on a Win32 window.
The trouble is, the download for the article above is on an ftp server that won't let me in.
As a bit of background info, I have a .NET app. The main window is registered to handle custom window messages. From a separate app, I need to post messages to this window. I can't find the window by caption as the caption changes. I can't find it JUST by window class, as the window class is the same for all forms in that app domain.
Ideally, I'd like to set a custom property on the Win32 window of the main form (Form1) that say, yes, this is form1. Then when I'm enumerating the windows of this app, I can tell that this is the required form by seeing if this custom property exists.
Cheers,
Steve
See here for an overview of window properties. Basically, you call the Win32 API function SetProp to set a window property and GetProp to retrieve it. There are a few more functions for enumerating properties and the like, but it sounds as if SetProp and GetProp is all you need.
As Martin says, the answer is the Win32 APIs GetProp and SetProp.
Here's what I now do when I create the main form:
[DllImport("user32.dll", SetLastError=true)]
static extern bool SetProp(IntPtr hWnd, string lpString, IntPtr hData);
SetProp( this.Handle, #"foo", new IntPtr( 1 ) ) ;
Now, I can check this property when enumerating the windows:
[DllImport("user32.dll")]
private static extern IntPtr GetProp(IntPtr hWnd, string lpString);
IntPtr result = GetProp( (IntPtr) hWnd, #"foo" ) ;

Resources