IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Windows Forms Discussion :

[Débutant] OnPaint NullArgumentException


Sujet :

Windows Forms

  1. #1
    Membre expérimenté

    Homme Profil pro
    Senior Développeur JEE
    Inscrit en
    Avril 2002
    Messages
    795
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : Belgique

    Informations professionnelles :
    Activité : Senior Développeur JEE
    Secteur : Finance

    Informations forums :
    Inscription : Avril 2002
    Messages : 795
    Points : 1 660
    Points
    1 660
    Par défaut [Débutant] OnPaint NullArgumentException
    Bonjour,

    Tout d'abord je développe sous pda en C#, mais ma question n'est pas en rapport direct avec le compactframework, mais avec l'event OnPaint.

    J'utilise on Control qui est utilisé pour signer avec un stylet.

    Voici le code

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    using System;
    using System.Drawing;
    using System.Drawing.Imaging; 
    using System.Windows.Forms;
    using System.Text;
    using System.Collections;
    using System.IO;
    using System.Reflection; 
     
    namespace NIS_2008
    { 
     
    	public class SignatureControl : Control
    	{
     
    		#region Local Variables
     
    		private ArrayList Points = new ArrayList();
    		private Bitmap BackGroundImage;
    		private Graphics GraphicsHandle;
    		private Pen SignaturePen = new Pen(Color.Black);
    		private Point LastMouseCoordinates = new Point(0,0);
    		private bool CaptureMouseCoordinates = false;
    		private string AppPath="";
    		private string ImageFileName="";
    		private string Delimiter=",";
     
     
    		#endregion
     
    		#region Line To Draw
    		private struct LineToDraw
    		{ 
    			public int StartX;
    			public int StartY;
    			public int EndX;
    			public int EndY;
    		}
    		#endregion
     
    		#region Constructor
    		public SignatureControl(string ApplicationPath,string BaseImageFileName)
    		{
    			AppPath = ApplicationPath; 
    			ImageFileName = BaseImageFileName;
    		}
    		#endregion
     
            #region Constructor
            public SignatureControl()
            {
     
            }
            #endregion
     
    		#region On Paint
    		protected override void OnPaint(PaintEventArgs e) 
    		{
                base.OnPaint(e);
                Write2File(BackGroundImage == null, "\\My Documents\\PDA_LOG.log");
    			//LoadBackgroundImageIfInvalid();
                //LoadBackgroundImage();
    			e.Graphics.DrawImage(BackGroundImage, 0, 0);			 
    		}
    		#endregion
     
    		#region On Paint Background
    		protected override void OnPaintBackground(PaintEventArgs e) 
    		{
     
    		}
    		#endregion
     
    		#region On Mouse Down
    		protected override void OnMouseDown(MouseEventArgs e) 
    		{
    			base.OnMouseDown(e);
     
    			if (CaptureMouseCoordinates) { return; }
     
    			CaptureMouseCoordinates = true;
    			LastMouseCoordinates.X = e.X;
    			LastMouseCoordinates.Y = e.Y;
     
    		}
    		#endregion
     
    		#region On Mouse Up
    		protected override void OnMouseUp(MouseEventArgs e) 
    		{
    			base.OnMouseUp(e);
    			CaptureMouseCoordinates = false;	
    		}
    		#endregion
     
    		#region On Mouse Move
    		protected override void OnMouseMove(MouseEventArgs e)
    		{
    			base.OnMouseMove(e);			
     
    			if (!CaptureMouseCoordinates) { return; }
     
    			LineToDraw l = new LineToDraw();
     
    			l.StartX = LastMouseCoordinates.X;
    			l.StartY = LastMouseCoordinates.Y;
    			l.EndX = e.X;
    			l.EndY = e.Y;
     
    			Points.Add(l);
     
    			GraphicsHandle.DrawLine(SignaturePen, l.StartX, l.StartY, l.EndX,l.EndY);
     
    			LastMouseCoordinates.X = l.EndX;
    			LastMouseCoordinates.Y = l.EndY;
     
    			Invalidate();
     
    		}
    		#endregion
     
    		#region Draw Signature
    		public void DrawSignature()
    		{
    			LineToDraw l;
     
    			try
    			{
    				if (Points.Count < 1) { return; } 
     
    				for(int i=0;i<Points.Count;i++)
    				{
    					l = (LineToDraw)Points[i];
    					GraphicsHandle.DrawLine(SignaturePen, l.StartX, l.StartY, l.EndX,l.EndY);
    				}
     
    				Invalidate();
    			}
    			catch (Exception) { throw; }
    		}
    		#endregion
     
    		#region Save
    		public void Save(string FileName)
    		{
    			LineToDraw l;
     
    			try
    			{
    				if (Points.Count < 1) { return; } 
     
    				StreamWriter sw = new StreamWriter(FileName,false);
     
    				for(int i=0;i<Points.Count;i++)
    				{
    					l = (LineToDraw)Points[i];
    					sw.Write(l.StartX.ToString() + Delimiter);
    					sw.Write(l.StartY.ToString() + Delimiter);
    					sw.Write(l.EndX.ToString() + Delimiter);
    					sw.WriteLine(l.EndY.ToString());
    				}
     
    				sw.Close(); 
     
    			}
    			catch (Exception) { throw; }
    		}
    		#endregion
     
    		#region Load
    		public void Load(string FileName)
    		{
    			LineToDraw l;
     
    			try
    			{
     
    				this.Clear(true);
     
    				StreamReader sr = new StreamReader(FileName);
     
    				string line;
     
    				while ((line = sr.ReadLine()) != null)
    				{
     
    					l = new LineToDraw();
     
    					string[] linesplit = line.Split(Delimiter.ToCharArray());
     
    					l.StartX = int.Parse(linesplit[0].ToString());
    					l.StartY = int.Parse(linesplit[1].ToString());
    					l.EndX = int.Parse(linesplit[2].ToString());
    					l.EndY = int.Parse(linesplit[3].ToString());
    					Points.Add(l); 
    				}
     
    				sr.Close(); 
     
    			}
    			catch (Exception) { throw; }
    		}
    		#endregion
     
    		#region Clear
    		public void Clear(bool ClearCapturedLines)
    		{
    			try
    			{
    			 LoadBackgroundImage();
    			 Invalidate();
    			 if (ClearCapturedLines == false) { return; }
    			 Points.Clear();
    			}
    			catch (Exception) { throw; }
    		}
    		#endregion
     
    		#region Load Background Image If Invalid
    		private void LoadBackgroundImageIfInvalid()
    		{
                Write2File("Starting LoadBackgroundImageIfInvalid", "\\My Documents\\PDA_LOG.log");
    		  try
    		  {
                  Write2File(BackGroundImage == null, "\\My Documents\\PDA_LOG.log");
                  /*Write2File("BackGroundImage.Width: " + BackGroundImage.Width + "this.width: "+ this.Width, "\\My Documents\\PDA_LOG.log");
                  Write2File("BackGroundImage.Height: " + BackGroundImage.Height + "this.Height: " + this.Height, "\\My Documents\\PDA_LOG.log");*/
     
    			if (BackGroundImage == null || BackGroundImage.Width != this.Width || BackGroundImage.Height != this.Height)
    			{
    				LoadBackgroundImage();
    			}
    		  }
              catch (Exception ex) { MessageBox.Show(ex.StackTrace); }
    		}
    		#endregion
     
    		#region Load Background Images
    		private void LoadBackgroundImage()
    		{
                Write2File("Starting LoadBackgroundImage", "\\My Documents\\PDA_LOG.log");
    			try
    			{
                    Write2File("Background image path: " + Path.Combine(AppPath, ImageFileName), "\\My Documents\\PDA_LOG.log");
                    Write2File(File.Exists(Path.Combine(AppPath, ImageFileName)), "\\My Documents\\PDA_LOG.log");
    				BackGroundImage = new Bitmap(Path.Combine(AppPath,ImageFileName));   
    				GraphicsHandle = Graphics.FromImage(BackGroundImage);
    			}
                catch (Exception ex) { MessageBox.Show(ex.StackTrace); }
                Write2File("Stopping LoadBackgroundImage", "\\My Documents\\PDA_LOG.log");
    		}
    		#endregion
     
            private void Write2File(string msg, string filePath)
            {
                try
                {
                    System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Append);
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
                    sw.WriteLine(msg);
                    sw.Flush();
                    sw.Close();
                    fs.Close();
                }
                catch (IOException ioe)
                {
                    MessageBox.Show(ioe.StackTrace);
                    Write2File(ioe.StackTrace, "\\My Documents\\PDA_LOG.log");
                }
     
            }
     
            private void Write2File(Boolean msg, string filePath)
            {
                try
                {
                    System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Append);
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
                    sw.WriteLine(msg);
                    sw.Flush();
                    sw.Close();
                    fs.Close();
                }
                catch (IOException ioe)
                {
                    MessageBox.Show(ioe.StackTrace);
                    Write2File(ioe.StackTrace, "\\My Documents\\PDA_LOG.log");
                }
     
            }
     
    	}
     
    }
    L'evenement OnPaint me retourne un NullArgumentException au niveau de la méthode Graphics.DrawImage,

    Pourtant le control est instancié, mais on dirait que le OnPaint est appelé dans une classe non instanciée ce qui me retourne un nullArgument de la variable BackGroundImage.

    Voici la portion de code qui est appelée lorsque l'event SelectedIndexChanged du tabcontrol.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    private void loadNotePersonnelle()
            {
                try
                {
                    this.signatureControlPanel.Controls.Remove(this.signatureControl1);
                    signatureControl1 = new NIS_2008.SignatureControl(AppPath, SignatureBackgroundImageFileName);
                    signatureControl1.Location = signatureControlPanel.Location;
                    signatureControl1.Size = signatureControlPanel.Size;
                    this.signatureControl1.Name = "signatureControl1";
                    this.signatureControl1.Text = "signatureControl1";
                    Cursor.Current = Cursors.WaitCursor;
                    signatureControl1.Clear(true);
                    if(File.Exists(AppPath + "\\" + this.selectedTask + "_NP.txt"))
                    {
                        signatureControl1.Load(Path.Combine(AppPath, this.selectedTask + "_NP.txt"));
                        signatureControl1.DrawSignature();
                        signatureControl1.Refresh();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
     
     
            }
    Je tourne en rond depuis deux jours.

    Si quelqu'un a une solution, elle est la bienvenue.

    Merci d'avance pour vos réponses.
    Langages : Java, SQL
    Outils : Eclipse, Intellij
    SGBD : Oracle, PostgreSQL
    Mes Articles

  2. #2
    Membre émérite Avatar de Guulh
    Homme Profil pro
    Inscrit en
    Septembre 2007
    Messages
    2 160
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Septembre 2007
    Messages : 2 160
    Points : 2 925
    Points
    2 925
    Par défaut
    J'ai pas le courage de tout lire dans le détail, mais si tu rajoutais un (if this.BackGroundImage != null) avant e.Graphics.DrawImage(BackGroundImage, 0, 0);, c'est pas suffisant ?
    ಠ_ಠ

  3. #3
    Membre expérimenté

    Homme Profil pro
    Senior Développeur JEE
    Inscrit en
    Avril 2002
    Messages
    795
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : Belgique

    Informations professionnelles :
    Activité : Senior Développeur JEE
    Secteur : Finance

    Informations forums :
    Inscription : Avril 2002
    Messages : 795
    Points : 1 660
    Points
    1 660
    Par défaut
    J'avais déjà essayé mais le BackGroundImage est toujours null, donc il ne lançait jamais la méthode DrawImage --> le control ne s'affichait pas.

    Le pire c'est que si j'utilise ce control avec un simple form avec un seul panel, il s'affiche et fonctionne normalement.

    C'est simplement depuis que je l'ai inclus dans mon appli principale dans un tabpage que cela foire.

    On dirait que le OnPaint de mon control est appelé lors du SelectedIndexChanged et que mon control n'est pas instancié, alors qu'il l'est.

    Merci malgré tout pour ta suggestion.
    Langages : Java, SQL
    Outils : Eclipse, Intellij
    SGBD : Oracle, PostgreSQL
    Mes Articles

  4. #4
    Membre émérite Avatar de Guulh
    Homme Profil pro
    Inscrit en
    Septembre 2007
    Messages
    2 160
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 42
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Septembre 2007
    Messages : 2 160
    Points : 2 925
    Points
    2 925
    Par défaut
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     this.signatureControlPanel.Controls.Remove(this.signatureControl1);
    signatureControl1 = new NIS_2008.SignatureControl(AppPath, SignatureBackgroundImageFileName);
    Pourquoi supprimes tu puis recrées-tu un contrôle ? As-tu vraiment besoin de créer dynamiquement des contrôles ? Tu ne peux pas te contenter de modifier leurs propriétés ?
    ಠ_ಠ

  5. #5
    Membre expérimenté

    Homme Profil pro
    Senior Développeur JEE
    Inscrit en
    Avril 2002
    Messages
    795
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 49
    Localisation : Belgique

    Informations professionnelles :
    Activité : Senior Développeur JEE
    Secteur : Finance

    Informations forums :
    Inscription : Avril 2002
    Messages : 795
    Points : 1 660
    Points
    1 660
    Par défaut
    Au début je ne créait pas de nouvelle instance de mon contrôle.

    En fait ce qui est visible dans le code maintenant est une suite d'essais qui ont foiré les uns après les autres.

    C'était juste un essai pour voir si en recréant un nouveau contrôle, cela résolvait le problème de NullArgumentException.
    Langages : Java, SQL
    Outils : Eclipse, Intellij
    SGBD : Oracle, PostgreSQL
    Mes Articles

Discussions similaires

  1. [Débutant C#] Onpaint
    Par brv1guizmo dans le forum C#
    Réponses: 3
    Dernier message: 20/05/2008, 16h38
  2. [MFC] Débutant : Problème avec OnPaint()
    Par ZaaN dans le forum MFC
    Réponses: 14
    Dernier message: 05/12/2005, 13h15
  3. [Kylix] Le débutant en Kylix et Linux....
    Par Eclypse dans le forum EDI
    Réponses: 2
    Dernier message: 08/05/2002, 10h37
  4. Réponses: 3
    Dernier message: 07/05/2002, 16h06
  5. [HyperFile] 2 questions de débutant
    Par khan dans le forum HyperFileSQL
    Réponses: 2
    Dernier message: 29/04/2002, 23h18

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo