1

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);
            }
    }
Hasan
  • 101
  • 8
  • 1
    You'll have to get rid of ChangeToMessageOnlyWindow(), message-only windows are meant to implement private messaging, they don't receive system messages. – Hans Passant May 10 '22 at 18:53
  • What should I replace it with? Could you please provide a more detailed answer – Hasan May 10 '22 at 19:11
  • A minimized i.e hidden window does not receive input and therefore does not broadcast any events. – BionicCode May 11 '22 at 10:57
  • What window messages were you expecting to get from a minimised window? I also don't follow what you're attempting to achieve. Please clarify your question - in the question. – Andy May 11 '22 at 17:28

0 Answers0