简体   繁体   中英

Why does this code work on Windows 7, but doesn't on Windows XP?

A little background: I'm a WPF to WinForms convertee and for some time I've been migrating my application.

I was reported by a friend that my code doesn't work on Windows XP (it generates a stack overflow at startup) even though it works fine on Windows 7 (which I develop in).

After a little research, what caused the problem was something along these lines:

 private void listView1_SelectedIndexChanged(object sender, EventArgs e)
 {
     listView1.SelectedIndices.Clear();
     listView1.Items[0].Selected = true;
 }

Now that I noticed the obviously poor decision, I wasn't wondering why it doesn't work on Windows XP. I was wondering why does it work on Windows 7 .

Obviously at some point the compiler figures out what I'm trying to do and prevents the same event to be fired over and over again, but I'd much rather have it do nothing, so I can see and squish the bug on sight on the platform I'm developing in, rather than have to test it under two platforms simultaneously. Back in WPF I could handle such behaviour manually by setting e.Handled to 'true', in WinForms apparently there's no such thing.

Is there some sort of a compiler flag for this?

Try this:

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
   if (!listView1.Items[0].Selected) {
       listView1.SelectedIndices.Clear();
       listView1.Items[0].Selected = true;
   }
}

You only want to SET selection ONCE, on your first item. The problem is it's likely getting into a perpetual loop.

As to why Windows 7 is more forgiving than XP I couldn't say. Could be the order the LVM_* messages are processed in or anything.

Check and see if the .NET version makes any difference. If you have a newer version of .NET on your Windows 7 machine than on XP (very likely), then it is possible for there to be differences even if you are targeting the earlier version.

See what MSDN says about .NET backwards compatibility .

this may work (NOT TESTED)

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
   if(Environment.OSVersion.Version.Major < 6) listview1.SelectedIndexChanged -= new EventHandler(listView1_SelectedIndexChanged);
   listView1.SelectedIndices.Clear();
   listView1.Items[0].Selected = true;
   if(Environment.OSVersion.Version.Major < 6) listview1.SelectedIndexChanged += new EventHandler(listView1_SelectedIndexChanged);
}

edit look its OS specific :o

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM