需要提前說明一下:
win7系統比較特殊,下面將要說到PictureBox控件的背景色BackColor
1 BackColor設爲綠色時,PictureBox,既不被鼠標擊穿,也不透明;
2 BackColor設爲藍色時,PictureBox,可以被鼠標擊穿,但不透明;
3 BackColor設爲黑色時,PictureBox,可以被鼠標擊穿,並且透明(滿足要求);
但這位老兄https://blog.csdn.net/rediculous/article/details/8877638說:Win7下VS2010編程時,關鍵色只能是綠色或黑色。
轉入正題:
下面的內容均轉自:https://www.cnblogs.com/ifdog/p/5940015.html#commentform
注意:我在它的內容上做了一些修改:
這傢伙做這個需求的目的源於一個叫LICEcap的錄屏軟件(這個軟件我手上有一個,免安裝的),他想做的效果如下
這個炫酷的空心窗口就是鏡頭,調整好大小,然後對準需要錄製的地方按下Record就可以生成gif了。
一 操作控件透明和被鼠標擊穿的步驟:
1 在Visual Studio裏新建一個Winform項目,並拖入一個PictureBox控件並設置其屬性BackColor爲Green,如下圖:
注意了:BackColor屬性的設置,如果在win7下就要注意了,文章開頭已經說了
2 在主窗體程序編寫如下:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.TopMost = true;
SetWindowLong(this.Handle, GWL_EXSTYLE, WS_EX_LAYERED);
SetLayeredWindowAttributes(this.Handle, 65280, 255, LWA_COLORKEY);
}
private const uint WS_EX_LAYERED = 0x80000;
private const int GWL_EXSTYLE = -20;
private const int LWA_COLORKEY = 1;
[DllImport("user32", EntryPoint = "SetWindowLong")]
private static extern uint SetWindowLong(IntPtr hwnd,int nIndex,uint dwNewLong);
[DllImport("user32", EntryPoint = "SetLayeredWindowAttributes")]
private static extern int SetLayeredWindowAttributes(IntPtr hwnd,int crKey,int bAlpha,int dwFlags);
}
先使用SetWindowLong將窗口定義爲分層窗體,然後調用SetLayeredWindowAttributes方法設置透明。
其中第二個參數crKey爲一個int型的顏色值,轉換方式爲(int)(0xRRGGBB),本例中Dec(0x00FF00)=65280爲綠色。
第四個參數爲透明方式,本例中使用LWA_COLORKEY = 1,表示將該窗口顏色爲crKey的部分都設置爲透明。
因此相應地,我們需要在窗口設計器中畫一個顏色爲綠色的方塊。本例中使用了一個PictureBox,並設置了背景顏色。
注意:
1 如果PictureBox的背景色爲黑色,則代碼SetLayeredWindowAttributes(this.Handle, 65280, 255, LWA_COLORKEY)中的65280改爲0
2 如果PictureBox的背景色爲藍色,則代碼SetLayeredWindowAttributes(this.Handle, 65280, 255, LWA_COLORKEY)中的65280改爲255
3 最終效果如下:
二 整個窗體被鼠標擊穿和透明
只需要在窗體程序中加入TransparencyKey = BackColor即可,如下:
public Form1()
{
InitializeComponent();
TransparencyKey = BackColor;//背景透明(鼠標穿透)
}
其它的就不要了