Search code examples
c#gdi

make GDI drawing more efficient C#


At the moment my code takes about 10% of my CPUs power. How can I make it more efficient and less flickerish? Code:

private void timer1_Tick(object sender, EventArgs e)
{
    DrawLocal();
    Thread.Sleep(17);
    pictureBox1.Invalidate();
}

private void DrawLocal()
{
    int localReadX = ReadAddress("hl2", "client.dll+0xBFFF00 364 0");
    int localReadY = ReadAddress("hl2", "client.dll+0xBFFF00 368 0");

    byte[] bytesOflocalX = BitConverter.GetBytes(localReadX);//converts to float
    byte[] bytesOflocalY = BitConverter.GetBytes(localReadY);//converts to float

    float localX = BitConverter.ToSingle(bytesOflocalX, 0)/10;//converts to float
    float localY = BitConverter.ToSingle(bytesOflocalY, 0)/10;//converts to float

    Graphics localP = pictureBox1.CreateGraphics();
    localP.FillRectangle(new SolidBrush(Color.Red), localX, localY, 5, 5);

    Graphics localName = pictureBox1.CreateGraphics();
    localName.DrawString("  local", new Font("Arial", 7), new SolidBrush(Color.Red), localX, localY);
}

Solution

  • The comments above, demonstrated below:

        private Font f = new Font("Arial", 7);
    
        public Form1()
        {
            InitializeComponent();
            pictureBox1.Paint += pictureBox1_Paint;
        }
    
        private void timer1_Tick(object sender, EventArgs e)
        {
            pictureBox1.Invalidate();
        }
    
        void pictureBox1_Paint(object sender, PaintEventArgs e)
        {
            int localReadX = ReadAddress("hl2", "client.dll+0xBFFF00 364 0");
            int localReadY = ReadAddress("hl2", "client.dll+0xBFFF00 368 0");
    
            byte[] bytesOflocalX = BitConverter.GetBytes(localReadX);//converts to float
            byte[] bytesOflocalY = BitConverter.GetBytes(localReadY);//converts to float
    
            float localX = BitConverter.ToSingle(bytesOflocalX, 0) / 10;//converts to float
            float localY = BitConverter.ToSingle(bytesOflocalY, 0) / 10;//converts to float
    
            e.Graphics.FillRectangle(Brushes.Red, localX, localY, 5, 5);
            e.Graphics.DrawString("  local", f, Brushes.Red, localX, localY);
        }