Truex had dominated most of the race, but Hamlin had gone to the front when his car hooked up under the first sunshine of the afternoon. Truex mounted a comeback, diving low with a couple laps left, but he couldn't make the move stick, and Hamlin pulled away.
He coaxed his Joe Gibbs Racing Toyota the rest of the way for his second win this season.
Truex wound up leading a race-high 173 laps but had to settle for second, his third top-5 finish of the season. He still hasn't won in 175 Sprint Cup races.
Jimmie Johnson finished third for Hendrick Motorsports, which has failed in 14 tries to win the team's milestone 200th race. Dale Earnhardt Jr. and Kasey Kahne also finished in the top 10.
"I was just watching from the third spot, hoping those guys would give me an opportunity," Johnson said. "I just wish I was closer to those guys to race for it."
Hamlin's best finish at Kansas Speedway was third last year, and for most of Sunday he was content to ride around during long green-flag runs away from the spotlight.
He kept getting better with each stop, though, and his car seemed to hook up after the final one, when the sun finally broke through on a blustery, overcast day.
Truex said that his final set of tires may have cost him. He was looser than he had been all afternoon with the final set, and that allowed Hamlin to build enough of a buffer to hold off his final charge. Truex was five lengths down with five laps left, but pulled even with two to go.
"I guess if we can be this frustrated with second, it tells you how close we are as a team," said Truex, who hasn't won since Dover in 2007. "The race car was really good. I'm just not really sure what to think about that last set of tires. I was just wrecking-loose that last set."
Truex called the performance a statement win for Michael Waltrip Racing.
Hamlin is starting to have a statement season.
He won earlier this year at Phoenix, started on the pole at California, and led 31 laps a couple weeks ago at Martinsville before finishing sixth. He was 12th last week at Texas.
Matt Kenseth finished fourth despite having a wild afternoon trying to get into the pits, often sliding across the commitment line. Greg Biffle followed up his victory last week with a fifth-place run, although he conceded he didn't have the car to contend for the win.
Kevin Harvick was sixth, followed by Earnhardt and Kahne, giving Hendrick Motorsports at least three cars in the top 10 for the second straight week. Jeff Gordon had engine trouble late in the race and finished 21st.
The 14-race drought for Hendrick Motorsports is the longest since going 15 races without a win during the 2002 and '03 seasons. The streak began after Johnson's win last October at Kansas.
Carl Edwards took another step in the right direction with a ninth-place finish at what he considers his home track. Kyle Busch rounded out the top 10 and was followed by Brad Keselowski, Juan Pablo Montoya, Tony Stewart, Jamie McMurray and Joey Logano.