WndProc handler is inefficient

I have the following WndProc handler in my form. This should prevent the form from moving horizontally (allowing only vertical movement):

protected override void WndProc(ref System.Windows.Forms.Message m)
{
    if (!ShowCaption && m.Msg == 0x216)
    {  // Trap WM_MOVING
        var rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
        int w = rc.right - rc.left;
        rc.left = this.Left;
        rc.right = rc.left + w;
        Marshal.StructureToPtr(rc, m.LParam, false);
    }
    base.WndProc(ref m);
}

This works, but when the user moves the form, CPU usage is greatly increased. What can be so ineffective in this function and are there any ways?

+3
source share
2 answers

I tried my code and it works well. It did not saturate a 100% processor, as you said, only took ~ 16%.

I believe that processing takes a lot of time, it is a drawing of your form or a drawing of your background windows (and not an implementation of wndproc).

, ,

System.Threading.Thread.Sleep(10);

:

Marshal.StructureToPtr(rc, m.LParam, false);

10 100 , ...

EDIT: , ~ 16% ~ 12% .

+2

, base.WndProc If

if (!ShowCaption && m.Msg == 0x216)
{
    // Trap WM_MOVING
}
else
{
    base.WndProc(ref m);
}

( , )

public partial class Form1 : Form
{
    private int initialX;
    public Form1()
    {
        InitializeComponent();
        initialX = this.Location.X;
    }

    private void Form1_LocationChanged(object sender, EventArgs e)
    {
        if (this.Location.X != initialX)
            this.Location = new Point(initialX, this.Location.Y);
    }
}
+1

Source: https://habr.com/ru/post/1779961/


All Articles