[Tips] 如何建立一個透明的視窗,而且可以透過它操作背景的檔案或是icon

[Tips] 如何建立一個透明的視窗,而且可以透過它操作背景的檔案或是icon

近期接到一個客戶的需求 - 如何建立一個透明的視窗,而且可以透過它操作背景的檔案或是icon。

 

網路搜尋並實作後,可以參考下列作法:

1. 建立Windows專案以後,將此Form的BackColor與TransparencyKey屬性的設定值都選為Control。

image

 

image

 

2. 把FormBorderStyle屬性的設定值設為None。

image

 

4. 在畫面上放置一個Label,並設定所欲顯示的文字

 

5. 顯示結果:

image

image

 

 

執行後,發現切換不同程式會造成原先的透明程式被放到下一層,所以找一下看看有沒有可以讓程式畫面永遠在最上層的方法,請參考下列方法:

 

5. 在畫面中設定下列程式(呼叫SetWindowsPos API來調整Order),讓程式永遠都在其他視窗上面:

   1:  public partial class Form1 : Form
   2:  {
   3:          static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
   4:          const UInt32 SWP_NOSIZE = 0x0001;
   5:          const UInt32 SWP_NOMOVE = 0x0002;
   6:          const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
   7:   
   8:          [DllImport("user32.dll")]
   9:          [return: MarshalAs(UnmanagedType.Bool)]
  10:          public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
  11:   
  12:          public Form1()
  13:          {
  14:              InitializeComponent();
  15:          }
  16:   
  17:          private void Form1_Load(object sender, EventArgs e)
  18:          {
  19:              SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
  20:          }
  21:   }

 

 

 

6. 執行結果:

看個影片也浮在上面了…

image

 

 

 

 

參考連結:

Form.TransparencyKey - http://msdn.microsoft.com/zh-tw/library/system.windows.forms.form.transparencykey.aspx

SetWindowPos - http://msdn.microsoft.com/en-us/library/windows/desktop/ms633545(v=vs.85).aspx

 

 

如果您有微軟技術開發的問題,可以到MSDN Forum發問。

如果您有微軟IT管理的問題,可以到TechNet Forum發問喔。