我有一个C ++ CLI项目,创建了一个新的UI。 想法是打开此UI并画一条线或显示图片。 如果我在InitializeComponent()之后直接调用绘画方法;或在drawWindow_Load方法内-没有成功。如果我添加一个按钮并调用完全相同的方法,则可以看到油漆。我想念什么? .h文件:
#pragma once
namespace UserInterface {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
public ref class drawWindow : public System::Windows::Forms::Form
{
public:
drawWindow(void)
{
InitializeComponent();
paintIt();
}
protected:
~drawWindow()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Button^ button1;
protected:
private:
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
void InitializeComponent(void)
{
this->button1 = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// button1
//
this->button1->Location = System::Drawing::Point(-1, -1);
this->button1->Name = L"button1";
this->button1->Size = System::Drawing::Size(75, 23);
this->button1->TabIndex = 1;
this->button1->Text = L"button1";
this->button1->UseVisualStyleBackColor = true;
this->button1->Click += gcnew System::EventHandler(this, &drawWindow::button1_Click);
//
// drawWindow
//
this->AutoScaleDimensions = System::Drawing::SizeF(9, 20);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(278, 244);
this->Controls->Add(this->button1);
this->Name = L"drawWindow";
this->Text = L"drawWindow";
this->Load += gcnew System::EventHandler(this, &drawWindow::drawWindow_Load);
this->ResumeLayout(false);
}
#pragma endregion
private: System::Void drawWindow_Load(System::Object^ sender, System::EventArgs^ e) {
//paintIt();
}
public: System::Void paintIt();
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e);
};
}
和cpp文件:
#include "stdafx.h"
#include "drawWindow.h"
System::Void UserInterface::drawWindow::paintIt()
{
Graphics ^ pg = CreateGraphics();
Pen ^ red_pen = gcnew Pen(Color::Red);
pg->DrawLine(red_pen, 30, 30, 350, 350);
delete pg;
}
System::Void UserInterface::drawWindow::button1_Click(System::Object^ sender, System::EventArgs^ e) {
paintIt();
}
答案 0 :(得分:0)
以下代码通过覆盖paint函数在我的窗体上绘制一个矩形(将矩形更改为直线应该很容易-即使用g-> DrawLine代替g-> DrawRectangle):-
virtual Void Form1::OnPaint(PaintEventArgs^ pe) override
{
Graphics^ g = pe->Graphics;
g->Clear(Color::AntiqueWhite);
Pen^ redPen = gcnew Pen(Color::Red, 3.0f);
// Draw rectangle to screen.
g->DrawRectangle(redPen, 500, 595, 100, 100);
}
如果表单上存在其他控件,则这些控件将显示在矩形的前面。