且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

创建自定义形状的Windows窗体而不是“默认"矩形?

更新时间:2023-12-06 16:41:34

TransparencyKey方法,已讨论   

哇!它确实起作用,但是距离完成还有很长的路要走.还有很多小事情需要完成.例如:

  • 单击字幕按钮不会按下".有一个内置状态可以与 DrawCaptionButton 方法一起使用,但是您需要在单击其中一个按钮时强制重新绘制,或者直接在窗体右侧进行重新绘制然后到那里.
  • 它不支持视觉样式.这是 ControlPaint 类的限制;它是在发明视觉样式之前编写的.实现对此的支持将需要做更多的工作,但是有 WinForms包装器.您将必须确保编写后备代码来处理禁用视觉样式的情况.
  • 字幕按钮实际上并没有居中-我只是盯着它看.即使您的眼球比我的眼球好,这仍然是一个糟糕的方法,因为字幕按钮的大小可以不同,具体取决于系统设置和您所运行的操作系统的版本(Vista更改了按钮的形状).
  • 当鼠标悬停在标题栏按钮上方时,其他窗口将调用这些动作.但是,当您尝试使用 WM_NCLBUTTONUP (而不是 WM_NCLBUTTONDOWN )时,必须双击字幕按钮才能使它们工作.这是因为非客户区正在捕获鼠标.我敢肯定有解决方案,但是在发现真正的解决方案之前我就忍耐了.
  • 当窗口最小化(或还原)时,您不会获得漂亮的动画效果,字幕按钮也没有悬停发光.您可以免费获得大量视觉效果,这些默认风格在这里是行不通的.通过编写更多代码,可以轻松添加其中的某些内容,但是对于您编写的每一行,维护负担激增—较新版本的Windows可能会破坏事情.更糟糕的是,有些事情远不容易实现,因此甚至不值得.而所有这些努力又是为了什么?
  • 仅在激活/停用时重新绘制整个表单以更新标题按钮可能是一个坏主意.如果您要在表单上绘制其他更复杂的内容,则可能会减慢整个系统的运行速度.
  • 一旦开始将控件添加到表单,则可能会遇到问题.例如,即使有了Label控件,也无法通过单击并按住该Label控件的顶部来拖动窗体.标签控件不会响应 WM_NCHITTEST 消息而返回 HTTRANSPARENT ,因此该消息不会传递给父表单.您可以对 Label 进行子类化,并改用子类.
  • 该代码未在Windows 8上经过完全测试 ,因为我没有副本.自定义非客户区域往往会因新的OS更新而崩溃,新的操作系统更新会更改非客户区域的呈现方式,因此您需要自行调整相应的代码.即使可以正常使用,也肯定不会具有正确的Windows 8外观.
  • Et cetera et cetera .

您还可以看到,就像我在上文中警告过的那样,圆形边框没有抗锯齿,因此看起来参差不齐.不幸的是,这是无法解决的.

I am looking to create a custom shaped form in c#.

I have a background image (png) that has is transparent in some places.

Is there anyway of making the form shape to be the shape of this image instead of the 'usual' rectangle?

I am only asking this as I wish to design a custom skin for my PC (a bit like rainmeter/rocketdock combined, but in a 'compressed' way).

I have heard of using a 'transparency key', but this would remove a colour from the background (I will be using a colour picker in a later stage, and so if the user chose that specific colour, it would not show).

As always, any help would be much appreciated.

The TransparencyKey approach, discussed here on MSDN is the simplest way to do this. You set your form's BackgroundImage to an image mask. The image mask has the regions to be transparent filled with a certain color—fuchsia is a popular choice, since no one actually uses this horrible color. Then you set your form's TransparencyKey property to this color, and it is essentially masked out, rendering those portions as transparent.

But I guess in a color picker, you want fuchsia to be available as an option, even if no one ever selects it. So you'll have to create custom-shaped forms the other way—by setting a custom region. Basically, you create a Region object (which is basically just a polygon) to describe the desired shape of your form, and then assign that to the form's Region property.

Do note that you are changing the shape of the entire window when you do this, not just the client area, so your design needs to account for that. Also, regions cannot be anti-aliased, so the result tends to be pretty ugly if you're using a shape that does not have straight edges.

And another caveat…I strongly recommend not doing this. It takes quite a bit of work to get it right, and even once you get finished, the result is usually gaudy and user-hostile. Even when everything goes just right, you'll end up with something that looks like this—and no one wants that. Users are quite accustomed to boring old rectangular application windows. Applications shouldn't try to be exact digital replicas of real-world widgets. It seems like that would make them intuitive or easy to use, but it really doesn't. The key to good design is identifying the user's mental model for your application and figuring out a good way of meshing that with the standards set by your target windowing environment.


I noticed this tab still open and had a few spare moments, so I tried to bang out a quick sample. I made the "form" consist of two randomly-sized circles, just to emphasize the custom shape effect and the transparency—don't read anything into the design or get any crazy ideas! Here's what I came up with:

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

public class MyCrazyForm : Form
{
   private Size szFormSize = new Size(600, 600);
   private Size szCaptionButton = SystemInformation.CaptionButtonSize;
   private Rectangle rcMinimizeButton = new Rectangle(new Point(330, 130), szCaptionButton);
   private Rectangle rcCloseButton = new Rectangle(new Point(rcMinimizeButton.X + szCaptionButton.Width + 3, rcMinimizeButton.Y), SystemInformation.CaptionButtonSize);

   public MyCrazyForm()
   {
      // Not necessary in this sample: the designer was not used.
      //InitializeComponent();

      // Force the form's size, and do not let it be changed.
      this.Size = szFormSize;
      this.MinimumSize = szFormSize;
      this.MaximumSize = szFormSize;

      // Do not show a standard title bar (since we can't see it anyway)!
      this.FormBorderStyle = FormBorderStyle.None;

      // Set up the irregular shape of the form.
      using (GraphicsPath path = new GraphicsPath())
      {
         path.AddEllipse(0, 0, 200, 200);
         path.AddEllipse(120, 120, 475, 475);
         this.Region = new Region(path);
      }
   }

   protected override void OnActivated(EventArgs e)
   {
      base.OnActivated(e);

      // Force a repaint on activation.
      this.Invalidate();
   }

   protected override void OnDeactivate(EventArgs e)
   {
      base.OnDeactivate(e);

      // Force a repaint on deactivation.
      this.Invalidate();
   }

   protected override void OnPaint(PaintEventArgs e)
   {
      base.OnPaint(e);

      // Draw the custom title bar ornamentation.
      if (this.Focused)
      {
         ControlPaint.DrawCaptionButton(e.Graphics, rcMinimizeButton, CaptionButton.Minimize, ButtonState.Normal);
         ControlPaint.DrawCaptionButton(e.Graphics, rcCloseButton, CaptionButton.Close, ButtonState.Normal);
      }
      else
      {
         ControlPaint.DrawCaptionButton(e.Graphics, rcMinimizeButton, CaptionButton.Minimize, ButtonState.Inactive);
         ControlPaint.DrawCaptionButton(e.Graphics, rcCloseButton, CaptionButton.Close, ButtonState.Inactive);
      }
   }

   private Point GetPointFromLParam(IntPtr lParam)
   {
      // Handle 64-bit builds, which we detect based on the size of a pointer.
      // Otherwise, this is functionally equivalent to the Win32 MAKEPOINTS macro.
      uint dw = unchecked(IntPtr.Size == 8 ? (uint)lParam.ToInt64() : (uint)lParam.ToInt32());
      return new Point(unchecked((short)dw), unchecked((short)(dw >> 16)));
   }

   protected override void WndProc(ref Message m)
   {
      const int WM_SYSCOMMAND = 0x112;
      const int WM_NCHITTEST = 0x84;
      const int WM_NCLBUTTONDOWN = 0xA1;
      const int HTCLIENT = 1;
      const int HTCAPTION = 2;
      const int HTMINBUTTON = 8;
      const int HTCLOSE = 20;

      // Provide additional handling for some important messages.
      switch (m.Msg)
      {
         case WM_NCHITTEST:
            {
               base.WndProc(ref m);

               Point ptClient = PointToClient(GetPointFromLParam(m.LParam));
               if (rcMinimizeButton.Contains(ptClient))
               {
                  m.Result = new IntPtr(HTMINBUTTON);
               }
               else if (rcCloseButton.Contains(ptClient))
               {
                  m.Result = new IntPtr(HTCLOSE);
               }
               else if (m.Result.ToInt32() == HTCLIENT)
               {
                  // Make the rest of the form's entire client area draggable
                  // by having it report itself as part of the caption region.
                  m.Result = new IntPtr(HTCAPTION);
               }

               return;
            }
         case WM_NCLBUTTONDOWN:
            {
               base.WndProc(ref m);

               if (m.WParam.ToInt32() == HTMINBUTTON)
               {
                  this.WindowState = FormWindowState.Minimized;
                  m.Result = IntPtr.Zero;
               }
               else if (m.WParam.ToInt32() == HTCLOSE)
               {
                  this.Close();
                  m.Result = IntPtr.Zero;
               }

               return;
            }
         case WM_SYSCOMMAND:
            {
               // Setting the form's MaximizeBox property to false does *not* disable maximization
               // behavior when the caption area is double-clicked.
               // Since this window is fixed-size and does not support a "maximized" mode, and the
               // entire client area is treated as part of the caption to enable dragging, we also
               // need to ensure that double-click-to-maximize is disabled.
               // NOTE: See documentation for WM_SYSCOMMAND for explanation of the magic value 0xFFF0!
               const int SC_MAXIMIZE = 0xF030;
               if ((m.WParam.ToInt32() & 0xFFF0) == SC_MAXIMIZE)
               {
                  m.Result = IntPtr.Zero;
               }
               else
               {
                  base.WndProc(ref m);
               }
               return;
            }
      }
      base.WndProc(ref m);
   }
}

Here it is running on Windows XP and 7, side-by-side:

     

Whew! It does work, but it's a long way from complete. There are lots of little things that still need to be done. For example:

  • The caption buttons do not "depress" when clicked. There is a built-in state for that that can be used with the DrawCaptionButton method, but you need to either force a redraw when one of the buttons is clicked, or do the repaint directly on the form right then and there.
  • It doesn't support Visual Styles. This is a limitation of the ControlPaint class; it was written before Visual Styles were invented. Implementing support for this will be a lot more work, but there is a WinForms wrapper. You will have to make sure that you write fallback code to handle the case where Visual Styles are disabled, too.
  • The caption buttons aren't actually centered—I just eyeballed it. And even if your eyeballs are better than mine, this is still a bad approach, because the caption buttons can be different sizes, depending on system settings and which version of the OS you're running (Vista changed the button shapes).
  • Other windows invoke the actions when the mouse goes up over the caption bar buttons. But when you try to use WM_NCLBUTTONUP (instead of WM_NCLBUTTONDOWN), you have to double-click the caption buttons to make them work. This is because the non-client area is capturing the mouse. I'm sure there's a solution, but I ran out of patience before I discovered what it was.
  • You don't get the pretty animation effects when the window is minimized (or restored), nor do you have the glow-on-hover for the caption buttons. There are tons of visual niceties that you get for free with the default styles that are missing-in-action here. Some of them can be easily added by writing more code, but for each line you write, the maintenance burden skyrockets—newer versions of Windows are likely to break things. And worse, some things are far from trivial to implement, so it probably isn't even worth it. And all this effort for what, again?
  • Repainting the entire form on activation/deactivation just to update the caption buttons is probably a bad idea. If you are painting anything else more complicated on the form, this is likely to slow down the entire system.
  • Once you start adding controls to the form, you might run into a problem. For example, even with a Label control, you won't be able to drag the form around by clicking and holding on top of that Label control. Label controls don't return HTTRANSPARENT in response to the WM_NCHITTEST message, so the message doesn't get passed on to the parent form. You can subclass Label to do so and use your subclass instead.
  • The code is completely untested with Windows 8, since I don't have a copy. Custom non-client areas tend to blow up with new OS updates that change the way the non-client area is rendered, so you're on your own to adapt the code accordingly. Even if it works, it certainly won't have the right Windows 8 look-and-feel.
  • Et cetera, et cetera.

You can also see that, like I cautioned above, the circular border is not anti-aliased, so it looks jagged. Unfortunately, that is unfixable.