日期:2014-05-18  浏览次数:21054 次

怎样清除 Graphics 在桌面显示的内容。
运行下面代码后桌面一真有文字,一直到关闭程序,有没方法可以清除掉。

其中有一个 “g.Dispose();”和“g.Clear();”但不知道怎么用。希望高手帮帮忙。谢谢


  [DllImport("user32.dll", CharSet = CharSet.Auto)]
  public static extern IntPtr GetDC(IntPtr hWnd);
  IntPtr hdc = GetDC(IntPtr.Zero);
  public Form1()
  {
  string show = "显示这行字符在桌面";
  InitializeComponent();
  Graphics g = Graphics.FromHdc(hdc);
  g.DrawString(show, new Font("宋体 ", 36), new SolidBrush(Color.Red), new Point(430, 330));  
  }


------解决方案--------------------
顯示 背景顏色的話 , 在 new SolidBrush(Color.Red) Color. 里面改不就可以了?
楼主说的清除是什么意思?
------解决方案--------------------
如果 LZ 想用g.Clear(); 这方法 清除 。。
感觉 有点 。。
需要的话就
C# code
g.Clear(Color.White);

------解决方案--------------------
桌面么?
那你一定得到桌面的句柄了。
C# code
[DllImport("user32.dll", EntryPoint="InvalidateRect")]
public static extern int InvalidateRect (
    IntPtr hwnd,
    Rectangle lpRect,
    bool bErase
);
[DllImport("user32.dll", EntryPoint="GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow ();

//调用
InvalidateRect(GetDesktopWindow(),System.Windows.Forms.Screen.PrimaryScreen.Bounds,true);

------解决方案--------------------
重绘桌面:
C# code
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern IntPtr GetDesktopWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool RedrawWindow(IntPtr hwnd, RECT rcUpdate, IntPtr hrgnUpdate, int flags);

RedrawWindow(GetDesktopWindow(), null, IntPtr.Zero, 0x85);


------解决方案--------------------
新建控制台程序。粘贴:
C# code

[DllImport("user32.dll", EntryPoint = "InvalidateRect")]
public static extern int InvalidateRect(
    IntPtr hwnd,
    IntPtr lpRect,
    bool bErase
);
[DllImport("user32.dll", EntryPoint = "GetDesktopWindow")]
public static extern IntPtr GetDesktopWindow();

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
public static extern bool RedrawWindow(IntPtr hwnd, ref Rectangle rcUpdate, IntPtr hrgnUpdate, int flags);



static void Main(string[] args)
{
    Thread.Sleep(2000);
    Console.WriteLine("现在开始绘制屏幕");
    Graphics g = Graphics.FromHwnd(IntPtr.Zero);
    g.DrawLine(Pens.Yellow, new Point(0, 0), new Point(500, 800));
    g.Dispose(); 
    Thread.Sleep(2000);
    Console.WriteLine("现在开始清除屏幕");
    Rectangle rect = Screen.PrimaryScreen.Bounds;
    RedrawWindow(GetDesktopWindow(), ref rect, IntPtr.Zero, 0x85);
    Console.ReadKey();
}