Resolved Windows Forms Application overlayed other Application

shawnhee

Member
Joined
Dec 2, 2020
Messages
10
Programming Experience
Beginner
My WFA has overlayed other application since i added this code unto it. But i need this code to lock other users from repositioning the form. Please help ?
C#:
protected override void WndProc(ref Message m)
{
    const int WM_NCLBUTTONDOWN = 161;
    const int WM_SYSCOMMAND = 274;
    const int HTCAPTION = 2;
    const int SC_MOVE = 61456;
    if ((m.Msg == WM_NCLBUTTONDOWN)&&
        (m.WParam.ToInt32() == SC_MOVE))
    {
        return;
    }
    if ((m.Msg == WM_NCLBUTTONDOWN) &&
        (m.WParam.ToInt32() == HTCAPTION))
    {
        return;
    }
    base.WndProc(ref m);
 
Last edited by a moderator:
Solution
This may or may not be of interest but here are a couple of classes I created several years ago:
SystemMenuManager Class:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    /// <summary>
    /// Removes and disables the Move and Close items in a form's system menu.
    /// </summary>
    public sealed class SystemMenuManager
    {
        /// <summary>
        /// The possible states of a menu item.
        /// </summary>
        public enum MenuItemState
        {
            /// <summary>
            /// Appears normal and responds to clicks.
            /// </summary>
            Enabled = MF_ENABLED,
            /// <summary>
            /// Appears greyed out and does not respond to...
Try it by removing : m.Msg == WM_NCLBUTTONDOWN) && (
Checking buttons is not required. Remove the quoted from your code.

Does your window form border style need to be a 3d? In simple terms, does it need the min, max, close buttons on the top right?

If not, here is a simpler way to do it :
C#:
        Point SetLocation = new Point(500, 250);
        public Form1()
        {
            InitializeComponent();
            this.Location = SetLocation;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.SizeGripStyle = SizeGripStyle.Hide;
            this.FormBorderStyle = FormBorderStyle.None;
        }       
        private void Form1_Move(object sender, EventArgs e)
        {
            this.Location = SetLocation;
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.None;
        }
Otherwise, if my code above is no use to you, you will need to use the SC_Move API as you are, and as mentioned here : WM_SYSCOMMAND message (Winuser.h) - Win32 apps

There is an example I found here (Source below) : Creating a immovable windows’ form in c#

This is not my source, as this is the authors source of the linked comment above, so all credit to him for this snipped :
C#:
protected override void WndProc(ref Message message)
{
    const int WM_SYSCOMMAND = 0x0112;
    const int SC_MOVE = 0xF010;
    switch(message.Msg)
    {
        case WM_SYSCOMMAND:
           int command = message.WParam.ToInt32() & 0xfff0;
           if (command == SC_MOVE)
              return;
           break;
    }
    base.WndProc(ref message);
}

You can find an elaborate answer to your question by Bill Woodruff here regarding how to prevent moving forms along with some good pointers : Disable move form in winform - CodeProject

I will now mark this as answered. Hope it helps!
 
This may or may not be of interest but here are a couple of classes I created several years ago:
SystemMenuManager Class:
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    /// <summary>
    /// Removes and disables the Move and Close items in a form's system menu.
    /// </summary>
    public sealed class SystemMenuManager
    {
        /// <summary>
        /// The possible states of a menu item.
        /// </summary>
        public enum MenuItemState
        {
            /// <summary>
            /// Appears normal and responds to clicks.
            /// </summary>
            Enabled = MF_ENABLED,
            /// <summary>
            /// Appears greyed out and does not respond to clicks.
            /// </summary>
            Greyed = MF_GRAYED,
            /// <summary>
            /// Appears normal but does not respond to clicks.
            /// </summary>
            Disabled = MF_DISABLED,
            /// <summary>
            /// Is not present.
            /// </summary>
            Removed
        }

        /// <summary>
        /// Represents the Move menu item.
        /// </summary>
        private const int SC_MOVE = 0xF010;
        /// <summary>
        /// Represents the Close menu item.
        /// </summary>
        private const int SC_CLOSE = 0xF060;

        /// <summary>
        /// Indicates that a menu item is identified by command ID.
        /// </summary>
        private const int MF_BYCOMMAND = 0x0;

        /// <summary>
        /// Indicates that a menu item is enabled.
        /// </summary>
        private const int MF_ENABLED = 0x0;
        /// <summary>
        /// Indicates that a menu item is greyed out.
        /// </summary>
        private const int MF_GRAYED = 0x1;
        /// <summary>
        /// Indicates that a menu item is disabled.
        /// </summary>
        private const int MF_DISABLED = 0x2;

        /// <summary>
        /// The form whose menu is being managed.
        /// </summary>
        private Form target;
        /// <summary>
        /// The state of the form's Close menu item.
        /// </summary>
        private MenuItemState closeState;
        /// <summary>
        /// The handle of the menu being managed.
        /// </summary>
        private IntPtr menuHandle;

        [DllImport("user32.dll")]
        private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

        [DllImport("user32.dll")]
        private static extern int EnableMenuItem(IntPtr hMenu, int wIDEnableItem, int wEnable);

        [DllImport("user32.dll")]
        private static extern bool DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);

        public SystemMenuManager(Form target, bool movePresent)
            : this(target, movePresent, MenuItemState.Enabled)
        {
        }

        public SystemMenuManager(Form target, MenuItemState closeState)
            : this(target, true, closeState)
        {
        }

        public SystemMenuManager(Form target, bool movePresent, MenuItemState closeState)
        {
            this.target = target;
            this.closeState = closeState;

            this.target.Load += new EventHandler(target_Load);
            this.target.Resize += new EventHandler(target_Resize);
            this.target.KeyDown += new KeyEventHandler(target_KeyDown);

            this.menuHandle = GetSystemMenu(target.Handle, false);

            if (!movePresent)
            {
                // Remove the Move menu item.
                DeleteMenu(this.menuHandle, SC_MOVE, MF_BYCOMMAND);
            }

            if (closeState == MenuItemState.Removed)
            {
                // Remove the Close menu item.
                DeleteMenu(this.menuHandle, SC_CLOSE, MF_BYCOMMAND);
            }
            else
            {
                this.RefreshCloseItem();
            }

            if (closeState != MenuItemState.Enabled)
            {
                // Set the Keypreview to True so that the Alt+F4 key combination can be detected.
                target.KeyPreview = true;
            }
        }

        /// <summary>
        /// Sets the state of the Close menu item if present but not enabled.
        /// </summary>
        private void RefreshCloseItem()
        {
            if (this.closeState == MenuItemState.Disabled || this.closeState == MenuItemState.Greyed)
            {
                EnableMenuItem(this.menuHandle,
                               SC_CLOSE,
                               MF_BYCOMMAND | (int)this.closeState);
            }
        }

        private void target_Load(object sender, EventArgs e)
        {
            // Refresh the initial state of the Close menu item.
            RefreshCloseItem();
        }

        private void target_Resize(object sender, EventArgs e)
        {
            // If present, the Close item will be re-enabled after a resize operation so refresh its state.
            RefreshCloseItem();
        }

        private void target_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F4 &&
                e.Alt &&
                this.closeState != MenuItemState.Enabled)
            {
                // Suppress the Alt+F4 key combination.
                e.Handled = true;
            }
        }
    }
}
FormImmobiliser Class:
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    /// <summary>
    /// Prevents a form being moved.
    /// </summary>
    public sealed class FormImmobiliser : NativeWindow
    {
        /// <summary>
        /// Represents a rectangular area.
        /// </summary>
        private struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;

            public RECT(Rectangle r)
            {
                this.Left = r.Left;
                this.Top = r.Top;
                this.Right = r.Right;
                this.Bottom = r.Bottom;
            }
        }

        private const int WM_MOVING = 0x216;
        private const int TRUE = 1;

        /// <summary>
        /// The form to be immobilised.
        /// </summary>
        private Form target;

        public FormImmobiliser(Form target)
        {
            this.target = target;
            this.target.HandleCreated += new EventHandler(target_HandleCreated);
            this.target.HandleDestroyed += new EventHandler(target_HandleDestroyed);
        }

        void target_HandleCreated(object sender, EventArgs e)
        {
            // Listent to the target forms message queue.
            this.AssignHandle(this.target.Handle);
        }

        void target_HandleDestroyed(object sender, EventArgs e)
        {
            this.ReleaseHandle();
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_MOVING)
            {
                // Reset the new location to the same as the current location.
                Marshal.StructureToPtr(new RECT(this.target.Bounds),
                                       m.LParam,
                                       false);
                m.Result = new IntPtr(TRUE);
            }

            base.WndProc(ref m);
        }
    }
}
The second class will prevent a form being moved but, if you have not set the form's ControlBox property to False then the system menu items will still be displayed when clicking the icon on the title bar. The first class can be used to disable/remove the Move and Close menu items. Here is some sample usage:
C#:
public partial class Form1 : Form
{
    SystemMenuManager menuManager;
 
    public Form1()
    {
        InitializeComponent();
 
        // Remove the Move menu item.
        this.menuManager = new SystemMenuManager(this, false);
    }
}
C#:
public partial class Form1 : Form
{
    SystemMenuManager menuManager;
 
    public Form1()
    {
        InitializeComponent();
 
        // Remove the Close menu item.
        this.menuManager = new SystemMenuManager(this, SystemMenuManager.MenuItemState.Removed);
    }
}
C#:
public partial class Form1 : Form
{
    SystemMenuManager menuManager;
 
    public Form1()
    {
        InitializeComponent();
 
        // Remove the Move menu item and grey out the Close menu item.
        this.menuManager = new SystemMenuManager(this, false, SystemMenuManager.MenuItemState.Greyed);
    }
}
C#:
public partial class Form1 : Form
{
    FormImmobiliser immobiliser;
 
    public Form1()
    {
        InitializeComponent();
 
        // Prevent the form being moved.
        this.immobiliser = new FormImmobiliser(this);
    }
}
 
Last edited:
Solution
Marked as best answer. While I haven't tried it. I see no reason for it not to work. It's the same API as posted above in both OP's post and mine, but your answer is more useful than the answer I provided, plus your inline comments are helpful too. Good share (y)
 
Hi, thanks for all replies,

But unfortunately what i need is to able to minimize/hide the app when i clicked anywhere outside the application, and display it again when i click from taskbar.... Because for now the app is unable to hide when i click outside it, so it is blocking my other running apps.....

Anyway i appreciate your help :)

Really sorry for disturbing.... Pls forgive ?
Hope to find another answer....
 
Can you explain why you need your program to overlay another program?
 
Actually i've found a solution, but this is not i want.... Because this will just close the whole program, what i want is just minimize it in taskbar, and show up again when i press it from taskbar

Here is the code:
C#:
        protected override void OnMouseCaptureChanged(EventArgs e)

        {

            if (!this.Capture)

            {

                if (!this.RectangleToScreen(this.DisplayRectangle).Contains(Cursor.Position))

                {

                    this.Hide();

                }

                else

                {

                    this.Capture = true;

                }

            }

            base.OnMouseCaptureChanged(e);

        }

Please help..... Your help is much appreciated
 
Last edited by a moderator:
Can you explain why you need your program to overlay another program?
Because i need to copy texts from the coded c# program and paste it at powerpoint. It would be more easy if i just click outside the program and paste it at powerpoint, and go back to the program again when i need to copy another thing. Now the coded program is blocking powerpoint.. So i need to press the minimize button at the top of the program to minimize it, which is slow.....
 
Because i need to copy texts from the coded c# program and paste it at powerpoint. It would be more easy if i just click outside the program and paste it at powerpoint, and go back to the program again when i need to copy another thing.
It sounds like all you needed was for your program to be "always on top", and not necessarily to be overlaying another program.

An alternative is just get another monitor. Run Powerpoint on one monitor and your program on another monitor.
 

Latest posts

Back
Top Bottom