2015-11-03 51 views
2

我有一個窗體,其中有各種按鈕和麪板。我有一個按鈕,當按下按鈕時會對某些值執行檢查,如果檢查通過,我需要鼠標單擊以通過窗體下落並打到應用程序窗口下面的任何按鈕。點擊通過表單上的條件

被按下後,按鈕,檢查已通過什麼我目前做的是,我的表格設置爲透明使用:

[DllImport("user32.dll", SetLastError = true)] 
static extern int GetWindowLong(IntPtr hWnd, int nIndex); 

[DllImport("user32.dll")] 
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); 
private int oldWindowLong = 0; 

public void SetFormTransparent(IntPtr Handle) 
{ 
    oldWindowLong = GetWindowLong(Handle, -20); 
    SetWindowLong(Handle, -20, Convert.ToInt32(oldWindowLong | 0x80000 | 0x20)); 
} 

public void SetFormNormal(IntPtr Handle) 
{ 
    SetWindowLong(Handle, -20, Convert.ToInt32(oldWindowLong | 0x80000)); 
} 

然後我創建了一個1毫秒定時器,我模擬鼠標點擊使用:

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] 
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo); 

並將窗體設置恢復正​​常。這導致了一個非常不一致,有時緩慢/無反應的行爲。

如果我想在按鈕檢查通過後模擬鼠標點擊,還有其他選擇嗎?

+0

只要窗口有一個父窗口,或者是一個擁有的窗口,那麼你可以[使用這個](http://stackoverflow.com/a/7692496/17034)。 –

+0

你好,感謝您的鏈接,這對我來說很有用。不過,我的窗戶不屬於另一個窗戶。這是根源,我需要點擊才能通過它並擊中其他應用程序或其下的桌面。 – Footch

回答

3

重點是使用Color.Magenta作爲TrancparecyKeyBackColor您的窗體。 然後使按鈕不可見,並模擬點擊事件,然後再次使按鈕可見。

這裏是一個示例,當您單擊按鈕時,它將使表單透明,然後模擬單擊以通過表單。

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] 
public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint cButtons, uint dwExtraInfo); 

private const int MOUSEEVENTF_LEFTDOWN = 0x02; 
private const int MOUSEEVENTF_LEFTUP = 0x04; 

public void PerformClick() 
{ 
    uint X = (uint)Cursor.Position.X; 
    uint Y = (uint)Cursor.Position.Y; 
    mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, X, Y, 0, 0); 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    //Just to keep the form on top 
    this.TopMost = true; 

    //Make form transparent and click through 
    this.TransparencyKey = Color.Magenta; 
    this.BackColor = Color.Magenta; 

    //Make the button invisible and perform a click 
    //The click reaches behind the button 
    //Then make button visible again to be able handle clicks again 
    this.button4.Visible = false; 
    PerformClick(); 
    this.button4.Visible = true; 
} 

注意

製造透明和點擊
爲了使形式透明,並點擊通過的形式,你可以簡單地設置您的形式向TrancparecyKey財產和BackColor財產Color.Magenta

請注意,關鍵是使用洋紅色作爲TrancparecyKeyBackColor。例如,如果您使用紅色,它會使表單透明,但不會使其點擊。

如果您的表單上有一些控件,它們將保持可見狀態,並且會收到點擊。如果你需要讓他們看不見,你可以將它們的Visible屬性只是設置爲false

進行正常
要作出這樣的形式正常的,這是不夠的設定BackColorTrancparecyKey不同的另一種顏色,例如SystemColors.Control

+0

謝謝。我已經使用另一種顏色的TransparencyKey來使表單透明,但是這不會讓我的點擊穿過窗口。執行按鈕點擊不會模擬應用程序窗口下方的點擊,因此我也無法使用它。 – Footch

+0

關鍵在於將洋紅色作爲顏色使用,例如,紅色使您的窗體透明但不通過,但洋紅色使其透明且點擊通過。 –

+0

我測試解決方案,它在這裏正常工作:) –