473,651 Members | 2,582 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Time Tick consumes 100% CPU

Hi,

I am using the following code to the update a section of the image
which is drawn on a panel.
this.m_Timer = new System.Windows. Forms.Timer(thi s.components);
this.m_Timer.Ti ck += new System.EventHan dler(this.m_Tim er_Tick);
this.m_Timer.En albled = true;

private void m_Timer_Tick(ob ject sender, System.EventArg s e)
{
RepaintMagnifie r();
}

private void RepaintMagnifie r()
{
Graphics g = this.pnlBody.Cr eateGraphics();
g.SmoothingMode = System.Drawing. Drawing2D.Smoot hingMode.HighQu ality;
g.Interpolation Mode =
System.Drawing. Drawing2D.Inter polationMode.Hi ghQualityBicubi c;
g.PixelOffsetMo de =
System.Drawing. Drawing2D.Pixel OffsetMode.High Quality;

if(img != null)
g.DrawImage(img , new Rectangle(0, 0, this.pnlBody.Wi dth,
this.pnlBody.He ight), new
Rectangle(iXpos ,iYpos,(int)(th is.pnlBody.Widt h*((float)this. iZoomFactor/100)),(int)(thi s.pnlBody.Heigh t*((float)this. iZoomFactor/100))),
GraphicsUnit.Pi xel);
}

The image file size is around 0.5 MB which is being drawn on the panel
control.

Above code is taking 100% CPU cycle.

I am using the above approach for repainting the screen to avoid the
flickering.

It there any other way to perform this action or should i use the a
secondary thread instead of timer to repaint the screen.
Thanks,
Utkarsh

Nov 17 '05 #1
7 5934
I am not good at graphics but once done, you should Dispose "g"

HTH
Kalpesh

Nov 17 '05 #2
How often does the time fire?

Normally, to prevent flickering when repainting, you would set your
forms so they use double buffering.

Check this specific article:

http://www.bobpowell.net/doublebuffer.htm

Also check out all the articles on his site, they're very good:

http://www.bobpowell.net
good luck

Nov 17 '05 #3
Hi utkarsh,
if you want to avoid flickering and you are using a panel to display an
image I would override the OnPaintBackgrou nd method to do nothing - to reduce
flickering caused by painting the background, then override the OnPaint
method to paint a bitmap image you have stored internally in the panel, on
the paint method don't do anything apart from painting. you would then have
another method you woud call to update the image properties outside of the on
paint method. Something like:
private Image _bufferedImage;
private int _x = 0;
private int _y = 0;
private float _scaleFactor = 1.0f;

//You call this explicitly to update the buffered image
public void ReDraw()
{
//assume there is another method like LoadImage which will
load
//an image into the _bufferedImage member variable
Graphics g = Graphics.FromIm age(_bufferedIm age);

GraphicsContain er gcOrig = g.BeginContaine r();

//do some processing, i.e. change x and y and scale
//of the image
g.TranslateTran sform(_x, _y);
g.ScaleTransfor m(_scaleFactor, _scaleFactor);
g.DrawImage(_im age,5,5);

g.EndContainer( gcOrig);
this.Refresh();
}

protected override void OnPaint(PaintEv entArgs e)
{
//simply paint your buffered image to the control - do not
do any
//processing
if(_bufferedIma ge != null)
{
e.Graphics.Draw Image(_buffered Image, 0 ,0);
}
}

protected override void OnPaintBackgrou nd(PaintEventAr gs pevent)
{
//do nothing here so that image does not have to repaint the background
}

Hope that helps
Mark R Dawson
http://www.markdawson.org

"utkarsh" wrote:
Hi,

I am using the following code to the update a section of the image
which is drawn on a panel.
this.m_Timer = new System.Windows. Forms.Timer(thi s.components);
this.m_Timer.Ti ck += new System.EventHan dler(this.m_Tim er_Tick);
this.m_Timer.En albled = true;

private void m_Timer_Tick(ob ject sender, System.EventArg s e)
{
RepaintMagnifie r();
}

private void RepaintMagnifie r()
{
Graphics g = this.pnlBody.Cr eateGraphics();
g.SmoothingMode = System.Drawing. Drawing2D.Smoot hingMode.HighQu ality;
g.Interpolation Mode =
System.Drawing. Drawing2D.Inter polationMode.Hi ghQualityBicubi c;
g.PixelOffsetMo de =
System.Drawing. Drawing2D.Pixel OffsetMode.High Quality;

if(img != null)
g.DrawImage(img , new Rectangle(0, 0, this.pnlBody.Wi dth,
this.pnlBody.He ight), new
Rectangle(iXpos ,iYpos,(int)(th is.pnlBody.Widt h*((float)this. iZoomFactor/100)),(int)(thi s.pnlBody.Heigh t*((float)this. iZoomFactor/100))),
GraphicsUnit.Pi xel);
}

The image file size is around 0.5 MB which is being drawn on the panel
control.

Above code is taking 100% CPU cycle.

I am using the above approach for repainting the screen to avoid the
flickering.

It there any other way to perform this action or should i use the a
secondary thread instead of timer to repaint the screen.
Thanks,
Utkarsh

Nov 17 '05 #4
Thanks Mark for your code and so much help!! :)

But my problem is little bit different.
I have two screen left and right. In left panel I have loaded a Image
in picture box. When user move the mouse on the left panel, a
maginified view of a image section, near by the cursor, should be
visible in the right panel.

I have to do the similar work like the windows magnifier ( Programs ->
Accessories -> Accessibility -> Magnifier)

So I have loaded the same image in both the screens and I have to
update the right screen as mouse move in left. I have removed the
flickering by using the timer tick event. But only problem left is,
timer is consuming the 100% CPU.

Thanks again,
Utkarsh Panwar

Nov 17 '05 #5
Hi Utkarsh,
I made a little app that mimics the magnifier behaviour you talked about,
with an image on the left and a magnified version on the right. I loaded a
3MB file and it seems to take about 50% of the CPU on my home computer when I
move the mouse very rapidly, but with no flickering.

I have 3 files:
1. ZoomSelectorPic tureBox.cs -> displays an image with a red rectangle
around the mouse indicating where the zoomed in portion of the image will be
displayed. This inherits from PictureBox (although it doesn't really need to)

2. ZoomMagnifierPi ctureBox which shows a zoomed in version of the selected
region in ZoomSelectorPic tureBox, this also inherits from picturebox

3. Form1.cs -> creates instances of the above classes. you will need to
modify the Form1_Load method to load an image on your computer.

I have pasted all three files below, but the formatting will be messed up in
these windows. If you like you can download the entire source from
http://www.markdawson.org/software/csharp/magnifier.zip which may be easier
than getting the text code out from below.
//FORM1.cs

using System;
using System.Drawing;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;
using System.Data;

namespace WindowsApplicat ion4
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows. Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;

public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeCompo nent();

//
// TODO: Add any constructor code after InitializeCompo nent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Disp ose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
//
// Form1
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
this.ClientSize = new System.Drawing. Size(800, 469);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHan dler(this.Form1 _Load);

}
#endregion

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run (new Form1());
}

private void Form1_Load(obje ct sender, System.EventArg s e)
{
ZoomSelectorPic tureBox selectorPicture Box = new ZoomSelectorPic tureBox();
selectorPicture Box.Image = Image.FromFile( @"c:\test.bmp") ;

this.Controls.A dd(selectorPict ureBox);
selectorPicture Box.Left = 0;
selectorPicture Box.Top = 0;
selectorPicture Box.Width = 400;
selectorPicture Box.Height = 400;

ZoomMagnifierPi ctureBox zoomMagnifier = new
ZoomMagnifierPi ctureBox(select orPictureBox);
this.Controls.A dd(zoomMagnifie r);
zoomMagnifier.L eft = 400;
zoomMagnifier.T op = 0;
zoomMagnifier.W idth = 400;
zoomMagnifier.H eight = 400;
}
}
}



//ZoomMagnifierPi ctureBox.cs

using System;
using System.Windows. Forms;
using System.Drawing;

namespace WindowsApplicat ion4
{
public class ZoomMagnifierPi ctureBox : PictureBox
{
private Rectangle _zoomRegion;
private Image _originalImage;

public ZoomMagnifierPi ctureBox(ZoomSe lectorPictureBo x zoomSelector) : base()
{
_originalImage = zoomSelector.Im age;
zoomSelector.Zo omRectangleChan ged += new
WindowsApplicat ion4.ZoomSelect orPictureBox.Zo omRectangleLoca tionChangedEven tHandler(zoomSe lector_ZoomRect angleChanged);
}

protected override void OnPaintBackgrou nd(PaintEventAr gs pevent)
{
//base.OnPaintBac kground (pevent);
}

protected override void OnPaint(PaintEv entArgs e)
{
//base.OnPaint (e);
e.Graphics.Draw Image(_original Image, new Rectangle(0,0, this.Width,
this.Height), _zoomRegion.X, _zoomRegion.Y, _zoomRegion.Wid th,
_zoomRegion.Hei ght, GraphicsUnit.Pi xel);
}

private void zoomSelector_Zo omRectangleChan ged(Rectangle zoomRectangle)
{
_zoomRegion = zoomRectangle;
this.Refresh();
}
}
}


//ZoomSelectorPic tureBox.cs

using System;
using System.Windows. Forms;
using System.Drawing;

namespace WindowsApplicat ion4
{
public class ZoomSelectorPic tureBox : PictureBox
{
private Rectangle _zoomRegion;
private bool _mouseIsOver = false;

public delegate void ZoomRectangleLo cationChangedEv entHandler(Rect angle
zoomRectangle);
public event ZoomRectangleLo cationChangedEv entHandler ZoomRectangleCh anged;

public ZoomSelectorPic tureBox() : base()
{
//create zoom region rectangle
_zoomRegion = new Rectangle(0, 0, 50, 50);

//set up event handlers
this.MouseMove += new MouseEventHandl er(ZoomSelector PictureBox_Mous eMove);
this.MouseLeave += new EventHandler(Zo omSelectorPictu reBox_MouseLeav e);
this.MouseEnter += new EventHandler(Zo omSelectorPictu reBox_MouseEnte r);
}

protected override void OnPaintBackgrou nd(PaintEventAr gs pevent)
{
//base.OnPaintBac kground (pevent);
}

protected override void OnPaint(PaintEv entArgs e)
{
base.OnPaint (e);

//only do this if the mouse is over the control
if(_mouseIsOver )
{
using(Pen p = new Pen(Color.Red, 5))
{
e.Graphics.Draw Rectangle(p, _zoomRegion);
}
}
}

private void ZoomSelectorPic tureBox_MouseMo ve(object sender,
MouseEventArgs e)
{
//make the mouse in the center of the zoom region
_zoomRegion.X = e.X - _zoomRegion.Wid th / 2;
_zoomRegion.Y = e.Y - _zoomRegion.Wid th / 2;

//raise the event to listeners to refresh their
//zoomed view
if(ZoomRectangl eChanged != null)
{
ZoomRectangleCh anged(_zoomRegi on);
}

//force image to be redrawn
this.Refresh();
}

private void ZoomSelectorPic tureBox_MouseLe ave(object sender, EventArgs e)
{
_mouseIsOver = false;

//force image to redraw without the rectangle
this.Refresh();
}

private void ZoomSelectorPic tureBox_MouseEn ter(object sender, EventArgs e)
{
_mouseIsOver = true;
}
}
}
Hope that helps
Mark R Dawson
http://www.markdawson.org


"utkarsh" wrote:
Thanks Mark for your code and so much help!! :)

But my problem is little bit different.
I have two screen left and right. In left panel I have loaded a Image
in picture box. When user move the mouse on the left panel, a
maginified view of a image section, near by the cursor, should be
visible in the right panel.

I have to do the similar work like the windows magnifier ( Programs ->
Accessories -> Accessibility -> Magnifier)

So I have loaded the same image in both the screens and I have to
update the right screen as mouse move in left. I have removed the
flickering by using the timer tick event. But only problem left is,
timer is consuming the 100% CPU.

Thanks again,
Utkarsh Panwar

Nov 17 '05 #6
A timer is really not a good idea, take Marks advice on the
OnPaintBackgrou nd and OnPaint methods and add an OnMouseMove event
handler to the left panel. In that handler add something like
rightPanel.Inva lidate(). This will force the right panel to be repainted
when the mouse moves over the left panel.

Nick Z.

utkarsh wrote:
Thanks Mark for your code and so much help!! :)

But my problem is little bit different.
I have two screen left and right. In left panel I have loaded a Image
in picture box. When user move the mouse on the left panel, a
maginified view of a image section, near by the cursor, should be
visible in the right panel.

I have to do the similar work like the windows magnifier ( Programs ->
Accessories -> Accessibility -> Magnifier)

So I have loaded the same image in both the screens and I have to
update the right screen as mouse move in left. I have removed the
flickering by using the timer tick event. But only problem left is,
timer is consuming the 100% CPU.

Thanks again,
Utkarsh Panwar

Nov 17 '05 #7
Thank you very much Mark for such a great help !!!

:)

I looked at the code it is perfectly fine. CPU goes high till 50%, if
mouse movement is faster. But there is absolutly no flickering.
Thanks Again,
Utkarsh Panwar

Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
4378
by: Christine | last post by:
I've implemented a countdown timer for a tutorial web page that should give the user 45 minutes to complete the test, only to find that the timer is slowly 'losing' time. On average, it actually takes an extra 35 seconds, but has taken an extra 2.5 minutes in some cases. Any ideas what might be the cause? And more importantly - the fix? Code snippet below... Thanks, Christine
9
7265
by: HL | last post by:
I am using VS 2005 Beta - C# Problem: The Timer fires a few milliseconds before the actual Due-Time Let's say a timer is created in the following manner: System.Threading.Timer m_timer = null; Let's declare a constant Int32 m_TimePeriod = 10000;
3
3858
by: Steve | last post by:
I used the QueryPerformanceCounter and QueryPerformanceFrequency methods in my VC++ 6.0 projects to measure correct time spans, for example for timeouts, how much time takes to execute certain method etc I wonder whether there is something similar in .NET to measure time spans? Meantime I still use these methods through DllImport private static extern bool QueryPerformanceFrequency(out long lpFrequency);
6
4693
by: Rich | last post by:
Hello, I have a label in my app where I display time from a Timer contol like this: Private Sub Timer1_Tick(...) Handles Timer1.Tick lbl_Time.Text = TimeOfDay.ToString End Sub The display is 1/1/0001 10:00:01 AM
8
1347
by: Dean | last post by:
Hi, I am using Vb.net and I want to know how to put the Time, Date which ticks?? Please reply as soon as possible Dean PS: Please make the answer simple because I am only 11 Yrs old and New to VB
3
1709
by: Tim_Mac | last post by:
hi, i'm generating PDF files from crystal reports in my .Net 1.1 web site, and saving them to disk for the user to download in their own time. the format i'm currently using is: FileName_<DateTime.Now.Ticks>.PDF there is a relatively low level of concurrent users on this site, but i am a little concerned that two requests could happen within the same tick, resulting in a filename clash and overwrite. is this possible? the docs say...
0
3274
hqprog
by: hqprog | last post by:
Having search extensively I've learned the two functions timegm and gmtime_r though in the GNU standard C library extend the ISO standard. I need to use these two functions in myprog.c (on pc - see *** in code snippet below) which processes a large csv file into smaller csv files based on time (GMT, UTC). myprog.c was run on MAC OSX and but won't compile for me. Probably these two functions were defined in the time.h that was used. But...
3
1505
w33nie
by: w33nie | last post by:
I'd like to put a clock on my web site, that shows the time where I am, not where the user is. I found a regular clock with google, that shows the time of the user's system clock, so I thought it might be able to be tweaked to show the time where I am. I live in the UK at the moment, so right now we're on UTC+1. But I travel around a fair bit, so I was wondering if i'd be able to have the time zone it is displaying coded in PHP, & therefore...
11
5579
by: xenoix | last post by:
hey there, im reasonably new to C# and im currently writing a backup application which im using as a learning resource. My PC :- Visual Studio 2005 .NET Framework 2 Component Factory Krypton Tools Test PC :- .Net Framework 2
0
8275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8792
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8457
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7294
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6157
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4143
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4280
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2696
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1585
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.