I am trying to use the save file dialog in a windows forms project of mine. When trying to save a file I use the showDialog() method and it throws a System.AccessViolationError. The initial directory of the save file dialog isn't set so I don't see why there is an access violation. Here's the code I wrote for using the save file dialog:
var imageSaver = new SaveFileDialog();
imageSaver.Filter = fileType + " File|*." + fileType;
imageSaver.Title = "Save Image";
if (imageSaver.ShowDialog() == DialogResult.OK)
{
b.Save(imageSaver.FileName, imgFormat);
Close();
}
This block of code is used in an event for when a button is clicked, however, after a bit of testing, I found out that the same code works when used in the constructor of the form and in the load event of the form.
Here is the entire class:
using System.Drawing.Imaging;
namespace Pixart
{
public partial class ImageGenerator : Form
{
int width;
int height;
Cell[,] cells;
ImageFormat imgFormat;
string fileType;
bool useMultiplier;
public ImageGenerator(string fileType, ImageFormat imgFormat, Cell[,] cells, int width, int height)
{
InitializeComponent();
this.width = width;
this.height = height;
this.cells = cells;
this.imgFormat = imgFormat;
this.fileType = fileType;
titleLabel.Text = "Export " + fileType.ToUpper();
widthNumber.Minimum = width;
widthNumber.Increment = width;
widthNumber.Maximum = (4000 / width) * width;
heightNumber.Minimum = height;
heightNumber.Increment = height;
heightNumber.Maximum = (4000 / height) * height;
if (heightNumber.Maximum / height < widthNumber.Maximum / width)
multiplierNumber.Maximum = heightNumber.Maximum / height;
else
multiplierNumber.Maximum = widthNumber.Maximum / width;
widthLabel.ForeColor = SystemColors.ControlDarkDark;
heightLabel.ForeColor = SystemColors.ControlDarkDark;
sizeLabel.ForeColor = SystemColors.ControlDarkDark;
multiplierLabel.ForeColor = SystemColors.ControlText;
useMultiplier = true;
//The code works here for some reason
//var imageSaver = new SaveFileDialog();
//imageSaver.Filter = fileType + " File|*." + fileType;
//imageSaver.Title = "Save Image";
//if (imageSaver.ShowDialog() == DialogResult.OK)
//{
//}
}
private void ImageGenerator_Load(object sender, EventArgs e)
{
//The code also works here
//var imageSaver = new SaveFileDialog();
//imageSaver.Filter = fileType + " File|*." + fileType;
//imageSaver.Title = "Save Image";
//if (imageSaver.ShowDialog() == DialogResult.OK)
//{
//}
}
private void multiplierNumber_ValueChanged(object sender, EventArgs e)
{
widthLabel.ForeColor = SystemColors.ControlDarkDark;
heightLabel.ForeColor = SystemColors.ControlDarkDark;
sizeLabel.ForeColor = SystemColors.ControlDarkDark;
multiplierLabel.ForeColor = SystemColors.ControlText;
useMultiplier = true;
}
private void widthNumber_ValueChanged(object sender, EventArgs e)
{
widthLabel.ForeColor = SystemColors.ControlText;
heightLabel.ForeColor = SystemColors.ControlText;
multiplierLabel.ForeColor = SystemColors.ControlDarkDark;
sizeLabel.ForeColor = SystemColors.ControlText;
useMultiplier = false;
widthNumber.Value = (widthNumber.Value / width) * width;
}
private void heightNumber_ValueChanged(object sender, EventArgs e)
{
widthLabel.ForeColor = SystemColors.ControlText;
heightLabel.ForeColor = SystemColors.ControlText;
multiplierLabel.ForeColor = SystemColors.ControlDarkDark;
sizeLabel.ForeColor = SystemColors.ControlText;
useMultiplier = false;
heightNumber.Value = (Convert.ToInt32(heightNumber.Value) / height) * height;
}
private void saveButton_Click(object sender, EventArgs e)
{
int imageWidth = width * Convert.ToInt32(multiplierNumber.Value);
int imageHeight = height * Convert.ToInt32(multiplierNumber.Value);
if (!useMultiplier)
{
imageWidth = Convert.ToInt32(widthNumber.Value);
imageHeight = Convert.ToInt32(heightNumber.Value);
}
using (Bitmap b = new Bitmap(imageWidth, imageHeight))
{
for (int r = 0; r < height; r++)
{
for (int c = 0; c < width; c++)
{
for (int y = 0; y < imageHeight / height; y++)
{
for (int x = 0; x < imageWidth / width; x++)
{
b.SetPixel((c * (imageWidth / width)) + x, (r * (imageHeight / height)) + y, cells[c, r].Colour);
}
}
}
}
var imageSaver = new SaveFileDialog();
imageSaver.Filter = fileType + " File|*." + fileType;
imageSaver.Title = "Save Image";
//line after this throws an error
if (imageSaver.ShowDialog() == DialogResult.OK)
{
b.Save(imageSaver.FileName, imgFormat);
Close();
}
}
}
private void cancelButton_Click(object sender, EventArgs e)
{
Close();
}
private void ImageGenerator_Deactivate(object sender, EventArgs e)
{
Close();
}
}
}
The error message System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory in your code is occurring because the Form Deactivate event occurs when the SaveFileDialog opens.
The issue is due to the following code:
private void ImageGenerator_Deactivate(object sender, EventArgs e)
{
Close();
}
Solution: Remove Close() (or comment it out)
private void ImageGenerator_Deactivate(object sender, EventArgs e)
{
}
Related
I want to make a bitmap and save it and display it. I can display it but I cannot save it.
I get this runtime error : System.Runtime.InteropServices.ExternalException: 'A generic error occurred in GDI+.'
I am even using using and I still get that error
private void button1_Click(object sender, EventArgs e)
{
byte[] returndata = new byte[7057600];
for (int x = 0; x < returndata.Length; )
{
returndata[x] = 255;
returndata[x + 1] = 255;
returndata[x + 2] = 0;
returndata[x + 3] = 0;
x = x + 4;
}
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
saveFileDialog1.Filter = "Bitmaps|*.bmp";
Bitmap temp = null;
temp = InttoBitmap(returndata);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string location = saveFileDialog1.FileName;
temp.Save(location, ImageFormat.Bmp);
pictureBox1.Image = temp;
}
}
}
int keepWidth = 3208;
int keepHeight = 2200;
public Bitmap InttoBitmap(byte[] array)
{
unsafe
{
IntPtr pixptr = Marshal.AllocHGlobal(keepWidth * keepHeight * 4);
Marshal.Copy(array, 0, pixptr, keepWidth * keepHeight);
Bitmap bitmap = new Bitmap(keepWidth, keepHeight, 2 * keepWidth, System.Drawing.Imaging.PixelFormat.Format24bppRgb, pixptr);
return bitmap;
}
}
I am working modifying an application that will be an utility. The application is designed so far to load pictures from any folder and show them in thumbnails, then the user should be able to select those that will want to save in a database. The thumbnails consists of an ImageViewer form that will load each image. Thus, in the ImageViewer form there is a textbox and a checkbox. Each of them will be generated dynamically as many pictures are loaded (see the image below). The problem is that when clicking the checkbox it should show the name listed above the picture (thumbnail textbox) of the file in a label (it can be a label or textbox). Any time when the user clicks the checkbox will see a message saying: 'Added anyImage.jpg' or when deselecting the checkbox will say 'Removed anyImage.jpg'. It is not showing the text in the label. I have the following code.
This code is to load the main form:
public MainForm()
{
InitializeComponent();
Login loginSystem = new Login();
lbHowMany.Visible = false;
lbHowMany.Text = "Images";
lbNumberOfFiles.Visible = false;
btnEnableViewer.Text = "Disable Viewer";
this.buttonCancel.Enabled = false;
//stripSelectedFile.Text = "";
m_ImageDialog = new ImageDialog();
m_AddImageDelegate = new DelegateAddImage(this.AddImage);
m_Controller = new ThumbnailController();
m_Controller.OnStart += new ThumbnailControllerEventHandler(m_Controller_OnStart);
m_Controller.OnAdd += new ThumbnailControllerEventHandler(m_Controller_OnAdd);
m_Controller.OnEnd += new ThumbnailControllerEventHandler(m_Controller_OnEnd);
if (ImageViewer.sendSelectedFile != null)
{
stripSelectedFile.Text = ImageViewer.sendSelectedFile.ToString();
txInformation.Text = ImageViewer.sendSelectedFile.ToString();
}
}
This other code is from the ImageViewer form checkbox:
public void cboxToSave_CheckedChanged(object sender, EventArgs e)
{
if (cboxToSave.Checked == true)
{
sendSelectedFile = "Added: " + txFileName.Text;
}
else
{
{
sendSelectedFile = "Removed: " + txFileName.Text;
}
}
}
This is the variable declared in the class that will send the selected file name to the main form: public static string sendSelectedFile;
ImageViewer Code:
public partial class ImageViewer : UserControl
{
private Image m_Image;
private string m_ImageLocation;
private bool m_IsThumbnail;
private bool m_IsActive;
public static string sendSelectedFile;
public ImageViewer()
{
m_IsThumbnail = false;
m_IsActive = false;
InitializeComponent();
}
public Image Image
{
set
{
m_Image = value;
}
get
{
return m_Image;
}
}
public string ImageLocation
{
set
{
m_ImageLocation = value;
}
get
{
return m_ImageLocation;
}
}
public bool IsActive
{
set
{
m_IsActive = value;
this.Invalidate();
}
get
{
return m_IsActive;
}
}
public bool IsThumbnail
{
set
{
m_IsThumbnail = value;
}
get
{
return m_IsThumbnail;
}
}
public void ImageSizeChanged(object sender, ThumbnailImageEventArgs e)
{
this.Width = e.Size;
this.Height = e.Size;
this.Invalidate();
}
public void LoadImage(string imageFilename, int width, int height)
{
Image tempImage = Image.FromFile(imageFilename);
m_ImageLocation = imageFilename;
//gets the name of the file from the location
txFileName.Text = Path.GetFileNameWithoutExtension(imageFilename);
int dw = tempImage.Width;
int dh = tempImage.Height;
int tw = width;
int th = height;
double zw = (tw / (double)dw);
double zh = (th / (double)dh);
double z = (zw <= zh) ? zw : zh;
dw = (int)(dw * z);
dh = (int)(dh * z);
m_Image = new Bitmap(dw, dh);
Graphics g = Graphics.FromImage(m_Image);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(tempImage, 0, 0, dw, dh);
g.Dispose();
tempImage.Dispose();
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
if (g == null) return;
if (m_Image == null) return;
int dw = m_Image.Width;
int dh = m_Image.Height;
int tw = this.Width - 8; // remove border, 4*4
int th = this.Height - 8; // remove border, 4*4
double zw = (tw / (double)dw);
double zh = (th / (double)dh);
double z = (zw <= zh) ? zw : zh;
dw = (int)(dw * z);
dh = (int)(dh * z);
int dl = 4 + (tw - dw) / 2; // add border 2*2
int dt = 4 + (th - dh) / 2; // add border 2*2
g.DrawRectangle(new Pen(Color.Yellow), dl, dt, dw, dh);
if (m_IsThumbnail)
for (int j = 0; j < 3; j++)
{
//draws and color the horizontal line in the miniature
g.DrawLine(new Pen(Color.LightSalmon),
new Point(dl + 3, dt + dh + 1 + j),
new Point(dl + dw + 3, dt + dh + 1 + j));
//draws and color the vertical right line in the miniature
g.DrawLine(new Pen(Color.LightGreen),
new Point(dl + dw + 1 + j, dt + 3),
new Point(dl + dw + 1 + j, dt + dh + 3));
}
g.DrawImage(m_Image, dl, dt, dw, dh);
if (m_IsActive)
{
//draws the rectangle inside and gives it color
g.DrawRectangle(new Pen(Color.MediumTurquoise, 1), dl, dt, dw, dh);
//draws the rectangle outside and gives it color
g.DrawRectangle(new Pen(Color.RosyBrown, 2), dl - 2, dt - 2, dw + 4, dh + 4);
}
}
private void OnResize(object sender, EventArgs e)
{
this.Invalidate();
}
public void cboxToSave_CheckedChanged(object sender, EventArgs e)
{
if (cboxToSave.Checked == true)
{
sendSelectedFile = "Added: " + txFileName.Text;
}
else
{
{
sendSelectedFile = "Removed: " + txFileName.Text;
}
}
}
}
Code in the MainForm that adds the images in the flowLayoutPanelMain
delegate void DelegateAddImage(string imageFilename);
private DelegateAddImage m_AddImageDelegate;
private void AddImage(string imageFilename)
{
try
{
// thread safe
if (this.InvokeRequired)
{
this.Invoke(m_AddImageDelegate, imageFilename);
}
else
{
int size = ImageSize;
lbNumberOfFiles.Visible = true;
lbHowMany.Visible = true;
ImageViewer imageViewer = new ImageViewer();
imageViewer.Dock = DockStyle.Bottom;
imageViewer.LoadImage(imageFilename, 256, 256);
imageViewer.Width = size;
imageViewer.Height = size;
imageViewer.IsThumbnail = true;
imageViewer.MouseClick += new MouseEventHandler(imageViewer_MouseClick);
txInformation.Text = imageFilename;
SetProgressBar();
counter++;
lbHowMany.Text = "Images";
lbNumberOfFiles.Text = counter.ToString();
this.OnImageSizeChanged += new ThumbnailImageEventHandler(imageViewer.ImageSizeChanged);
//passes the pictures to the main picture container
this.flowLayoutPanelMain.Controls.Add(imageViewer);
}
}
catch (Exception e)
{
MessageBox.Show("An error has ocurred. Error: " + e, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Here's a quick example of the ImageViewer Form raising a custom event whenever the checkbox is changed:
public partial class ImageViewer : Form
{
public ImageViewer()
{
InitializeComponent();
}
public delegate void dlgImageChecked(ImageViewer sender, string message);
public event dlgImageChecked ImageChecked;
private void cboxToSave_CheckedChanged(object sender, EventArgs e)
{
if (ImageChecked != null)
{
ImageChecked(this, (cboxToSave.Checked ? "Added: " : "Removed: ") + txFileName.Text);
}
}
}
Now, when you create instances of ImageViewer, you need to wire up that event...something like:
// ... in your MainForm class ...
private void button1_Click(object sender, EventArgs e)
{
// when you create your instances of ImageViewer, wire up their ImageChecked() event:
ImageViewer iv = new ImageViewer();
iv.ImageChecked += Iv_ImageChecked;
}
private void Iv_ImageChecked(ImageViewer sender, string message)
{
ImageViewer iv = (ImageViewer)sender; // if you need to reference it for other reasons ...
stripSelectedFile.Text = message;
txInformation.Text = message;
}
Your original post didn't show the creation of your ImageViewer instances so you'll need to incorporate the above somehow into your code.
This is the scroll event
int countver = 0;
int counthor = 0;
Image newImage;
private void trackBar2_Scroll(object sender, EventArgs e)
{
if (files != null && files.Length > 0)
{
newImage = Image.FromFile(files[files.Length - 1]);
float imghorizontal = newImage.HorizontalResolution;
float imgvertical = newImage.VerticalResolution;
if (trackBar2.Value < trackBar2.Maximum)
{
countver += 100;
counthor += 100;
}
if (trackBar2.Value == trackBar2.Maximum)
{
countver += 100;
counthor += 100;
}
pictureBox1.Image = ResizeImage(files[files.Length - 1], (int)imghorizontal + counthor, (int)imgvertical + countver);
label15.Text = (int)imghorizontal + counthor.ToString() + "," + (int)imgvertical + countver.ToString();
label15.Visible = true;
}
}
This is the method Resize Image
private static Bitmap ResizeImage(String filename, int maxWidth, int maxHeight)
{
using (Image originalImage = Image.FromFile(filename))
{
//Caluate new Size
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
if (newWidth >= 0 && newHeight >= 0)
{
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
//--Quality Settings Adjust to fit your application
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
return newImage;
}
}
return null;
}
}
The problem is when i move the scroll up or down it's taking a 1-3 seconds to make the image process. And if i move the scroll up faster to another value it's taking even more(another vlaue i mean i'm trying to move the slider from the beginning to the end the program hang).
This is the form1 code i'm using a backgroundworker to change the images size on the hard disk. The whole idea is to give the user a preview of how the image/s will look like and then if he decide it's good enough he click a button that start the backgroundworker.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace Images_Batch_Resize
{
public partial class Form1 : Form
{
OpenFileDialog openFileDialog1;
string[] files;
string directoryPath;
public Form1()
{
InitializeComponent();
label6.Visible = false;
label7.Visible = false;
label8.Visible = false;
label9.Visible = false;
label10.Visible = false;
label12.Visible = false;
label15.Visible = false;
openFileDialog1 = new OpenFileDialog();
trackBar2.Minimum = 0;
trackBar2.Maximum = 20;
}
private void changeWorkingDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff|"
+ "All Graphics Types|*.bmp;*.jpg;*.jpeg;*.png;*.tif;*.tiff";
//openFileDialog1.InitialDirectory = #"c:\";
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Multiselect = true;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
files = openFileDialog1.FileNames;
try
{
if (files.Length > 0)
{
label6.Text = files.Length.ToString();
label6.Visible = true;
directoryPath = Path.GetDirectoryName(files[0]);
label12.Text = directoryPath;
label12.Visible = true;
pictureBox2.Load(files[0]);
pictureBox1.Load(files[0]);
trackBar1.Minimum = 0;
trackBar1.Maximum = files.Length - 1;
}
}
catch (IOException)
{
}
}
}
private void beginOperationToolStripMenuItem_Click(object sender, EventArgs e)
{
if (files.Length > 0)
{
backgroundWorker1.RunWorkerAsync();
}
}
private static Bitmap ResizeImage(String filename, int maxWidth, int maxHeight)
{
using (Image originalImage = Image.FromFile(filename))
{
//Caluate new Size
int newWidth = originalImage.Width;
int newHeight = originalImage.Height;
double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;
if (aspectRatio <= 1 && originalImage.Width > maxWidth)
{
newWidth = maxWidth;
newHeight = (int)Math.Round(newWidth / aspectRatio);
}
else if (aspectRatio > 1 && originalImage.Height > maxHeight)
{
newHeight = maxHeight;
newWidth = (int)Math.Round(newHeight * aspectRatio);
}
if (newWidth >= 0 && newHeight >= 0)
{
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics g = Graphics.FromImage(newImage))
{
//--Quality Settings Adjust to fit your application
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
return newImage;
}
}
return null;
}
}
int countver = 0;
int counthor = 0;
Image newImage;
private void trackBar2_Scroll(object sender, EventArgs e)
{
if (files != null && files.Length > 0)
{
newImage = Image.FromFile(files[files.Length - 1]);
float imghorizontal = newImage.HorizontalResolution;
float imgvertical = newImage.VerticalResolution;
if (trackBar2.Value < trackBar2.Maximum)
{
countver += 100;
counthor += 100;
}
if (trackBar2.Value == trackBar2.Maximum)
{
countver += 100;
counthor += 100;
}
pictureBox1.Image = ResizeImage(files[files.Length - 1], (int)imghorizontal + counthor, (int)imgvertical + countver);
label15.Text = (int)imghorizontal + counthor.ToString() + "," + (int)imgvertical + countver.ToString();
label15.Visible = true;
}
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
pictureBox1.Load(files[trackBar1.Value]);
pictureBox2.Load(files[trackBar1.Value]);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
BackgroundWorker worker = sender as BackgroundWorker;
int counter = 0;
int percentage = 0;
foreach (string file in files)
{
Bitmap bmp1 = new Bitmap(ResizeImage(file, 300, 300));
string resizedfilename = Path.Combine(directoryPath, Path.GetFileNameWithoutExtension(file) + "_resized.jpg");
bmp1.Save(resizedfilename);
bmp1.Dispose();
counter++;
percentage = counter * 100 / files.Length;
worker.ReportProgress(percentage);
}
}
catch(Exception err)
{
string ttt = err.ToString();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
}
int oldValue = 0;
private void trackBar2_ValueChanged(object sender, EventArgs e)
{
if ((sender as TrackBar).Value >= oldValue)
{
}
else
{
}
oldValue = (sender as TrackBar).Value;
}
}
}
I am making a card guessing game.there are 100 cards place in 10rows and 10 columns each card with a number and user have to find a number he is thinking of. i want to devise an algorithm to determine whether a given number is written on one of the cards by turning up less than 20 cards.I hav created the buttons dynamically, now im having hard time making a logic to search through them.This is my code.
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
int rememberlast = 0, move = 0;
object savelastobject;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int sizee = 50, where = 0;
this.Height = 0;
this.Width = 0;
var generatedNum = new List<int>();
var random = new Random();
while (generatedNum.Count < 100)
{
var tempo = random.Next(0, 100);
if (generatedNum.Contains(tempo)) continue;
generatedNum.Add(tempo);
}
char[] text2 = text.ToCharArray();
for (int x = 0; x < 10; x++)
{
for (int y = 0; y < 10; y++)
{
Button ta = new Button();
ta.Name = x.ToString()+y.ToString();
ta.Width = sizee;
ta.Height = sizee;
ta.Tag = generatedNum[where];
where++;
ta.BackColor = Color.Red;
ta.Location = new Point(70 * y, 70 * x);
Controls.Add(ta);
ta.Click += new System.EventHandler(this.button_Click);
this.Width += 90 * x / 13;
this.Height += 90 * x / 8;
}
}
}
private void button_Click(object sender, EventArgs e)
{
Control me = (Control)sender;
rememberlast = int.Parse(me.Tag.ToString());
savelastobject = me;
me.Text = me.Tag.ToString();
me.Enabled = true;
me.BackColor = Color.Gray;
move++;
label2.Text = move.ToString();
me.Enabled = true;
me.Text = me.Tag.ToString();
me.BackColor = Color.Gray;
me.Refresh();
Thread.Sleep(1000);
if (move == 20)
{
MessageBox.Show("Total Moves Consumed");
Application.Restart();
}
if (me.Tag.ToString() == textBox1.Text)
{
//Control him = (Control)savelastobject;
//him.BackColor = Color.LightBlue;
me.BackColor = Color.LightBlue;
MessageBox.Show("You Win");
Application.Restart();
}
}
}
}
I am developing a GIS application. I want to open a particular form with drawn lines. The form which will open contains a textbox which is showing the length of the line. I am able to select the line. I am able to get the length of the line.
I want to link the form with each line. and the same form should be displayed whenever that line is selected. How can i do it?
should i go for serialization? or is there any good solution?
I know this is GIS related thing, but its more like a C# problem.
Code:
private bool amDigitizing = false;
//Coordiant
private List<DotSpatial.Topology.Coordinate> myDigitizedPoints = new List<DotSpatial.Topology.Coordinate>();
private List<DotSpatial.Topology.Coordinate> myExtractedPoints = new List<DotSpatial.Topology.Coordinate>();
// DEM Layer
private DotSpatial.Controls.MapRasterLayer demLyr;
// Line Layer
private DotSpatial.Controls.MapLineLayer LineLyr;
FormTableEditor ft = new FormTableEditor();
public Form1()
{
InitializeComponent();
appManager1.LoadExtensions();
appManager1.CompositionContainer.ComposeParts(toolManager1);
}
private void map1_MouseMove(object sender, MouseEventArgs e)
{
Coordinate c_mouse = map1.PixelToProj(new System.Drawing.Point(e.X, e.Y));
Xstrip.Text = "X:" + Convert.ToString(c_mouse.X);
Ystrip.Text = "Y:" + Convert.ToString(c_mouse.Y);
}
private void btnDraw_Click(object sender, EventArgs e)
{
try
{
//map1.Layers.Remove(LineLyr);
}
catch
{
// do nothing
}
// Start a Drawing
MessageBox.Show(" Click on the map to draw, double click to stop drawing");
amDigitizing = true;
myDigitizedPoints = new List<DotSpatial.Topology.Coordinate>();
map1.FunctionMode = DotSpatial.Controls.FunctionMode.None;
}
private void map1_MouseClick_1(object sender, MouseEventArgs e)
{
// digitizing
if (amDigitizing == true)
{
DotSpatial.Topology.Coordinate c = new DotSpatial.Topology.Coordinate();
System.Drawing.Point p = new System.Drawing.Point();
p.X = e.X;
p.Y = e.Y;
c = map1.PixelToProj(p);
//double[] s = c.ToArray();
//StartX = s[0];
//StartY = s[1];
myDigitizedPoints.Add(c);
}
}
int NoOfMines = 0;
private void map1_MouseDoubleClick_1(object sender, MouseEventArgs e)
{
// Double click ends digitizing
if (amDigitizing == true)
{
DotSpatial.Topology.Coordinate c = new DotSpatial.Topology.Coordinate();
System.Drawing.Point p = new System.Drawing.Point();
p.X = e.X;
p.Y = e.Y;
c = map1.PixelToProj(p);
myDigitizedPoints.Add(c);
//double[] s = c.ToArray();
//EndX = s[0];
//EndY = s[1];
amDigitizing = false;
DotSpatial.Data.Feature f = new DotSpatial.Data.Feature(DotSpatial.Topology.FeatureType.Line, myDigitizedPoints);
DotSpatial.Data.FeatureSet fs = new DotSpatial.Data.FeatureSet();
fs.AddFeature(f);
NoOfMines = NoOfMines +1 ;
fs.Projection = map1.Projection;
for (int i = 0; i < NoOfMines; i++)
{
fs.Name = "Mine Field" + NoOfMines.ToString();
}
//fs.SaveAs(GraphicsPathExt, true);
//LineLyr = (DotSpatial.Controls.MapLineLayer)map1.AddLayer(GraphicsPathExt);
LineLyr = (MapLineLayer)map1.Layers.Add(fs);
}
}
// Length of the line
private void mnuThin_Click(object sender, EventArgs e)
{
LineLyr.Symbolizer.SetFillColor(Color.Red);
LineLyr.Symbolizer.SetWidth(5.0);
LineLyr.Symbolizer.SetOutline(Color.White, 1.0);
map1.Refresh();
IRaster r = (IRaster)map1.Layers[0].DataSet;
IFeatureSet fs = LineLyr.DataSet;
int np = 0;
try
{
foreach (IFeature f in fs.Features)
{
np += f.Coordinates.Count * 100;
}
}
catch
{
}
double[] plotX = new double[np - 99];
double[] plotY = new double[np - 99];
double x1= 0, y1 = 0, x2 = 0 , y2 = 0 , dx = 0 , dy = 0, newx = 0, newy = 0;
double z = 0;
double TotalLength = 0.0;
int i = 0;
double[] Slope = new double[np / 100];
foreach (IFeature f in fs.Features)
{
foreach (DotSpatial.Topology.Coordinate c in f.Coordinates)
{
x2 = c.X;
y2 = c.Y;
if (i > 0)
{
dx = (x2 - x1) / 100;
dy = (y2 - y1) / 100;
newx = x1;
newy = y1;
for (int j = 0; j < 100; j++)
{
TotalLength += Math.Sqrt(Math.Pow(dx, 2) + Math.Pow(dy, 2));
z = demLyr.DataSet.GetNearestValue(newx, newy);
i += 1;
}
}
x1 = x2;
y1 = y2;
if (i == 0)
{
z = demLyr.DataSet.GetNearestValue(newx, newy);
i += 1;
x1 = x2;
y1 = y2;
}
}
}
//Length of the line
ft.textBox1.Text = TotalLength.ToString();
}
//Selection of layer
private void customizeToolStripMenuItem_Click(object sender, EventArgs e)
{
IMapLayer layerSelect = appManager1.Map.Layers.SelectedLayer;
if (layerSelect == LineLyr)
{
ft.Show();
}
}
As Peter duniho mentioned in the comments of selection change event.
i used that approach to link the form.
DrawObject o = new DrawObject;
Form1 f = new Form1(o);
LegendItem li = new LegendItem();
if (li.IsSelected == true)
{
f.Textbox1.Text = frontage.ToString();
f.show();
}