I'm trying to get window messages in a WPF app to be able to use the Win32 API; the problem is that every time the app goes out of focus/is minimized I'm unable to receive any more messages. I tried doing this but my implementation of it in WPF (which I'm not entirely sure of how correct it is, see code below) converts the window to a read-only window after which I can't interact with the GUI at all, it's not even there in the taskbar anymore (Not to mention how this only works if I minimize the window, it doesn't help when the app is still on the screen but out of focus).
public partial class MainWindow : Window
{
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);
private int SC_MONITORPOWER = 0xF170;
private int WM_SYSCOMMAND = 0x0112;
private int SC_MINIMIZE = 0xF020;
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
source.AddHook(WndProc);
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WM_SYSCOMMAND) //Intercept System Command
{
if ((wParam.ToInt32() & 0xFFF0) == SC_MONITORPOWER)
{ //Intercept Monitor Power Message
MessageBox.Show("WORKING");
}
if ((wParam.ToInt32() & 0xFFF0) == SC_MINIMIZE)
{
ChangeToMessageOnlyWindow();
}
}
return IntPtr.Zero;
}
private void ChangeToMessageOnlyWindow()
{
IntPtr HWND_MESSAGE = new IntPtr(-3);
SetParent(new WindowInteropHelper(this).Handle, HWND_MESSAGE);
}
}