私は C# の初心者ですが、Head Start C# のチュートリアル ブックをゆっくりと読んでいます (そして、これまでのところ非常に楽しいと感じています)。ただし、最初の「ラボ」課題で壁にぶつかりました。PictureBox を制御するためのコードが提供され、そのコードをメイン フォームで動作させることはできますが、クラス内から動作させることはできません。 . 私は古いレッスンに戻って、何が欠けているかについてかなり良い考えを持っていますが、私の人生では、クラス内からメインフォームのPictureBoxにアクセスする方法を理解できません(チュートリアルが私がすべきだと言っているように)。
私は本をまったく先に進めていなかったので、少しイライラしますが、これはまだカバーしていないことを誓います. とにかく、本物のプログラマーには魅力的です。
チュートリアルで提供されているコードは次のとおりです。「オブジェクトはフォーム上のものを制御できます」(本を持っている人は p208) というセクションにあります。
Point p = MyPictureBox.Location
p.x += distance;
MyPictureBox.Location = p
以下に、コードの関連する (私が思うに?) 部分を投稿します。Button1 はコンパイル時に機能し、Button2 は「機能」します。つまり、現在のクラスは、渡された INT を出力するように指示するだけです。これは、機能しないコードをコメントアウトしたためです。
前もって感謝します!
Form1 のコード:
//
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;
// Namespaces I'll need.
namespace Troubleshooting_PicBoxes
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); // Start all the Form1 stuff (all IDE-generated)
}
private void button1_Click(object sender, EventArgs e) //method from clicking the first button
{
int distance = 5; // Create this variable called "distance"
Point BoxMovement = MyPictureBox.Location; //create a point called BoxMovement
BoxMovement.X += distance; // Adjust the X of BoxMovement by my distance int.
MyPictureBox.Location = BoxMovement; // now adjust the Box by the Point's location.
}
private void button2_Click(object sender, EventArgs e)
{
PicMover PicMoverObject1 = new PicMover(); // Reserve Space for&Create object
PicMoverObject1.MoveThatPic(5); // Execute Object Method with a value of 5
}
}
}
PicMover クラスのコード:
//
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 Troubleshooting_PicBoxes
{
class PicMover
{
public void MoveThatPic(int distance) // New method,
// takes a variable called Distance.
{
MessageBox.Show(distance.ToString()); // Just show us that Variable.
// I need to be able to access Form1's picture box before I can use this. :(
/* Point BoxMovement = MyPictureBox.Location; //create a point called BoxMovement
BoxMovement.X += distance; // Adjust the X of that by distance.
MyPictureBox.Location = BoxMovement; // now adjust the Box by the Point's location.
*/
}
}
}