LoginSignup
1
1

More than 1 year has passed since last update.

【C#】WindowsフォームアプリケーションでWordと画面分割するときに手こずった話 - Microsoft.Office.Interop.Word

Last updated at Posted at 2021-12-27

とあるアプリケーションを開発しているときに2つのウィンドウを同じ大きさでスクリーンに並べようとしたときにハマった時の話です。
もしかしたらプログラミング経験の浅い人だけでなく、ベテランの方でもハマる可能性があるので参考になれば幸いです。

画面分割イメージ(理想)

メインフォームの大きさと同等の大きさのWordをスクリーン内に並べる。
image.png

画面分割イメージ(現実)

Wordの大きさがメインフォームよりも大きくなり、起動位置が大きく右にズレて画面からはみ出る。
image.png

原因

下記のプロパティがpx単位ではなくpoint単位のため。
- objWord.ActiveWindow.Top
- objWord.ActiveWindow.Left
- objWord.ActiveWindow.Width
- objWord.ActiveWindow.Height

point単位のところをpx単位で指定すれば、当然意図したサイズよりも大きくなる。
よってobjWordComs.ActiveWindow.Leftでセットした値以上に右へ配置されて起動され画面からはみ出る。
言わずもがなobjWordComs.ActiveWindow.Heightもまた意図したサイズよりも大きくなる。

ソースコード

Rectangle rectangle = Screen.GetWorkingArea(this.FindForm());
this.FindForm().SetBounds(0, 0, this.FindForm().Width, rectangle.Height, BoundsSpecified.All);

Microsoft.Office.Interop.Word.Application objWordComs = new Microsoft.Office.Interop.Word.Application();
objWord.Documents.Open(filePath);
objWord.ActiveWindow.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateNormal;
objWord.ActiveWindow.Top = 0;
objWord.ActiveWindow.Left = Convert.ToInt32(this.FindForm().Width);
objWord.ActiveWindow.Width = Convert.ToInt32((rect.Width - this.FindForm().Width) / 2);
objWord.ActiveWindow.Height = Convert.ToInt32(rect.Height);

解決策

下記のプロパティに値をセットする際にPixelsToPointsメソッドをかませてからセットする。
- objWord.ActiveWindow.Top
- objWord.ActiveWindow.Left
- objWord.ActiveWindow.Width
- objWord.ActiveWindow.Height

ソースコード

Rectangle rectangle = Screen.GetWorkingArea(this.FindForm());
this.FindForm().SetBounds(0, 0, this.FindForm().Width, rectangle.Height, BoundsSpecified.All);

Microsoft.Office.Interop.Word.Application objWord = new Microsoft.Office.Interop.Word.Application();
objWord.Documents.Open(filePath);
objWord.ActiveWindow.WindowState = Microsoft.Office.Interop.Word.WdWindowState.wdWindowStateNormal;
objWord.ActiveWindow.Top = 0;
objWord.ActiveWindow.Left = Convert.ToInt32(objWord.PixelsToPoints(this.FindForm().Width));
objWord.ActiveWindow.Width = Convert.ToInt32(objWord.PixelsToPoints((rect.Width - this.FindForm().Width) / 2));
objWord.ActiveWindow.Height = Convert.ToInt32(objWord.PixelsToPoints(rect.Height));
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1