c# - Converting mouse click position to a given scale -


here's problem i'm trying solve:

you have screen display heart rate (of 1 hour - 60 minutes), how can know minute in, upon click on screen? when clicked on screen specific height , width.

this i've done: created form, , on form have docked picturebox object. picturebox object has method invoked clicking on picturebox object. method:

private void picturebox1_click(object sender, eventargs e) {     var mouseeventargs = e mouseeventargs;     if (mouseeventargs != null)     {         int widthperminute = (int)(mouseeventargs.x / ((picturebox1.width + 1) / 60.0));         messagebox.show((widthperminute).tostring());     } } 

is there more elegant solution?

i'm pretty sure misinterpreted asking first reply (i'm leaving @ end of answer reference).

i think you're asking higher-level design you're doing.

if going developing heart rate graph display further, rather using picturebox might want write own custom control it. way can encapsulate drawing logic nicely inside implementation.

that lot of learning though. worth if think might need write more in future.

msdn introduction here: http://msdn.microsoft.com/en-us/library/bs3yhkh7%28v=vs.110%29.aspx

but sound of it, it's interview question or something, in case won't want spending time on it. ;)


my previous answer:

i wouldn't there more "elegant" way, suppose make code more readable extracting separate method logic calculates minute:

int minuteatpictureboxcoord(int x) {     double totalminutes = 60;     double minutesperpixel = totalminutes/(picturebox1.width+1);     int minute = (int)(x*minutesperpixel);     return minute; } 

this lot longer, arguably lot easier see code correct. (although i'm not entirely sure +1 on picturebox1.width+1 - i'm not sure that's correct; copied original code.)

it simplifies call site:

private void picturebox1_click(object sender, eventargs e) {     var mouseeventargs = e mouseeventargs;     if (mouseeventargs != null)     {         int minute = minuteatpictureboxcoord(mouseeventargs.x);         messagebox.show(minute.tostring());     } } 

i think it's little easier tell @ glance code's to.

also, makes easier change calculations later if change things the number of minutes displayed across screen, or if have multiple rows of heart rate data (then you'd need x and y client coord).

one more thing: should using picturebox.mouseclick rather click(). way passed mouseeventargs don't need cast. become:

private void picturebox1_mouseclick(object sender, mouseeventargs e) {     int minute = minuteatpictureboxcoord(e.x);     messagebox.show(minute.tostring()); } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -