Saturday, 15 May 2010

c# - Do I need to dispose or destroy custom cursors -



c# - Do I need to dispose or destroy custom cursors -

i using code similar accepted reply this question create custom cursor. supposed ask, "what do when done custom cursor?" specific, question has 2 parts:

one: see code uses reflection set "ownhandle" field of cursor. create (native) handle gets destroyed when cursor object disposed? if not do?

two: have manually dispose cursor object or assigning new cursor command cause command dispose cursor me? instance:

private void customcursorbutton_clicked(object sender, eventargs e) { this.cursor = nativemethods.loadcustomcursor(@"c:\windows\cursors\aero_busy.ani"); } private void defaultcursorbutton_clicked(object sender, eventargs e) { var tmp = this.cursor; // have this.cursor = cursors.default; tmp.dispose(); // , this? }

you should ever phone call dispose() on object if know 100% sure object not used anywhere else. calling dispose() optional, finalizer of object ensures cleanup always occur. , 100% sure isn't used anywhere else. simply bit slow @ getting around doing job.

there little point single cursor object, cursor @ handful of kilobytes of memory. code creates cursor on , on 1 time again each click, , liable dispose parent's cursor (the cursor property ambient property) won't win lot of prizes. proper code makes effort ought resemble this:

private cursor customcursor; private void customcursorbutton_clicked(object sender, eventargs e) { if (customcursor == null) customcursor = nativemethods.loadcustomcursor(@"c:\windows\cursors\aero_busy.ani"); this.cursor = customcursor; } private void defaultcursorbutton_clicked(object sender, eventargs e) { var prev = this.cursor; this.cursor = cursors.default; if (prev == customcursor) { customcursor.dispose(); customcursor = null; } } protected override onformclosed(formclosedeventargs e) { base.onformclosed(e); if (customcursor != null) customcursor.dispose(); }

there's simple diagnostic available know you're getting wrong btw. task manager isn't much profiling .net apps great show whether missing dispose() calls getting problem in case. utilize view + select columns , tick "gdi objects", accurately traces cursor objects (in add-on other gdi objects). getting displayed value go on couple of hundred sign of trouble, give or take.

note must utilize environment.getfolderpath() retrieve install location of windows. , deal failure, there's no hard guarantee cursor available. details, details.

c# custom-controls idisposable cursors

No comments:

Post a Comment