• ベストアンサー
※ ChatGPTを利用し、要約された質問です(原文:なぜForm型にキャストするのでしょう?)

なぜForm型にキャストするのでしょう?

jactaの回答

  • jacta
  • ベストアンサー率26% (845/3158)
回答No.2

一般的なことをいえば、イベントハンドラに渡されたsender(ここではobjSender)がForm型であるとはかぎりません。 なぜなら、イベントハンドラをイベントとして処理するのではなく、直接呼び出すこともできてしまうからです。 ただ、今回のケースに限っていえば、MyPaintHandlerメソッドはprivateで他のクラスから呼ばれる可能性はなく、Form.Paintに登録しているので、Form型のオブジェクトがobjectに変換されて渡されることが期待できるということです。 厳密なことをいえば、"Paint Hello"というフォームのタイトルを頼りにするなどしてformのインスタンスを見つけ出し、Paintイベントを漁ってMyPaintHandlerを取り出した上で直接呼び出すといったこともできるでしょうから、やや無防備なのは確かですが... キャストが必要なのは、FormクラスのFontプロパティを使うためです。 Formではなくobject型のままではFormクラスのプロパティにアクセスすることはできません。

tranceporter
質問者

お礼

回答ありがとうございます。 検証プログラムをいろいろやってみて大変勉強になりました。 もう少しC#の挙動を理解する必要があるようです。 またよろしくお願いいたします。

tranceporter
質問者

補足

ありがとうございます。Fontプロパティを使うためのキャスト、理解しました。 もう少し質問させてください。その右側にある object objsender のobjectという型は すべてのクラスのルートであるという System.Object のObjectの部分でしょうか? 先頭が小文字なので別物でしょうか? つまりobjsender はどんなものにもキャスト可能、と思って良いですか?

関連するQ&A

  • Graphicsプロパティ

    例えば using System; using System.Drawing; using System.Windows.Forms; class SeparateMain { public static void Main() { Application.Run(new AnotherHelloWorld()); } } class AnotherHelloWorld : Form { public AnotherHelloWorld() { Text = "Another Hello World"; BackColor = Color.White; } protected override void OnPaint(PaintEventArgs pea) { Graphics grfx = pea.Graphics; grfx.DrawString("Hello, windows Forms!", Font, Brushes.Black, 0, 0); } } の中の Graphics grfx = pea.Graphics; という部分なのですが、この部分はなぜ必要で、何をしてるのでしょう。 GDI+というのでしょうか System.Drawing.Graphicsというクラスのインスタンス、grfxを定義して、 PaintEventArgsのインスタンスpeaのGraphicsプロパティを代入 この処理が必要な理由がわかりません。お願いします。

  • C# フォームプログラミングで

    public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { //Graphics grfx = CreateGraphics(); } private void Form2_Paint(object sender, PaintEventArgs e) { Form2 form2; form2.Paint += new PaintEventHandler(PaintHandler1); } static void PaintHandler1(object objSender,PaintEventArgs e) { Graphics grfx = e.Graphics; grfx.DrawString("test",Font font,Brushes.Black,0,0);//←ここでエラー } } このように書くと「引数を2個指定できる、メソッド DrawString のオーバーロードはありません」 というエラーがでてフォームに文字を表示できません 最初に「空のプロジェクト」で作れば普通にDrawStringで文字を表示できるのですが 「Windowsフォーム」を選んでからだと表示できないのはなぜでしょうか? 何がいけないのでしょう。

  • VC# 追加フォーム生成時、フォームに描画できない

    前略 ・VC#(.NET 2008)のプログラムでおしえてください。 ・メインのWindowsフォームからボタンクリックで 追加したサブWindowsフォーム上のピクチャーボックス上に何も操作なしでに描画したいのですができません。CreateGraphics()でオブジェクトを生成して描画しています。どのようにしたらよいのかおしえてください。フォームのイベントとして、Paint,Load,shown,Activated等いろいろやってもだめでした。  尚、サブフォームにボタンをもうけ このメソッドの中に描画コマンドを書き、ボタンを操作すると描画できます。下記は円を描こうとしていますが、shapeコンポーネントでは描けな複雑な描画をしたいと思っています。 ・以下に 下記の動作となるソースコードを記載します。 (1)起動するとメインフォームForm1のpictureBox1に 赤い円が描かれる (2)ボタンbutton1をクリックするとForm2が表示される。  Form2上のラベルlabel1とlabel2の文字色は青色に変わっています。  しかし、円は何故か描かれていません (3)Form2上のボタンをクリックすると赤い円がForm2上に描かれます。  どこをどのように直せば追加のサブフォームForm2が表示された時に Form2上のpictureBox1に円が描がかれているのでしょうか。以上、よろしくお願いします //----------------------------------------------------------- //メインフォーム using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace temp2 { public partial class Form1 : Form { public Form1(){ InitializeComponent(); } private void button1_Click(object sender, EventArgs e){ Form2 form2 = new Form2(); form2.ShowDialog(); } private void Form1_Paint(object sender, PaintEventArgs e){ Graphics g = pictureBox1.CreateGraphics(); g.DrawEllipse(Pens.Red, 0, 0, 200, 200); } } } //サブフォーム using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace temp2 { public partial class Form2 : Form { public Form2(){ InitializeComponent(); } private void pictureBox1_Paint(object sender, PaintEventArgs e){ label1.ForeColor = Color.Blue; Graphics g1 = pictureBox1.CreateGraphics(); g1.DrawEllipse(Pens.Blue, 0, 0, 50, 50); label2.ForeColor = Color.Blue; } private void button1_Click(object sender, EventArgs e){ Graphics g2 = pictureBox1.CreateGraphics(); g2.DrawEllipse(Pens.Blue, 0, 0, 50, 50); } private void Form2_Paint(object sender, PaintEventArgs e){ } private void Form2_Load(object sender, EventArgs e){ } private void Form2_Shown(object sender, EventArgs e){ } } } 以上

  • C#で派生クラスから描画処理を行う

    C#を勉強しているのですが、GUIを作り初めて描画処理で分からない所があり、質問させて頂きます。 基本クラスの方で「Hello, world!」という文字列をDrawStringで表示させる事は出来たのですが、それを基本クラスを継承した派生クラスのメソッドで行うと何も表示されないんです。 以下が試したコードです。 //基本クラスSample1 using System; using System.Drawing; using System.Windows.Forms; public class Sample1 : Form {   protected Bitmap image; protected Graphics g; protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Sample2 s = new Sample2(); s.helloworld(); e.Graphics.DrawImage(image, 0, 0); } public Sample1() { SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true); image = new Bitmap(600, 400); g = Graphics.FromImage(image); } static void Main() { Form form = new Sample1(); form.Text = "sample"; form.ClientSize = new Size(600, 400); form.BackColor = Color.FromArgb(0xff, 0xff, 0xff); Application.Run(form); } } //派生クラスSample2 using System; using System.Drawing; using System.Windows.Forms; public class Sample2 : Sample1 { Brush brush = new SolidBrush(Color.Black); public void helloworld() { g.DrawString("Hello, world!", this.Font, brush, 10, 10); } } なぜ表示されないのか分かる方いらしたら、ご教授願えないでしょうか。是非お願いします。

  • Form1で宣言したインスタンスをForm2で使う

    開発環境はMicrofoft visual stdio 2005 で開発言語はC#を使い、Windousアプリケーションでプログラミングしているのですが、あるフォームで宣言したインスタンスを別のフォームで使う方法がわかりません。具体的にソースコードで説明すると using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace tesuto {   public partial class Form1 : Form   {     class Car     {       public int a;     }     public void Form1_Load(object sender, EventArgs e)     {       Car bike = new Car();//ここで宣言したインスタンスを       bike.a = 10;       Form2 fm2 = new Form2(this);       fm2.Show();     }   }   public partial class Form2 : Form   {     public void Form2_Load(object sender, EventArgs e)     {       int b;       b = bike.a;//ここでこのように使いたい     }   } } ということです。 前も似たような質問をさせていただき、たくさんの回答をいただいたにも関わらず自分のプログラム能力が低く、理解できませんでした><。なのでよければ、回答は言葉だけではなくこの上のソースコードを基にして(コピペ貼り付けなどで)、すこしでいいですのでソースコードを書いていただけませんでしょうか。 また、プログラミングを初めてまだ間もないので、すこし初心者向けでお願いします。 質問する側なのに色々要求をして申し訳ないのですが、もし御面倒でなければ御回答をお待ちしております。 よろしくおねがいします。 

  • C#のGraphicsクラスについて(GDI+)

    以下のようにgraphicsクラスをつかった画像の描画をおこないました。 Graphics gr = Graphics.FromImage(mapObj); というふうにからのリソースからGraphicsオブジェクトをつくる方法です。 using System; using System.IO; using System.Windows.Forms; using System.Drawing; using System.Web; using System.Net; using System.Text; using System.Threading; using System.ComponentModel; public class MainClass{ public static void Main(string [] args){ NewForm formObj = new NewForm(); formObj.RenderMethod(); Application .Run(formObj); } } public class NewForm : Form{ public NewForm(){ this.Width = 500; this.Height = 500; } public void RenderMethod(){ Bitmap mapObj = new Bitmap(500,500); Graphics gr = Graphics.FromImage(mapObj); Image imageObj = Image.FromFile("C:\\test.jpg"); gr .DrawImage(imageObj, 0,0,150,150); this.BackgroundImage = mapObj; } } このほかに、フォームコントロールの thisl.CreateGraphics()という メソッドを使っても画像を描画できるとききました。 あるサンプルをみると public class NewForm : Form{ public NewForm(){ this.Width = 500; this.Height = 500; } public void RenderMethod(){ Graphics gr = this.CreateGraphics(); Image imageObj = Image.FromFile("C:\\test.jpg"); gr .DrawImage(imageObj, 0,0,150,150); } } とこのようにthis.CreateGraphics()をつかっていましたが 実際にはこれが描画されないのです。 Graphics gr = Graphics.FromImage(mapObj); というGraphicsクラスの静的メソッドを使う方法ではなく コントロールのCreateGraphicsメソッドをつかって描画するにはどうしたらよいのですか? 識者のかた、ご教授ください。

  • キャストの仕方がわかりません

    キャストの仕方がわかりません メソッド内でクラスを生成し、 そのクラスで共通処理を行いたいのですが、上手くいきません。 ジェネリクスの使い方が悪いのか、キャストで怒られてしまいます。 お分かりの方、いらっしゃいましたら教授願えますか。 以下、ソースです。 interface ToolInterface { /** 結果 */ public abstract Object toolResult(); } class TestA implements ToolInterface{ @Override public Object toolResult() { return "Aです"; } } class TestB implements ToolInterface{ @Override public Object toolResult() { return "Bです"; } } public class TestMain { public static void main(String args[]) { TestMain me = new TestMain(); me.dispResult(TestA.class); me.dispResult(TestB.class); } /** このメソッドでインスタンス化及び処理を行う */ private void dispResult(Class<?> obj) { try { obj.newInstance(); //ここでキャストか何かして表示させたい ToolInterface resObj = (ToolInterface) obj; System.out.println(resObj.toolResult()); } catch (InstantiationException e) { } catch (IllegalAccessException e) { } } }

    • ベストアンサー
    • Java
  • 他クラスからForm1にアクセス

    Class1からForm1のtextBox1にアクセスする件、oboroxxさんの明快な回答を 参考にしまして、何とか下記の様にコードの実装が出来ました。 初めての事ですから、コメント頂けますと、大変有難いです。 追加質問: Q1) button1_Clickの中に、『Class1 obj=new Class1();』があります。 ここで、newで作られました、objはGCの対象になりますか? いや、そうではなく、button1_Clickが終了すると、objは消滅しますか? お手数ですが、宜しくお願いします。 ============================ using System; using System.Windows.Forms; namespace TT_SendMessage { public partial class Form1:Form { public Form1() { InitializeComponent(); } public void write_textBox1(string str){ textBox1.Text=str; //<---OK Console.WriteLine("VVVVVVVVVVVVVv"); } private void button1_Click(object sender,EventArgs e) { Class1 obj=new Class1(); obj.fm1_pr=this; obj.bbb(); //write_textBox1("aaa"); //<---OK } }// public partial class Form1:Form { //================ class Class1 { private Form1 fm1=new Form1(); public Form1 fm1_pr { set { this.fm1=value;} get { return this.fm1;} }//Form1 fm1 public void bbb() { fm1.write_textBox1("bbb");//non_static } }//class Class1 { //================ } 以上、宜しくお願いします。

  • なぜprotected overrideなのか

    C#でわからないことが2,3あるのですが、このmsndのサンプルで public class FirstControl : Control{ public FirstControl() {} protected override void OnPaint(PaintEventArgs e) { // Call the OnPaint method of the base class. base.OnPaint(e); // Call methods of the System.Drawing.Graphics object. e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), ClientRectangle); } } これのprotected override void OnPaint(PaintEventArgs e){} の部分なのですが、なぜprotected overrinde修飾子なのでしょう 何をオーバーライドしてるのですか?他のサンプルにも構文のように出てくるのですが。 あとOnPaintはメソッドのようですがイベントを発生させるにはデリゲートではないのでしょうか あとPaintEventArgsはクラスということですがnewはいらないのでしょうか。staticがどこかにあるのでしょうか よろしくお願いします。

  • C#のGraphicsクラスについてです。

    C#のGraphicsクラスを用いて画像をフェードインで表示させよとしています。 まず以下のコードをごらんください。 ただ、フェードインで画像は表示されるものの、フォームの操作が一切できなくなってしまいます。 そのためマルチスレッドにしようとしたのですが using System; using System.IO; using System.Windows.Forms; using System.Drawing; using System.Web; using System.Net; using System.Text; using System.Threading; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Diagnostics; public class MainClass{ public static void Main(string [] args){ NewForm formObj = new NewForm(); Application .Run(formObj); } } public class NewForm : Form { //インスタンス変数の宣言 public Graphics g ; public Bitmap mapObj ; public Image imageObj; public ImageAttributes ia; public ColorMatrix cm; public Thread th ; public ParameterizedThreadStart ts; public PaintEventArgs e; public Rectangle rec; public int flag = 0; public delegate void TestDelegate(); public TestDelegate deleObj; public NewForm(){ Button buttonObj = new Button(); buttonObj.Width=100; buttonObj.Height = 30; //フェードさせるためのイベント発行用ボタンの設置 buttonObj.Click += new EventHandler(this.SetMethod); this.Controls.Add(buttonObj); } public void SetMethod(object sender , EventArgs e){ this.Paint += new PaintEventHandler(this.ThreadMethod); //フォームコントロールの再描画を促す this.Invalidate(); } public void ThreadMethod(object sender ,PaintEventArgs eventObj){ this.ts = new ParameterizedThreadStart(this.ThreadRenderMethod); this.th = new Thread(this.ts); this.th.Start(eventObj); MessageBox.Show("ThreadMethod実行後"); MessageBox.Show(InvokeRequired.ToString()); this.th.Join(); } public void ThreadRenderMethod(object paintObj){ MessageBox.Show(InvokeRequired.ToString()); this.deleObj =delegate(){ //無現ループしてしまうので、再描画イベント後イベントハンドラーを削除 this.Paint -= new PaintEventHandler(this.ThreadMethod); PaintEventArgs e = (PaintEventArgs)paintObj; try{ Console.WriteLine("paint メソッド発生"); this. g = e.Graphics; this.mapObj = new Bitmap(this.Width,this.Height); this.imageObj = Image.FromFile("C:\\c#\\test.jpg"); //this.g = Graphics.FromImage(this.mapObj); this.cm = new ColorMatrix(); this.cm.Matrix00 = 1; this.cm.Matrix11 = 1; this.cm.Matrix22 = 1; this.cm.Matrix33 = 0.0F; this.cm.Matrix44 = 1; this.ia = new ImageAttributes(); this.ia.SetColorMatrix(this.cm); this.rec = new Rectangle(0, 0, this.Width, this.Height); this.g.DrawImage(this.imageObj,rec,0,0,this.imageObj.Width,imageObj.Height,GraphicsUnit.Pixel,this.ia); this.BackgroundImage = mapObj; for(double i = 0.0; i <= 1.0; i = i + 0.001){ this.cm.Matrix33 = (float) i; this.ia.SetColorMatrix(this.cm); this.g.DrawImage(this.imageObj,rec,0,0,this.imageObj.Width,imageObj.Height,GraphicsUnit.Pixel,this.ia); this.BackgroundImage = this.mapObj; Thread.Sleep(100); } //this.imageObj.Dispose(); //this.g.Dispose(); }catch(Exception ex){ Console.WriteLine(ex.ToString()); } Console.WriteLine("paint end"); }; this.deleObj(); //this.Invoke(this.deleObj); this.BackgroundImage = Image.FromFile("C:\\c#\\test.jpg"); } } 上記コードでも、フェードは動作するものの、やはりフォームの操作ができなくなります。 どう対処したらよいでしょうか? 識者の方、よろしくご教授ください お願いいたします