c# - WPF create one Window for each screen, and center them on each screen -
edit: solved it. see fix in answer below.
i'm working on application should open small popup window on each screen connected computer runs on. simple enough on single screen (using windowstartuplocation = centerscreen), surprisingly difficult on multiple screens.
my current code this:
foreach (var s in screen.allscreens) //system.windows.forms.screen { var b = s.bounds; var w = new popupwindow(); var ow = w.width; //keep track of original size ... var oh = w.height; w.width = 0; //then set size 0, avoid w.height = 0;//popup shows before correctly positioned w.show(); //now show it, can place (when //tried place before showing, window //was repositioned when show() called) double dpix = 1, dpiy = 1; var presentationsource = presentationsource.fromvisual(w); if (presentationsource != null) { dpix = presentationsource.compositiontarget.transformtodevice.m11; dpiy = presentationsource.compositiontarget.transformtodevice.m22; } var aw = ow*dpix; //calculate actual size of window var ah = oh*dpiy; //***** wrong, see answer ***** w.left = (b.x + (b.width / dpix - aw) / 2); //place w.top = (b.y + (b.height / dpiy - ah) / 2); //************************************* w.width = ow; //and set size original size w.height = oh; } this seems work on primary screen. on other screens, windows not centered.
i guess because knowledge of wpf , dpi limited, , i'm doing wrong. point me in right direction?
of course, managed solve after posting here. looks did else wrong when tried divide entire location dpi, led me onto wrong path posted above.
the correct lines placing form should (all other code works):
w.left = (b.x + (b.width - aw) / 2) / dpix; w.top = (b.y + (b.height - ah) / 2) / dpix; but, still think lot of code simple task, if has better ideas, please let me know!
so (working) code i'm using now:
foreach (var s in screen.allscreens) //system.windows.forms.screen { var b = s.bounds; var w = new popupwindow(); var ow = w.width; //keep track of original size ... var oh = w.height; w.width = 0; //then set size 0, avoid w.height = 0;//popup shows before correctly positioned w.show(); //now show it, can place (when //tried place before showing, window //was repositioned when show() called) double dpix = 1, dpiy = 1; var ps = presentationsource.fromvisual(w); if (ps != null) { dpix = ps.compositiontarget.transformtodevice.m11; dpiy = ps.compositiontarget.transformtodevice.m22; } var aw = ow*dpix; //calculate actual size of window var ah = oh*dpiy; w.left = (b.x + (b.width - aw) / 2) / dpix; w.top = (b.y + (b.height - ah) / 2) / dpix; w.width = ow; //and set size original size w.height = oh; }
Comments
Post a Comment