2010-04-12 128 views

回答

5

對於純粹管理的解決方案,下面的代碼將在當前鼠標光標位置的桌面上繪製一個橢圓。

Point pt = Cursor.Position; // Get the mouse cursor in screen coordinates 

using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) 
{   
    g.DrawEllipse(Pens.Black, pt.X - 10, pt.Y - 10, 20, 20); 
} 

通過使用計時器,您可以每隔20ms更新一次鼠標位置並繪製新的hallow(橢圓)。

還有其他更有效的方法,我可以想到,但他們需要使用系統掛鉤unamanged代碼。看看SetWindowsHookEx瞭解更多信息。

更新:這裏是我在我的評論中描述的解決方案的示例,這只是粗略的,可用於測試目的。

public partial class Form1 : Form 
    { 
    private HalloForm _hallo; 
    private Timer _timer; 

    public Form1() 
    { 
     InitializeComponent(); 
     _hallo = new HalloForm(); 
     _timer = new Timer() { Interval = 20, Enabled = true }; 
     _timer.Tick += new EventHandler(Timer_Tick); 
    } 

    void Timer_Tick(object sender, EventArgs e) 
    { 
     Point pt = Cursor.Position; 
     pt.Offset(-(_hallo.Width/2), -(_hallo.Height/2)); 
     _hallo.Location = pt; 

     if (!_hallo.Visible) 
     { 
     _hallo.Show(); 
     } 
    }  
    } 

    public class HalloForm : Form 
    {   
    public HalloForm() 
    { 
     TopMost = true; 
     ShowInTaskbar = false; 
     FormBorderStyle = FormBorderStyle.None; 
     BackColor = Color.LightGreen; 
     TransparencyKey = Color.LightGreen; 
     Width = 100; 
     Height = 100; 

     Paint += new PaintEventHandler(HalloForm_Paint); 
    } 

    void HalloForm_Paint(object sender, PaintEventArgs e) 
    {  
     e.Graphics.DrawEllipse(Pens.Black, (Width - 25)/2, (Height - 25)/2, 25, 25); 
    } 
    } 
+0

感謝克里斯,我設法使用鉤子和Graphics.FromHwnd繪製一個半透明的光環。但是,我無法清除先前繪製的圓。 InvalidateRect似乎無法正確使用IntPtr.Zero或GetDesktopWindow。有任何想法嗎? – SharpAffair 2010-04-12 21:23:58

+0

嗨,約翰,所以我在想你恢復桌面的問題,我有以下想法。正如我最初所建議的,不是直接在桌面上繪圖,而是爲什麼現在要使用表單。所以創建一個新的Form,Hallow Form,設置FormBorderStyle = None,BackColor = LightGreen,TransparencyKey = LightGreen,TopMost = true,ShowInTaskBar = false,Width = 100,Height = 100。這會給你一個不顯示的窗體,但是你在PaintEvent窗體上繪製的任何東西都會顯示出來。然後在初始答案的計時器事件中更新窗口位置以跟蹤鼠標。從快速測試看起來很好。 – 2010-04-13 07:21:54

+0

我能想到的唯一明顯問題是,另一個窗口可能在窗口之後最高,在這種情況下,這個窗口不會顯示在窗口之上。 – 2010-04-13 07:24:16