Search Results

Search found 312 results on 13 pages for 'invalidate'.

Page 3/13 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • NHibernate second-level cache with external updates.

    - by SztupY
    I've got a web application that is 99% read-only, with a separate service that updates the database at specific intervals (like every 10 minutes). How can this service tell the application to invalidate it's second-level cache? Is it actually important? (I don't actually care if I have too much stale data) If I don't invalidate the cache how much time is needed to the records to get updated (if using SysCache)

    Read the article

  • How do I update blackberry UI items from a thread?

    - by Andrei T. Ursan
    public class PlayText extends Thread { private int duration; private String text; private PlayerScreen playerscrn; public PlayText(String text, int duration) { this.duration = duration; this.text = text; this.playerscrn = (PlayerScreen)UiApplication.getUiApplication().getActiveScreen(); } public void run() { synchronized(UiApplication.getEventLock()) { try{ RichTextField text1player = new RichTextField(this.text, Field.NON_FOCUSABLE); playerscrn.add(text1player); playerscrn.invalidate(); Thread.sleep(this.duration); RichTextField text2player = new RichTextField("hahhaha", Field.NON_FOCUSABLE); playerscrn.add(text2player); playerscrn.invalidate(); Thread.sleep(1000); RichTextField text3player = new RichTextField("Done", Field.NON_FOCUSABLE); playerscrn.add(text3player); playerscrn.invalidate(); }catch(Exception e){ System.out.println("I HAVE AN ERROR"); } } } } With the above code I'm trying to create a small text player. Instead to get all the text labels one by one, something like display text1player wait this.duration milliseconds display text2player wait 1000 milliseconds display text3player thread done. The screens waits this.duration + 1000 milliseconds and displays all the labels at once. I tried with a runnable and calling .invokeLater or .invokeAndWait but I still get the same behavior, and even if I get dirty like above using synchronized it still doesn't work. Does anyone know how I can display each label at a time? Thank you!

    Read the article

  • iPhone NSTimer OpenGL problem

    - by Toby Wilson
    I've got a problem that only seems to occur on the device, not in the simulator. My app's animation is started and stopped using these methods: NSTimer* animationTimer; -(void)startAnimation { if(animationTimer = nil) animationTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(drawView) userInfo:nil repeats:YES]; } -(void)stopAnimation { [animationTimer invalidate]; animationTimer = nil; } In the simulator this works fine and drawView starts being called at 60fps. On the device (testing on iPod Touch), the scheduleTimerWithTimeInterval method doesn't seem to work. Furthermore, [animationTimer invalidate] causes EXC_BAD_ACCESS. I've spotted an obvious but minor flaw; adding if(animationTimer != nil) to the stopAnimation method will prevent the crash, but doesn't solve the problem of the animation timer not being properly initialised. Edit: The above doesn't prevent a crash. animationTimer != nil yet calling invalidate causes EXC_BAD_ACCESS. Should also add, this problem doesn't occur all the time on the device. Maybe 40% of the time.

    Read the article

  • NSTimer as a timeout mechanism

    - by alexantd
    I'm pretty sure this is really simple, and I'm just missing something obvious. I have an app that needs to download data from a web service for display in a UITableView, and I want to display a UIAlertView if the operation takes more than X seconds to complete. So this is what I've got (simplified for brevity): MyViewController.h @interface MyViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> { NSTimer *timer; } @property (nonatomic, retain) NSTimer *timer; MyViewController.m @implementation MyViewController @synthesize timer; - (void)viewDidLoad { timer = [NSTimer scheduledTimerWithTimeInterval:20 target:self selector:@selector(initializationTimedOut:) userInfo:nil repeats:NO]; [self doSomethingThatTakesALongTime]; [timer invalidate]; } - (void)doSomethingThatTakesALongTime { sleep(30); // for testing only // web service calls etc. go here } - (void)initializationTimedOut:(NSTimer *)theTimer { // show the alert view } My problem is that I'm expecting the [self doSomethingThatTakesALongTime] call to block while the timer keeps counting, and I'm thinking that if it finishes before the timer is done counting down, it will return control of the thread to viewDidLoad where [timer invalidate] will proceed to cancel the timer. Obviously my understanding of how timers/threads work is flawed here because the way the code is written, the timer never goes off. However, if I remove the [timer invalidate], it does.

    Read the article

  • Migration a database from 32bit to 64bit

    - by Mike Dietrich
    Database migrations from an 32bit environment to an 64bit environment keeping the same platform architecture (e.g. moving an Oracle 10.2.0.5 database from MS Windows XP 32bit to MS Windows Server 2003 64bit) does not happen that often anymore. But still we see them getting done. And there are a few things to note when doing such a move. First of all the important question is:Will you upgrade your database as part of this move - Yes or No? If you say "Yes" then you are almost done with that topic as we will take care of that bitnes move during the upgrade. The only thing you have to take care is OLAP in case you are using OLAP Option with Analytic Workspaces (AW) by yourself. Those store data in Binary LOBs - and in order to move AWs from 32bit to 64bit you have to export your AWs prior to the move - and import them later on. People who don't use OLAP don't have to take care on this. But if you say "No" (meaning: no upgrade actions involved - you keep your database version) then you have to make sure to invalidate all packages and stored code in the database before you shutdown your database in the 32bit environment and prior to moving it over. And the same rule as above for OLAP applies once you use the OLAP Option. In the source environment: startup upgrade;    -- [or startup migrate; -- for Oracle 9i] @?/rdbms/admin/utlirp.sqlshutdown immediate In the destination environment: startup upgrade @?/olap/admin/xumuts.plb --Only if OLAP Option is installed@?/rdbms/admin/utlrp.sql The script utlirp.sql will invalidate all packages and stored code, utlrp.sql will recompile - and xumuts.plb will rebuild the OLAP Analytic Workspaces in case you have the OLAP Option installed.

    Read the article

  • Is it feasible and useful to auto-generate some code of unit tests?

    - by skiwi
    Earlier today I have come up with an idea, based upon a particular real use case, which I would want to have checked for feasability and usefulness. This question will feature a fair chunk of Java code, but can be applied to all languages running inside a VM, and maybe even outside. While there is real code, it uses nothing language-specific, so please read it mostly as pseudo code. The idea Make unit testing less cumbersome by adding in some ways to autogenerate code based on human interaction with the codebase. I understand this goes against the principle of TDD, but I don't think anyone ever proved that doing TDD is better over first creating code and then immediatly therafter the tests. This may even be adapted to be fit into TDD, but that is not my current goal. To show how it is intended to be used, I'll copy one of my classes here, for which I need to make unit tests. public class PutMonsterOnFieldAction implements PlayerAction { private final int handCardIndex; private final int fieldMonsterIndex; public PutMonsterOnFieldAction(final int handCardIndex, final int fieldMonsterIndex) { this.handCardIndex = Arguments.requirePositiveOrZero(handCardIndex, "handCardIndex"); this.fieldMonsterIndex = Arguments.requirePositiveOrZero(fieldMonsterIndex, "fieldCardIndex"); } @Override public boolean isActionAllowed(final Player player) { Objects.requireNonNull(player, "player"); Hand hand = player.getHand(); Field field = player.getField(); if (handCardIndex >= hand.getCapacity()) { return false; } if (fieldMonsterIndex >= field.getMonsterCapacity()) { return false; } if (field.hasMonster(fieldMonsterIndex)) { return false; } if (!(hand.get(handCardIndex) instanceof MonsterCard)) { return false; } return true; } @Override public void performAction(final Player player) { Objects.requireNonNull(player); if (!isActionAllowed(player)) { throw new PlayerActionNotAllowedException(); } Hand hand = player.getHand(); Field field = player.getField(); field.setMonster(fieldMonsterIndex, (MonsterCard)hand.play(handCardIndex)); } } We can observe the need for the following tests: Constructor test with valid input Constructor test with invalid inputs isActionAllowed test with valid input isActionAllowed test with invalid inputs performAction test with valid input performAction test with invalid inputs My idea mainly focuses on the isActionAllowed test with invalid inputs. Writing these tests is not fun, you need to ensure a number of conditions and you check whether it really returns false, this can be extended to performAction, where an exception needs to be thrown in that case. The goal of my idea is to generate those tests, by indicating (through GUI of IDE hopefully) that you want to generate tests based on a specific branch. The implementation by example User clicks on "Generate code for branch if (handCardIndex >= hand.getCapacity())". Now the tool needs to find a case where that holds. (I haven't added the relevant code as that may clutter the post ultimately) To invalidate the branch, the tool needs to find a handCardIndex and hand.getCapacity() such that the condition >= holds. It needs to construct a Player with a Hand that has a capacity of at least 1. It notices that the capacity private int of Hand needs to be at least 1. It searches for ways to set it to 1. Fortunately it finds a constructor that takes the capacity as an argument. It uses 1 for this. Some more work needs to be done to succesfully construct a Player instance, involving the creation of objects that have constraints that can be seen by inspecting the source code. It has found the hand with the least capacity possible and is able to construct it. Now to invalidate the test it will need to set handCardIndex = 1. It constructs the test and asserts it to be false (the returned value of the branch) What does the tool need to work? In order to function properly, it will need the ability to scan through all source code (including JDK code) to figure out all constraints. Optionally this could be done through the javadoc, but that is not always used to indicate all constraints. It could also do some trial and error, but it pretty much stops if you cannot attach source code to compiled classes. Then it needs some basic knowledge of what the primitive types are, including arrays. And it needs to be able to construct some form of "modification trees". The tool knows that it needs to change a certain variable to a different value in order to get the correct testcase. Hence it will need to list all possible ways to change it, without using reflection obviously. What this tool will not replace is the need to create tailored unit tests that tests all kinds of conditions when a certain method actually works. It is purely to be used to test methods when they invalidate constraints. My questions: Is creating such a tool feasible? Would it ever work, or are there some obvious problems? Would such a tool be useful? Is it even useful to automatically generate these testcases at all? Could it be extended to do even more useful things? Does, by chance, such a project already exist and would I be reinventing the wheel? If not proven useful, but still possible to make such thing, I will still consider it for fun. If it's considered useful, then I might make an open source project for it depending on the time. For people searching more background information about the used Player and Hand classes in my example, please refer to this repository. At the time of writing the PutMonsterOnFieldAction has not been uploaded to the repo yet, but this will be done once I'm done with the unit tests.

    Read the article

  • Scrollbar still is painted after it should be removed

    - by Walter Williams
    I have the following custom control and can place on a form (with AutoScroll set to true and the control anchored left, top and right). If the form is too short for the control, the form correctly resizes the control (to make room for the scroll) and displays the scroll bar. When the control is closed using the close glyph, the control is resized and the scroll bar is removed, but occasionally the scroll bar appears to remain painted. If the form is minimized or moved off-screen, the leftover paint is removed. I've tried Parent.Invalidate and have toyed with it in many ways but to no avail. Any suggestions? (Using VS 2008 Standard) using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace GroupPanelTest { public class GroupPanel : GroupBox { #region Members private const Int32 iHeaderHeight = 20; private Int32 iFullHeight = 200; private Boolean bClosed = false; private Rectangle rectCloseGlyphBounds = Rectangle.Empty; private Boolean bIsMoveOverCloseGlyph = false; #endregion #region Properties [DefaultValue(false)] public Boolean Closed { get { return (this.bClosed); } set { if (this.bClosed != value) { this.bClosed = value; if (this.bClosed) { this.iFullHeight = base.Height; base.Height = GroupPanel.iHeaderHeight; } else { base.Height = this.iFullHeight; } foreach (Control con in base.Controls) con.Visible = !this.bClosed; this.Invalidate(); } } } public new Int32 Height { get { return (base.Height); } set { if (value != base.Height) { if (this.Closed) { this.iFullHeight = value; } else { Int32 iOldHeight = base.Height; base.Height = value; } } } } [DefaultValue(typeof(Size), "350,200")] public new Size Size { get { return (base.Size); } set { if (base.Size != value) { base.Size = value; if (!this.Closed) this.iFullHeight = value.Height; } } } [DefaultValue(typeof(Padding), "0,7,0,0")] public new Padding Padding { get { return (base.Padding); } set { base.Padding = value; } } #endregion #region Construction public GroupPanel () { SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.Selectable, true); this.Size = new Size(350, 200); this.Padding = new Padding(0, 7, 0, 0); // the groupbox will add to that this.rectCloseGlyphBounds = new Rectangle(base.ClientSize.Width - 24, 2, 16, 16); } #endregion #region Overrides protected override void OnSizeChanged (EventArgs e) { this.rectCloseGlyphBounds = new Rectangle(base.ClientSize.Width - 24, 2, 16, 16); base.OnSizeChanged(e); } protected override void OnPaint (PaintEventArgs e) { base.OnPaint(e); // we want all the delegates to receive the events, but we do this first so we can paint over it Graphics g = e.Graphics; g.FillRectangle(SystemBrushes.Window, this.ClientRectangle); Rectangle rectTitle = new Rectangle(0, 0, this.ClientRectangle.Width, GroupPanel.iHeaderHeight); g.FillRectangle(SystemBrushes.Control, rectTitle); g.DrawString(this.Text, this.Font, SystemBrushes.ControlText, new PointF(5.0f, 3.0f)); if (this.bIsMoveOverCloseGlyph) { g.FillRectangle(SystemBrushes.ButtonHighlight, this.rectCloseGlyphBounds); Rectangle rectBorder = this.rectCloseGlyphBounds; rectBorder.Inflate(-1, -1); g.DrawRectangle(SystemPens.Highlight, rectBorder); } using (Pen pen = new Pen(SystemColors.ControlText, 1.6f)) { if (this.Closed) { g.DrawLine(pen, this.rectCloseGlyphBounds.Left + 3, this.rectCloseGlyphBounds.Top + 3, this.rectCloseGlyphBounds.Left + 8, this.rectCloseGlyphBounds.Top + 8); g.DrawLine(pen, this.rectCloseGlyphBounds.Left + 13, this.rectCloseGlyphBounds.Top + 3, this.rectCloseGlyphBounds.Left + 8, this.rectCloseGlyphBounds.Top + 8); g.DrawLine(pen, this.rectCloseGlyphBounds.Left + 3, this.rectCloseGlyphBounds.Top + 7, this.rectCloseGlyphBounds.Left + 8, this.rectCloseGlyphBounds.Top + 12); g.DrawLine(pen, this.rectCloseGlyphBounds.Left + 13, this.rectCloseGlyphBounds.Top + 7, this.rectCloseGlyphBounds.Left + 8, this.rectCloseGlyphBounds.Top + 12); } else { g.DrawLine(pen, this.rectCloseGlyphBounds.Left + 3, this.rectCloseGlyphBounds.Top + 8, this.rectCloseGlyphBounds.Left + 8, this.rectCloseGlyphBounds.Top + 3); g.DrawLine(pen, this.rectCloseGlyphBounds.Left + 13, this.rectCloseGlyphBounds.Top + 8, this.rectCloseGlyphBounds.Left + 8, this.rectCloseGlyphBounds.Top + 3); g.DrawLine(pen, this.rectCloseGlyphBounds.Left + 3, this.rectCloseGlyphBounds.Top + 12, this.rectCloseGlyphBounds.Left + 8, this.rectCloseGlyphBounds.Top + 7); g.DrawLine(pen, this.rectCloseGlyphBounds.Left + 13, this.rectCloseGlyphBounds.Top + 12, this.rectCloseGlyphBounds.Left + 8, this.rectCloseGlyphBounds.Top + 7); } } } protected override void OnMouseDown (MouseEventArgs e) { if (e.Button == MouseButtons.Left && this.rectCloseGlyphBounds.Contains(e.Location)) this.Closed = !this.Closed; // close will call invalidate base.OnMouseDown(e); } protected override void OnMouseMove (MouseEventArgs e) { this.bIsMoveOverCloseGlyph = this.rectCloseGlyphBounds.Contains(e.Location); this.Invalidate(this.rectCloseGlyphBounds); base.OnMouseMove(e); } #endregion } }

    Read the article

  • OnPaint event during a callback when the form is below?

    - by Martín Marconcini
    Imagine the following scenario: this.SetStyle(ControlStyles.UserPaint, true); //this doesn’t change anything … void OpenSomeForm() { SomeForm sf = new SomeForm(); sf.SomeEvent += new … (SomeEventOcurred); sf.ShowDialog(); } private void SomeEventOcurred(…) { OnePanelInThisForm.Invalidate(); } private void OnePanelInThisForm_Paint(object sender, PaintEventArgs e) { DoSomeDrawing(e.Graphics); } Now, OnePanelInThisForm draws correctly when the form loads. But if SomeEventOcurred is Fired from “SomeForm”, the paint event is not fired. If I close and reopen the form it correctly repaints. If I add a button to the form that executes: OnePanelInThisForm.Invalidate(); the panel is correctly repaint. What am I missing?

    Read the article

  • Is there any way that I can draw fast a chart with too many series? [on hold]

    - by Maryam Bagheri
    I have a project that need to draw a fast chart with many series. I must change start position of drawing to a favor position when user want. .Net Chart is slow in lots of series. I wanted to use this library: http://www.codeproject.com/Articles/32836/A-simple-C-library-for-graph-plotting?msg=4109664#xx4109664xx but loading speed is too slow when count of series increases. When I plot the chart, I must invalidate the chart for updates, drawing speed will be too slow if there are too many series. I need at least 900 series in a chart for this project. I wanted to use multiple layer series to decrease invalidate rate with the idea: http://www.codeproject.com/Articles/84833/Drawing-multiple-layers-without-flicker I do not know this idea would be helpful. I tested LightningChart control but it could not help me.

    Read the article

  • When i add a bitmap to an array list the last element is duplicated in previous indexes

    - by saxofone2
    I'm trying to implement a personal way of undo/redo in a finger paint-like app. I have in synthesis three objects: the Main class (named ScorePadActivity), the relative Main Layout (with buttons, menus, etc, as well as a View object where I create my drawings), and a third object named ArrayList where i'm writing the undo/redo code. The problem is, when I press the undo button nothing happens, but if I draw anything again "one-time" and press undo, the screen is updated. If I draw many times, to see any changes happen on screen I have to press the undo button the same number of times I have drawn. Seems like (as in title) when I add a bitmap to the array list the last element is duplicated in previous indexes, and for some strange reason, everytime I press the Undo Button, the system is ok for one time, but starts to duplicate until the next undo. The index increase is verified with a series of System.out.println inserted in code. Now when I draw something on screen, the array list is updated with the code inserted after the invocation of touchup(); method in motionEvent touch_up(); } this.arrayClass.incrementArray(mBitmap); mPath.rewind(); invalidate(); and in ArrayList activity; public void incrementArray(Bitmap mBitmap) { this._mBitmap=mBitmap; _size=undoArray.size(); undoArray.add(_size, _mBitmap); } (All Logs removed for clear reading) The undo button in ScorePadActivity calls the undo method in View activity: Button undobtn= (Button)findViewById(R.id.undo); undobtn.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mView.undo(); } }); in View activity: public void undo() { this.mBitmap= arrayClass.undo(); mCanvas = new Canvas(mBitmap); mPath.rewind(); invalidate(); } that calls the relative undo method in ArrayList activity: public Bitmap undo() { // TODO Auto-generated method stub _size=undoArray.size(); if (_size>1) { undoArray.remove(_size-1); _size=undoArray.size(); _mBitmap = ((Bitmap) undoArray.get(_size-1)).copy(Bitmap.Config.ARGB_8888,true); } return _mBitmap; } return mBitmap and invalidate: Due to my bad English I have made a scheme to make the problem more clear: I have tried with HashMap, with a simple array, I have tried to change mPath.rewind(); with reset();, new Path(); etc but nothing. Why? Sorry for the complex answer, i want give you a great thanks in advance. Best regards

    Read the article

  • Android AsyncTask testing problem with Android Test Framework

    - by Vlad
    I have a very simple AsyncTask implementation example and have problem to test it using Android JUnit framework. It works just fine when I instantiate and execute it in normal application. However when it's executed from any of Android Testing framework classes (i.e. AndroidTestCase, ActivityUnitTestCase, ActivityInstrumentationTestCase2 etc) it behaves sarngely: - It executes doInBackground() method correctly - However it doesn't invokes any of its notification methods (onPostExecute(), onProgressUpdate(), etc) -- just silently ignores them whitout showing any errors. This is very simple AsyncTask example package kroz.andcookbook.threads.asynctask; import android.os.AsyncTask; import android.util.Log; import android.widget.ProgressBar; import android.widget.Toast; public class AsyncTaskDemo extends AsyncTask<Integer, Integer, String> { AsyncTaskDemoActivity _parentActivity; int _counter; int _maxCount; public AsyncTaskDemo(AsyncTaskDemoActivity asyncTaskDemoActivity) { _parentActivity = asyncTaskDemoActivity; } @Override protected void onPreExecute() { super.onPreExecute(); _parentActivity._progressBar.setVisibility(ProgressBar.VISIBLE); _parentActivity._progressBar.invalidate(); } @Override protected String doInBackground(Integer... params) { _maxCount = params[0]; for (_counter = 0; _counter <= _maxCount; _counter++) { try { Thread.sleep(1000); publishProgress(_counter); } catch (InterruptedException e) { // Ignore } } } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int progress = values[0]; String progressStr = "Counting " + progress + " out of " + _maxCount; _parentActivity._textView.setText(progressStr); _parentActivity._textView.invalidate(); } @Override protected void onPostExecute(String result) { super.onPostExecute(result); _parentActivity._progressBar.setVisibility(ProgressBar.INVISIBLE); _parentActivity._progressBar.invalidate(); } @Override protected void onCancelled() { super.onCancelled(); _parentActivity._textView.setText("Request to cancel AsyncTask"); } } This is a test case. Here AsyncTaskDemoActivity is a very simple Activity providing UI for testing AsyncTask in mode: package kroz.andcookbook.test.threads.asynctask; import java.util.concurrent.ExecutionException; import kroz.andcookbook.R; import kroz.andcookbook.threads.asynctask.AsyncTaskDemo; import kroz.andcookbook.threads.asynctask.AsyncTaskDemoActivity; import android.content.Intent; import android.test.ActivityUnitTestCase; import android.widget.Button; public class AsyncTaskDemoTest2 extends ActivityUnitTestCase<AsyncTaskDemoActivity> { AsyncTaskDemo _atask; private Intent _startIntent; public AsyncTaskDemoTest2() { super(AsyncTaskDemoActivity.class); } protected void setUp() throws Exception { super.setUp(); _startIntent = new Intent(Intent.ACTION_MAIN); } protected void tearDown() throws Exception { super.tearDown(); } public final void testExecute() { startActivity(_startIntent, null, null); Button btnStart = (Button) getActivity().findViewById(R.id.Button01); btnStart.performClick(); assertNotNull(getActivity()); } } All this code is working just fine, except the fact that AsynTask doesn't invoke it's notification methods when executed by whithin Android Testing Framework. Any ideas?

    Read the article

  • Help Repainting a Line

    - by serhio
    I am doing a custom control (inherited from VisualBasic.PowerPacks.LineShape), that should be painted like as standard one, but also having a Icon displayed near it. So, I just overrided OnPaint like this: protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { e.Graphics.DrawIcon(myIcon, StartPoint.X, StartPoint.Y); base.OnPaint(e); } Now, everything is OK, but when my control moves, the icon still remains drawn on the ancient place. Is there a way to paint it properly? The sample code for tests using Microsoft.VisualBasic.PowerPacks; using System.Windows.Forms; using System.Drawing; namespace LineShapeTest { /// /// Test Form /// public class Form1 : Form { IconLineShape myLine = new IconLineShape(); ShapeContainer shapeContainer1 = new ShapeContainer(); Panel panel1 = new Panel(); public Form1() { this.panel1.Dock = DockStyle.Fill; // load your back image here this.panel1.BackgroundImage = global::WindowsApplication22.Properties.Resources._13820t; this.panel1.Controls.Add(shapeContainer1); this.myLine.StartPoint = new Point(20, 30); this.myLine.EndPoint = new Point(80, 120); this.myLine.Parent = this.shapeContainer1; MouseEventHandler panelMouseMove = new MouseEventHandler(this.panel1_MouseMove); this.panel1.MouseMove += panelMouseMove; this.shapeContainer1.MouseMove += panelMouseMove; this.Controls.Add(panel1); } private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { myLine.StartPoint = e.Location; } } } /// /// Test LineShape /// public class IconLineShape : LineShape { Icon myIcon = SystemIcons.Exclamation; protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { e.Graphics.DrawIcon(myIcon, StartPoint.X, StartPoint.Y); base.OnPaint(e); } } } Nota Bene, for the lineShape: Parent = ShapeContainer Parent.Parent = Panel Update 1 TRACES In this variant of OnPaint, we have traces: protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { Graphics g = Parent.Parent.CreateGraphics(); g.DrawIcon(myIcon, StartPoint.X, StartPoint.Y); base.OnPaint(e); } Update 2 BLINKS In this variant of OnPaint, we have a blinking image: protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { Parent.Parent.Invalidate(this.Region, true); Graphics g = Parent.Parent.CreateGraphics(); g.DrawIcon(myIcon, StartPoint.X, StartPoint.Y); base.OnPaint(e); } Update 3: External Invalidation This variant works well, but... from exterior of IconLineShape class: private void panel1_MouseMove(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Region r = myLine.Region; myLine.StartPoint = e.Location; panel1.Invalidate(r); } } /// /// Test LineShape /// public class IconLineShape : LineShape { Icon myIcon = SystemIcons.Exclamation; Graphics parentGraphics; protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { parentGraphics.DrawIcon(myIcon, StartPoint.X, StartPoint.Y); base.OnPaint(e); } protected override void OnParentChanged(System.EventArgs e) { // Parent is a ShapeContainer // Parent.Parent is a Panel parentGraphics = Parent.Parent.CreateGraphics(); base.OnParentChanged(e); } } Even this resolves the problem of the test example, I need this control to be done inside the control, because I can't force the external "clients" of this control do not forget to save the old region and invalidate the parent each time changing a location...

    Read the article

  • IPhone sdk stop the accelerometer from working when something happens.

    - by Harry
    Hi, I am using the accelerometer to move a few UIImageViews around the screen, at the moment the accelerometer only works when a NSTimer is at 0, this is fine. I would also like to make the accelerometer stop again when a different function happens. here is my code at the moment: -(BOOL) accelerometerWorks { return time == 0; } -(void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{ if(![self accelerometerWorks]) return; valueX = acceleration.x*25.5; int newX = (int)(ball.center.x +valueX); if (newX 320-BALL_RADIUS) newX = 320-BALL_RADIUS; if (newX < 0+BALL_RADIUS) newX = 0+BALL_RADIUS; int XA = (int)(balloonbit1.center.x +valueX); if (XA 320-BALL_RADIUS) XA = 320-BALL_RADIUS; if (XA < 0+BALL_RADIUS) XA = 0+BALL_RADIUS; int XB = (int)(balloonbit2.center.x +valueX); if (XB 320-BALL_RADIUS) XB = 320-BALL_RADIUS; if (XB < 0+BALL_RADIUS) XB = 0+BALL_RADIUS; int XI = (int)(balloonbit3.center.x +valueX); if (XI 320-BALL_RADIUS) XI = 320-BALL_RADIUS; if (XI < 0+BALL_RADIUS) XI = 0+BALL_RADIUS; int XJ = (int)(balloonbit4.center.x +valueX); if (XJ 320-BALL_RADIUS) XJ = 320-BALL_RADIUS; if (XJ < 0+BALL_RADIUS) XJ = 0+BALL_RADIUS; int XE = (int)(balloonbit5.center.x +valueX); if (XE 320-BALL_RADIUS) XE = 320-BALL_RADIUS; if (XE < 0+BALL_RADIUS) XE = 0+BALL_RADIUS; int XF = (int)(balloonbit6.center.x +valueX); if (XF 320-BALL_RADIUS) XF = 320-BALL_RADIUS; if (XF < 0+BALL_RADIUS) XF = 0+BALL_RADIUS; int XH = (int)(balloonbit8.center.x +valueX); if (XH 320-BALL_RADIUS) XH = 320-BALL_RADIUS; if (XH < 0+BALL_RADIUS) XH = 0+BALL_RADIUS; ball.center = CGPointMake (newX, 429); balloonbit1.center = CGPointMake (XA, 429); balloonbit2.center = CGPointMake (XB, 426); balloonbit3.center = CGPointMake (XI, 410); balloonbit4.center = CGPointMake (XJ, 415); balloonbit5.center = CGPointMake (XE, 409); balloonbit6.center = CGPointMake (XF, 427); balloonbit8.center = CGPointMake (XH, 417); } This all works fine, i would now like to stop the accelerometer from working, using the same accelerometerWorks method or a new method, accelerometerWontWork. This is the code that when it is called i would like the accelerometer to stop. (it is very long so i wont put all of it there, but its all the same throughout): -(void) checkCollision{ if (CGRectIntersectsRect(pinend.frame, balloonbit1.frame)){ if (balloonbit1.frame.origin.y pinend.frame.origin.y){ [maintimer invalidate]; levelfailed.center = CGPointMake (160, 235); } } if (CGRectIntersectsRect(pinend.frame, balloonbit2.frame)){ if (balloonbit2.frame.origin.y pinend.frame.origin.y){ [maintimer invalidate]; levelfailed.center = CGPointMake (160, 235); } } if (CGRectIntersectsRect(pinend.frame, balloonbit3.frame)){ if (balloonbit3.frame.origin.y pinend.frame.origin.y){ [maintimer invalidate]; levelfailed.center = CGPointMake (160, 235); } } } I understand that i may have to turn this into a BOOL. Thats fine. If i haven't explained it well please say and i will re write it. Thanks! Harry.

    Read the article

  • Caching factory design

    - by max
    I have a factory class XFactory that creates objects of class X. Instances of X are very large, so the main purpose of the factory is to cache them, as transparently to the client code as possible. Objects of class X are immutable, so the following code seems reasonable: # module xfactory.py import x class XFactory: _registry = {} def get_x(self, arg1, arg2, use_cache = True): if use_cache: hash_id = hash((arg1, arg2)) if hash_id in _registry: return _registry[hash_id] obj = x.X(arg1, arg2) _registry[hash_id] = obj return obj # module x.py class X: # ... Is it a good pattern? (I know it's not the actual Factory Pattern.) Is there anything I should change? Now, I find that sometimes I want to cache X objects to disk. I'll use pickle for that purpose, and store as values in the _registry the filenames of the pickled objects instead of references to the objects. Of course, _registry itself would have to be stored persistently (perhaps in a pickle file of its own, in a text file, in a database, or simply by giving pickle files the filenames that contain hash_id). Except now the validity of the cached object depends not only on the parameters passed to get_x(), but also on the version of the code that created these objects. Strictly speaking, even a memory-cached object could become invalid if someone modifies x.py or any of its dependencies, and reloads it while the program is running. So far I ignored this danger since it seems unlikely for my application. But I certainly cannot ignore it when my objects are cached to persistent storage. What can I do? I suppose I could make the hash_id more robust by calculating hash of a tuple that contains arguments arg1 and arg2, as well as the filename and last modified date for x.py and every module and data file that it (recursively) depends on. To help delete cache files that won't ever be useful again, I'd add to the _registry the unhashed representation of the modified dates for each record. But even this solution isn't 100% safe since theoretically someone might load a module dynamically, and I wouldn't know about it from statically analyzing the source code. If I go all out and assume every file in the project is a dependency, the mechanism will still break if some module grabs data from an external website, etc.). In addition, the frequency of changes in x.py and its dependencies is quite high, leading to heavy cache invalidation. Thus, I figured I might as well give up some safety, and only invalidate the cache only when there is an obvious mismatch. This means that class X would have a class-level cache validation identifier that should be changed whenever the developer believes a change happened that should invalidate the cache. (With multiple developers, a separate invalidation identifier is required for each.) This identifier is hashed along with arg1 and arg2 and becomes part of the hash keys stored in _registry. Since developers may forget to update the validation identifier or not realize that they invalidated existing cache, it would seem better to add another validation mechanism: class X can have a method that returns all the known "traits" of X. For instance, if X is a table, I might add the names of all the columns. The hash calculation will include the traits as well. I can write this code, but I am afraid that I'm missing something important; and I'm also wondering if perhaps there's a framework or package that can do all of this stuff already. Ideally, I'd like to combine in-memory and disk-based caching.

    Read the article

  • How to draw an overlay on a SurfaceView used by Camera on Android?

    - by Cristian Castiblanco
    I have a simple program that draws the preview of the Camera into a SurfaceView. What I'm trying to do is using the onPreviewFrame method, which is invoked each time a new frame is drawn into the SurfaceView, in order to execute the invalidate method which is supposed to invoke the onDraw method. In fact, the onDraw method is being invoked, but nothing there is being printed (I guess the camera preview is overwriting the text I'm trying to draw). This is a simplify version of the SurfaceView subclass I have: public class Superficie extends SurfaceView implements SurfaceHolder.Callback { SurfaceHolder mHolder; public Camera camera; Superficie(Context context) { super(context); mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(final SurfaceHolder holder) { camera = Camera.open(); try { camera.setPreviewDisplay(holder); camera.setPreviewCallback(new PreviewCallback() { public void onPreviewFrame(byte[] data, Camera arg1) { invalidar(); } }); } catch (IOException e) {} } public void invalidar(){ invalidate(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { Camera.Parameters parameters = camera.getParameters(); parameters.setPreviewSize(w, h); camera.setParameters(parameters); camera.startPreview(); } @Override public void draw(Canvas canvas) { super.draw(canvas); // nothing gets drawn :( Paint p = new Paint(Color.RED); canvas.drawText("PREVIEW", canvas.getWidth() / 2, canvas.getHeight() / 2, p); } }

    Read the article

  • Did I find a bug in WriteableBitmap when using string literals

    - by liserdarts
    For performance reasons I'm converting a large list of images into a single image. This code does exactly what I want. Private Function FlattenControl(Control As UIElement) As Image Control.Measure(New Size(1000, 1000)) Control.Arrange(New Rect(0, 0, 1000, 1000)) Dim ImgSource As New Imaging.WriteableBitmap(1000, 1000) ImgSource.Render(Control, New TranslateTransform) ImgSource.Invalidate Dim Img As New Image Img.Source = ImgSource Return Img End Function I can add all the images into a canvas pass the canvas to this function and I get back one image. My code to load all the images looks like this. Public Function BuildTextures(Layer As GLEED2D.Layer) As FrameworkElement Dim Container As New Canvas For Each Item In Layer.Items If TypeOf Item Is GLEED2D.TextureItem Then Dim Texture = CType(Item, GLEED2D.TextureItem) Dim Url As New Uri(Texture.texture_filename, UriKind.Relative) Dim Img As New Image Img.Source = New Imaging.BitmapImage(Url) Container.Children.Add(Img) End If Next Return FlattenControl(Container) End Function The GLEED2D.Layer and GLEED2D.TextureItem classes are from the free level editor GLEED2D (http://www.gleed2d.de/). The texture_filename on every TextureItem is "Images/tree_clipart_pine_tree.png" This works just fine, but it's just a proof of concept. What I really need to do (among other things) is have the path to the image hard coded. If I replace Texture.texture_filename in the code above with the string literal "Images/tree_clipart_pine_tree.png" the images do not appear in the final merged image. I can add a breakpoint and see that the WriteableBitmap has all of it's pixels as 0 after the call to Invalidate. I have no idea how this could cause any sort of difference, but it gets stranger. If I remove the call to FlattenControl and just return the Canvas instead, the images are visible. It's only when I use the string literal with the WriableBitmap that the images do not appear. I promise you that the value in the texture_filename property is exactly "Images/tree_clipart_pine_tree.png". I'm using Silverlight 3 and I've also reproduced this in Silverlight 4. Any ideas?

    Read the article

  • How do I access variable values from one view controller in another?

    - by Thomas
    Hello all, I have an integer variable (time) in one view controller whose value I need in another view controller. Here's the code: MediaMeterViewController // TRP - On Touch Down event, start the timer -(IBAction) startTimer { time = 0; // TRP - Start a timer timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES]; [timer retain]; // TRP - Retain timer so it is not accidentally deallocated } // TRP - Method to update the timer display -(void)updateTimer { time++; // NSLog(@"Seconds: %i ", time); if (NUM_SECONDS == time) [timer invalidate]; } // TRP - On Touch Up Inside event, stop the timer, decide stress level, display results -(IBAction) btn_MediaMeterResults { [timer invalidate]; NSLog(@"Seconds: %i ", time); ResultsViewController *resultsView = [[ResultsViewController alloc] initWithNibName:@"ResultsViewController" bundle:nil]; [self.view addSubview:resultsView.view]; } And in ResultsViewController, I want to process time based on its value ResultsViewController - (void)viewDidLoad { if(time < 3) {// Do something} else if ((time > 3) && (time < 6)) {// Do something else} //etc... [super viewDidLoad]; } I'm kind of unclear on when @property and @synthesize is necessary. Is that the case in this situation? Any help would be greatly appreciated. Thanks! Thomas

    Read the article

  • Clearing canvas with Canvas.drawColor()

    - by strangeInAStrangerLand
    I'm attempting to change the background image of a custom View with some success. The image will change but the problem is that I still see traces of the old image. When I attempt to clear the canvas before drawing the new image, it doesn't appear to work. I create a bitmap to store the image. When changing the image, I call Canvas.drawColor() before drawing the new image but the old image persists. I've tried drawColor(0), drawColor(Color.BLACK), c.drawColor(0, PorterDuff.Mode.CLEAR), and none of the above works. As such, I had to post this for review from more experienced minds than mine. The actual code is as follows: private int bgnd; private boolean switching; public void setBgnd(int incoming){ switching = true; switch (incoming){ case R.drawable.image1: bgnd = incoming; this.invalidate(); break; case R.drawable.image2: bgnd = incoming; this.invalidate(); break; } } protected void onDraw(Canvas c){ if(switching == true){ Bitmap b = BitmapFactory.decodeResource(getResources(), bgnd); c.drawColor(0, PorterDuff.Mode.CLEAR); c.drawBitmap(b, 0, 0, null); switching = false; }else{ Bitmap b = BitmapFactory.decodeResource(getResources(), bgnd); c.drawBitmap(b, 0, 0, null); } }

    Read the article

  • How to draw multiple rectangles using c#

    - by Nivas
    I have drawn and saved the Rectangle on the image i loaded in the picture box. How i like to draw multiple rectangles for that i tried array in the rectangle but it gives error ("Object reference not set to an instance of an object." (Null reference Exception was unhandled). private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (mybitmap == null) { mybitmap = new Bitmap(sz.Width, sz.Height); } rect[count] = new Rectangle(e.X, e.Y, 0, 0); this.Invalidate(); } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (stayToolStripMenuItem.Checked == true) { switch (e.Button) { case MouseButtons.Left: { rect[count] = new Rectangle(rect[count].Left, rect[count].Top, e.X - rect[count].Left, e.Y - rect[count].Top); pictureBox1.Invalidate(); count++: break; } } } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { if (stayToolStripMenuItem.Checked == true) { button1.Visible = true; button2.Visible = true; if (mybitmap == null) { return; } using (g = Graphics.FromImage(mybitmap)) { using (Pen pen = new Pen(Color.Red, 2)) { //g.Clear(Color.Transparent); e.Graphics.DrawRectangle(pen, rect); label1.Top = rect[count].Top; label1[count].Left = rect[count].Left; label1.Width = rect[count].Width; label1.Height = rect[count].Height; if (label1.TextAlign == ContentAlignment.TopLeft) { e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawRectangle(pen, rect[count]); } } } } } How can i do this.....

    Read the article

  • ASP.NET output caching - dynamically update dependencies

    - by ColinE
    Hi All, I have an ASP.NET application which requires output caching. I need to invalidate the cached items when the data returned from a web service changes, so a simple duration is not good enough. I have been doing a bit of reading about cache dependencies and think I have the right idea. It looks like I will need to create a cache dependency to my web service. To associate the page output with this dependency I think I should use the following method: Response.AddCacheItemDependency(cacheKey); The thing I am struggling with is what I should add to the cache? The dependency my page has is to a single value returned by the web service. My current thinking is that I should create a Custom Cache Dependency via subclassing CacheDependency, and store the current value in the cache. I can then use Response.AddCacheItemDependency to form the dependency. I can then periodically check the value and for a NotifyDependencyChange in order to invalidate my cached HTTP response. The problem is, I need to ensure that the cache is flushed immediately, so a periodic check is not good enough. How can I ensure that my dependant object in the cache which represents the value returned by the web service is re-evaluated before the HTTP response is fetched from the cache? Regards, Colin E.

    Read the article

  • iPhone: Using dispatch_after to mimick NSTimer

    - by Joseph Tura
    Don't know a whole lot about blocks. How would you go about mimicking a repeating NSTimer with dispatch_after? My problem is that I want to "pause" a timer when the app moves to the background, but subclassing NSTimer does not seem to work. I tried something which seems to work. I cannot judge its performance implications or whether it could be greatly optimized. Any input is welcome. #import "TimerWithPause.h" @implementation TimerWithPause @synthesize timeInterval; @synthesize userInfo; @synthesize invalid; @synthesize invocation; + (TimerWithPause *)scheduledTimerWithTimeInterval:(NSTimeInterval)aTimeInterval target:(id)aTarget selector:(SEL)aSelector userInfo:(id)aUserInfo repeats:(BOOL)aTimerRepeats { TimerWithPause *timer = [[[TimerWithPause alloc] init] autorelease]; timer.timeInterval = aTimeInterval; NSMethodSignature *signature = [[aTarget class] instanceMethodSignatureForSelector:aSelector]; NSInvocation *aInvocation = [NSInvocation invocationWithMethodSignature:signature]; [aInvocation setSelector:aSelector]; [aInvocation setTarget:aTarget]; [aInvocation setArgument:&timer atIndex:2]; timer.invocation = aInvocation; timer.userInfo = aUserInfo; if (!aTimerRepeats) { timer.invalid = YES; } [timer fireAfterDelay]; return timer; } - (void)fireAfterDelay { dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, self.timeInterval * NSEC_PER_SEC); dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_after(delay, queue, ^{ [invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:NO]; if (!invalid) { [self fireAfterDelay]; } }); } - (void)invalidate { invalid = YES; [invocation release]; invocation = nil; [userInfo release]; userInfo = nil; } - (void)dealloc { [self invalidate]; [super dealloc]; } @end

    Read the article

  • How can I remove a JPanel from a JFrame?

    - by Roman
    Recently I asked here how to add a new JPanel to JFrame. The answer helped me to get a working code. But not I have a related question: "How can I remove an old JPanel". I need that because of the following problem. A new JPanel appears appears when I want (either time limit is exceeded or user press the "Submit" button). But in several seconds some element of the old JPanel appears together with the component of the new JPanel. I do not understand why it happens. I thought that it is because I have to other threads which update the window. But the first thread just add the old panel once (so, it should be finished). And in the second thread I have a loop which is broken (so, it also should be finished). Here is my code: private Thread controller = new Thread() { public void run() { // First we set the initial pane (for the selection of partner). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().add(generatePartnerSelectionPanel()); frame.invalidate(); frame.validate(); } }); // Update the pane for the selection of the parnter. for (int i=40; i>0; i=i-1) { final int sec = i; SwingUtilities.invokeLater(new Runnable() { public void run() { timeLeftLabel.setText(sec + " seconds left."); } }); try {Thread.sleep(1000);} catch (InterruptedException e) {} if (partnerSubmitted) {break;} } // For the given user the selection phase is finished (either the time is over or form was submitted). SwingUtilities.invokeLater(new Runnable() { public void run() { frame.getContentPane().add(generateWaitForGamePanel()); frame.invalidate(); frame.validate(); } }); } };

    Read the article

  • CustomButton Field not aligning in the center

    - by rupesh
    Hi all I have created a custom button and i am placing the bunch of Custombuttons in a verticalfieldManager , I have aligned the verticalField Manager in the center. when i am creating a default buttonField then verticalfield Manager is able to align the buttonfield in the center. but when i am assigning custombuttonfield in the verticalField Manager it's not aligning in the center. here is my custombuttoncode enter code herepublic CustomButtonField(String label,long style) { super(style); this.label = label; onPicture = Bitmap.getBitmapResource(onPicturePath); font = getFont(); this.setPadding(5,5, 5, 5); } public String getLabel() { return label; } public int getPreferredHeight() { return onPicture.getHeight(); } public int getPreferredWidth() { return onPicture.getWidth(); } protected void layout(int width , int height) { setExtent(Math.min(width, Display.getWidth()), Math.min(height,getPreferredHeight())); } protected void paint(Graphics graphics) { int texty =(getHeight()-getFont().getHeight())/2; if (isFocus()) { graphics.setColor(Color.BLACK); graphics.drawBitmap(0, 0, getWidth(), getHeight(),onPicture , 0, 0); graphics.setColor(Color.WHITE); graphics.setFont(font); graphics.drawText(label,0,texty,DrawStyle.ELLIPSIS,getWidth()); } else { graphics.drawBitmap(0, 0, getWidth(), getHeight(),onPicture , 0, 0); graphics.setColor(Color.WHITE); graphics.setFont(font); graphics.drawText(label,0,texty,DrawStyle.ELLIPSIS,getWidth()); } } public boolean isFocusable() { return true; } protected void onFocus(int direction) { super.onFocus(direction); invalidate(); } protected void onUnfocus() { super.onUnfocus(); invalidate(); } protected boolean navigationClick(int status, int time) { fieldChangeNotify(0); return true; } protected boolean keyChar(char character, int status, int time) { if (character == Keypad.KEY_ENTER) { fieldChangeNotify(0); return true; } return super.keyChar(character, status, time); } }

    Read the article

  • How to check if there is an active session in a JSF page?

    - by Roberto de Santis
    Hi, there is a way to check if there is an active session directly in jsf page? I have try this but it doesn't work: <p:ajaxStatus onerror="#{session == null ? 'idleDialog.show();' : null}" thank you in advance @Update I have see that onerror isn't fired even if viewExpiredException occurr. @Update 1 Ok i have implemented something that may work: <h:form> <p:idleMonitor timeout="10000" idleListener="#{idleMonitorController.idleListener}" onidle="sessionPoll.stop();idleDialog.show();"/> </h:form> <p:dialog header="Sessione scaduta per inattività" widgetVar="idleDialog" modal="true" width="400"> <h:outputText value="Sessione scaduta" /> <h:button value="Ripristina Sessione" onclick="idleDialog.hide();sessionPoll.start();" /> </p:dialog> <h:form prependId="false"> <p:poll widgetVar="sessionPoll" interval="1"/> </h:form> and this is the listner: public void idleListener(IdleEvent event) { System.out.println("aaaa"); final HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); request.getSession(false).invalidate(); } now the only problem is that the session.invalidate doesn't work

    Read the article

  • How to draw mutiple rectangles using c#

    - by Nivas
    I have drawn and saved the Rectangle on the image i loaded in the picture box. How i like to draw multiple rectangles for that i tried array in the rectangle but it gives error ("Object reference not set to an instance of an object." (Null reference Exception was unhandled). enter code here private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (mybitmap == null) { mybitmap = new Bitmap(sz.Width, sz.Height); } rect = new Rectangle(e.X, e.Y, 0, 0); this.Invalidate(); } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (stayToolStripMenuItem.Checked == true) { switch (e.Button) { case MouseButtons.Left: { rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top); pictureBox1.Invalidate(); break; } } } } private void pictureBox1_Paint(object sender, PaintEventArgs e) { if (stayToolStripMenuItem.Checked == true) { button1.Visible = true; button2.Visible = true; if (mybitmap == null) { return; } using (g = Graphics.FromImage(mybitmap)) { using (Pen pen = new Pen(Color.Red, 2)) { //g.Clear(Color.Transparent); e.Graphics.DrawRectangle(pen, rect); label1.Top = rect.Top; label1.Left = rect.Left; label1.Width = rect.Width; label1.Height = rect.Height; if (label1.TextAlign == ContentAlignment.TopLeft) { e.Graphics.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawString(label1.Text, label1.Font, new SolidBrush(label1.ForeColor), rect); g.DrawRectangle(pen, rect); } } } } } How can i do this.....

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >